How to config elastic beanstalk laravel
  1. Home
  2. Chuyện coding
  3. How to config elastic beanstalk laravel
Admin 10 tháng trước

How to config elastic beanstalk laravel

Config .ebextensions

Ref: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environment-configuration-methods-before.html#configuration-options-before-ebextensions

  1. Config timezone

Create file 01_timezone.config

Exp: set time zone Asia/Tokyo

commands:
set_time_zone:
command: ln -f -s /usr/share/zoneinfo/Asia/Tokyo /etc/localtime

2. Config push log Laravel to Cloudwatch logs

Create file 02_logs.config

files:
  "/opt/aws/amazon-cloudwatch-agent/bin/config.json":
    mode: "000755"
    owner: root
    group: root
    content: |
      {
        "agent": {
          "run_as_user": "root"
        },
        "logs": {
          "logs_collected": {
            "files": {
              "collect_list": [
                {
                  "file_path": "/var/log/messages",
                  "log_group_name": "`{"Fn::Join":["/", ["/aws/elasticbeanstalk", { "Ref":"AWSEBEnvironmentName" }, "var/log/messages"]]}`",
                  "log_stream_name": "{instance_id}"
                },
                {
                  "file_path": "/var/app/current/storage/logs/laravel.log",
                  "log_group_name": "`{"Fn::Join":["/", ["/aws/elasticbeanstalk", { "Ref":"AWSEBEnvironmentName" }, "laravel.log"]]}`",
                  "log_stream_name": "{instance_id}"
                }
              ]
            }
          }
        }
      }

container_commands:
  01_install_cloudwatch_agent:
    command: |
      dnf install -y amazon-cloudwatch-agent
  02_configure_cloudwatch_agent:
    command: |
      /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -s -c file:/opt/aws/amazon-cloudwatch-agent/bin/config.json
  03_start_cloudwatch_agent:
    command: |
      systemctl enable amazon-cloudwatch-agent
      systemctl start amazon-cloudwatch-agent

Config .platform

Ref: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/platforms-linux-extend.html

  1. Create laravel.ini in folder “.platform/files”
; Set timezone Tokyo
date.timezone=Asia/Tokyo
; Determines if Zend OPCache is enabled
opcache.enable=1
; Set post max size, upload max filesize
post_max_size = 200M;
upload_max_filesize = 200M;
; New max excute time
max_execution_time = 300
; New Limit
memory_limit = 4096M
; Determines if Zend OPCache is enabled for the CLI version of PHP
opcache.enable_cli=1

; The OPcache shared memory storage size.
opcache.memory_consumption=512

; The amount of memory for interned strings in Mbytes.
opcache.interned_strings_buffer=128

; The maximum number of keys (scripts) in the OPcache hash table.
; Only numbers between 200 and 1000000 are allowed.
opcache.max_accelerated_files=1000000

; maximum memory allocated to store the results
realpath_cache_size=8192K

; save the results for 10 minutes (600 seconds)
realpath_cache_ttl=600

; The maximum percentage of "wasted" memory until a restart is scheduled.
opcache.max_wasted_percentage=5

; When this directive is enabled, the OPcache appends the current working
; directory to the script key, thus eliminating possible collisions between
; files with the same name (basename). Disabling the directive improves
; performance, but may break existing applications.
;opcache.use_cwd=1

; When disabled, you must reset the OPcache manually or restart the
; webserver for changes to the filesystem to take effect.
opcache.validate_timestamps=0

; How often (in seconds) to check file timestamps for changes to the shared
; memory storage allocation. ("1" means validate once per second, but only
; once per request. "0" means always validate)
opcache.revalidate_freq=0

; Enables or disables file search in include_path optimization
;opcache.revalidate_path=0

; If disabled, all PHPDoc comments are dropped from the code to reduce the
; size of the optimized code.
;opcache.save_comments=1

; If enabled, a fast shutdown sequence is used for the accelerated code
; Depending on the used Memory Manager this may cause some incompatibilities.
opcache.fast_shutdown=1

; Allow file existence override (file_exists, etc.) performance feature.
;opcache.enable_file_override=0

; A bitmask, where each bit enables or disables the appropriate OPcache
; passes
;opcache.optimization_level=0xffffffff

;opcache.inherited_hack=1
;opcache.dups_fix=0

; The location of the OPcache blacklist file (wildcards allowed).
; Each OPcache blacklist file is a text file that holds the names of files
; that should not be accelerated.
opcache.blacklist_filename=/etc/php-8.2.d/opcache*.blacklist

; Allows exclusion of large files from being cached. By default all files
; are cached.
;opcache.max_file_size=0

; Check the cache checksum each N requests.
; The default value of "0" means that the checks are disabled.
;opcache.consistency_checks=0

; How long to wait (in seconds) for a scheduled restart to begin if the cache
; is not being accessed.
;opcache.force_restart_timeout=180

; OPcache error_log file name. Empty string assumes "stderr".
;opcache.error_log=

; All OPcache errors go to the Web server log.
; By default, only fatal errors (level 0) or errors (level 1) are logged.
; You can also enable warnings (level 2), info messages (level 3) or
; debug messages (level 4).
;opcache.log_verbosity_level=1

; Preferred Shared Memory back-end. Leave empty and let the system decide.
;opcache.preferred_memory_model=

; Protect the shared memory from unexpected writing during script execution.
; Useful for internal debugging only.
;opcache.protect_memory=0

; Allows calling OPcache API functions only from PHP scripts which path is
; started from specified string. The default "" means no restriction
;opcache.restrict_api=

; Enables and sets the second level cache directory.
; It should improve performance when SHM memory is full, at server restart or
; SHM reset. The default "" disables file based caching.
; RPM note : file cache directory must be owned by process owner
;   for mod_php, see /etc/httpd/conf.d/php.conf
;   for php-fpm, see /etc/php-fpm.d/*conf
;opcache.file_cache=

; Enables or disables opcode caching in shared memory.
;opcache.file_cache_only=0

; Enables or disables checksum validation when script loaded from file cache.
;opcache.file_cache_consistency_checks=1

; Implies opcache.file_cache_only=1 for a certain process that failed to
; reattach to the shared memory (for Windows only). Explicitly enabled file
; cache is required.
;opcache.file_cache_fallback=1

; Validate cached file permissions.
; Leads OPcache to check file readability on each access to cached file.
; This directive should be enabled in shared hosting environment, when few
; users (PHP-FPM pools) reuse the common OPcache shared memory.
;opcache.validate_permission=0

; Prevent name collisions in chroot'ed environment.
; This directive prevents file name collisions in different "chroot"
; environments. It should be enabled for sites that may serve requests in
; different "chroot" environments.
;opcache.validate_root=0

; Enables or disables copying of PHP code (text segment) into HUGE PAGES.
; This should improve performance, but requires appropriate OS configuration.
opcache.huge_code_pages=1

2. Create 01_run_caches.sh in folder “.platform/hooks/postdeploy”


#!/bin/bash

# Run Caches

# After the deployment, it's highly recommended
# to re-run the caches for config, routes and views.
# sudo -uwebapp sh -c "php artisan config:clear"
# sudo -uwebapp sh -c "php artisan cache:clear"
sudo -uwebapp sh -c "php artisan optimize:clear"
sudo -uwebapp sh -c "php artisan optimize"

3. Create 02_make_folders_writable.sh in folder “.platform/hooks/postdeploy”


#!/bin/sh

# Make Folders Writable

# After the deployment finished, give the full 0777 permissions
# to some folders that should be writable, such as the storage/
# or bootstrap/cache/, for example.

sudo chmod -R 777 storage/
sudo chmod -R 777 bootstrap/cache/

4. Create config_opcache.sh in folder “.platform/hooks/prebuild”


#!/bin/sh

# Add custom configuration to PHP

# The .platform/files/laravel.ini files contains enabled OP-cache
# configuration. Feel free to edit it in case you want custom configuration.

sudo cp .platform/files/laravel.ini /etc/php.d/laravel.ini

5. Create restart_services in folder “.platform/hooks/predeploy”


#!/bin/sh

sudo systemctl reload php-fpm.service
sudo systemctl reload nginx.service

exit 0

6. Create nginx.conf in folder “.platform/nginx”


#Elastic Beanstalk Nginx Configuration File

user                    nginx;
error_log               /var/log/nginx/error.log warn;
pid                     /var/run/nginx.pid;
worker_processes        auto;
worker_rlimit_nofile    65729;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    include       conf.d/*.conf;

    map $http_upgrade $connection_upgrade {
        default     "upgrade";
    }

    server_tokens off;

    server {
        listen        80 default_server;
        access_log    /var/log/nginx/access.log main;

        # Basic auth:
        # auth_basic              "Closed site";
        # auth_basic_user_file    conf.d/.htpasswd;

        client_header_timeout 240;
        client_body_timeout   240;
        keepalive_timeout     240;
        gzip                  off;
        gzip_comp_level       4;
        gzip_types text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript;

        # Include the Elastic Beanstalk generated locations
        include conf.d/elasticbeanstalk/*.conf;
    }
}

7. Create laravel.conf in folder “.platform/nginx/conf.d/elasticbeanstalk”


# DO NOT set any root here because the root
# is automatically handled by Amazon.

#add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";

charset utf-8;

location / {
  ## Cors:
  add_header 'Access-Control-Allow-Origin' '*';
  add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
  add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
  add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';

  # Authen:
  # auth_basic              "Closed site";
  # auth_basic_user_file    conf.d/.htpasswd;

  try_files $uri $uri/ /index.php?$query_string;

}

location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt  { access_log off; log_not_found off; }

#error_page 404 /index.php;

location ~ /\.(?!well-known).* {
  deny all;
}

20 lượt xem | 0 bình luận
Tác giả vẫn chưa cập nhật trạng thái

Avatar