在 AWS Elastic Beanstalk 設定 NGINX

聽到一個需求是想要在 Beanstalk 上面設定 NGINX 的參數如 client_max_body_size 100M

這位使用者原本想要直接到機器設定 NGINX 的檔案,我就建議他不要,因為這樣如果新的機器部署會吃不到檔案,應該使用正規的方法部署 NGINX 的 conf,才可以達到每次程式做自動擴展的時候可以吃到參數。

觀察 Beanstalk 預設檔案

在說明要怎麼設定前可以先參考一下 Beanstalk 預設的 nginx.conf,可以看到如果要設定上面的參數我們應該把檔案設定在 /etc/nginx/conf.d 的資料夾裡面,因為它在中間有使用 include /etc/nginx/conf.d/*.conf;,會把所有的檔案都讀進去

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

# Load dynamic modules. See /usr/share/nginx/README.fedora.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

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

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

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

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    index   index.html index.htm;

    server {
        listen       80 ;
        listen       [::]:80 ;
        server_name  localhost;
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
        }

        # redirect server error pages to the static page /40x.html
        error_page 404 /404.html;
            location = /40x.html {
        }

        # redirect server error pages to the static page /50x.html
        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }
}

設定 NGINX conf.d 參數

在 Beanstalk 裏面它提供了一個 .platform 的資料夾,而 NGINX 的設定檔可以直接放進去因此要設定 NGINX 的參數可以把檔案放在 .platform/nginx/conf.d/myconf.conf 其他其實就跟平常使用 conf.d 一樣

client_body_buffer_size 100M;
client_max_body_size 100M;
proxy_buffering off;
proxy_buffer_size 128k;
proxy_buffers 100 128k;

資料夾結構

所以以 JAVA 來說它的結構會長成

~/my-app/
|-- web.jar
`-- .platform/
    `-- nginx/                # Proxy configuration
        |-- nginx.conf
        `-- conf.d/
            `-- custom.conf

把程式整個打包準備上傳到 Beanstalk

在 Beanstalk 上傳檔案如果使用手動需要把它打包成 deploy.zip,可以使用以下兩個指令

如果使用 git 可以使用

git archive -v -o deploy.zip --format=zip

如果沒有使用 zip 指令

zip ./deploy.zip -r * .[^.]*

參考資料

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