設定代理伺服器 - AWS Elastic Beanstalk

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

設定代理伺服器

Elastic Beanstalk 可以使用 NGINX 或 Apache HTTPD 做為反向代理伺服器,在連接埠 80 上將您的應用程式映射到 Elastic Load Balancing 負載平衡器。預設值為 NGINX。Elastic Beanstalk 提供了預設的代理組態,您可以加以擴展,或使用自己的組態將其完全覆寫。

Elastic Beanstalk 預設會設定代理將請求轉送至連接埠 5000 上的應用程式。您可將 PORT 環境屬性設定為主要應用程式接聽的連接埠,藉此覆寫預設連接埠。

注意

您應用程式接聽的連接埠,不會影響 NGINX 伺服器為接收來自負載平衡器的請求所接聽的連接埠。

在您的平台版本上設定代理伺服器

所有 AL2023/AL2 平台皆支援統一的代理組態功能。如需有關在執行 AL2023/AL2 的平台版本上設定代理伺服器的詳細資訊,請展開擴充 Elastic Beanstalk Linux 平台中的反向代理組態一節。

如果您的 Elastic Beanstalk Node.js 環境使用 Amazon Linux AMI 平台版本 (先前的 Amazon Linux 2),請閱讀本節中的資訊。

備註

Node.js 平台使用反向代理程式,將執行個體上來自 80 通訊埠的請求,轉傳給接聽 8081 埠的應用程式。Elastic Beanstalk 提供了預設的代理組態,您可以加以擴展,或使用自己的組態將其完全覆寫。

若要擴展預設的組態,請利用組態檔案,將 .conf 檔案加入至 /etc/nginx/conf.d。如需特定範例,請參閱 在執行 Node.js 的 EC2 執行個體上終止 HTTPS

Node.js 平台會將 PORT 環境變數設定為代理伺服器傳送流量至其中的連接埠。在您的程式碼中讀取此變數,以設定您應用程式的連接埠。

var port = process.env.PORT || 3000; var server = app.listen(port, function () { console.log('Server running at http://127.0.0.1:' + port + '/'); });

預設的 NGINX 組態會將流量轉發至位於 127.0.0.1:8081,名為 nodejs 的上游伺服器。您可以移除預設的組態,並在組態檔案中提供自己的組態。

範例 .ebextensions/proxy.config

下列的範例移除了預設的組態,並新增自訂組態,來將流量轉傳到 5,000 埠而非 8,081 埠。

files: /etc/nginx/conf.d/proxy.conf: mode: "000644" owner: root group: root content: | upstream nodejs { server 127.0.0.1:5000; keepalive 256; } server { listen 8080; if ($time_iso8601 ~ "^(\d{4})-(\d{2})-(\d{2})T(\d{2})") { set $year $1; set $month $2; set $day $3; set $hour $4; } access_log /var/log/nginx/healthd/application.log.$year-$month-$day-$hour healthd; access_log /var/log/nginx/access.log main; location / { proxy_pass http://nodejs; proxy_set_header Connection ""; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } gzip on; gzip_comp_level 4; gzip_types text/html text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript; location /static { alias /var/app/current/static; } } /opt/elasticbeanstalk/hooks/configdeploy/post/99_kill_default_nginx.sh: mode: "000755" owner: root group: root content: | #!/bin/bash -xe rm -f /etc/nginx/conf.d/00_elastic_beanstalk_proxy.conf service nginx stop service nginx start container_commands: removeconfig: command: "rm -f /tmp/deployment/config/#etc#nginx#conf.d#00_elastic_beanstalk_proxy.conf /etc/nginx/conf.d/00_elastic_beanstalk_proxy.conf"

範例組態 (/etc/nginx/conf.d/proxy.conf) 使用了位於 /etc/nginx/conf.d/00_elastic_beanstalk_proxy.conf 的預設組態做為基礎,以納入預設的伺服器區塊,此區塊具備壓縮與日誌設定,和靜態檔案映射。

removeconfig 命令會移除容器的預設組態,因此代理伺服器使用自訂組態。Elastic Beanstalk 會在部署每個組態時,重新建立預設組態。為了說明此點,在下列範例中,新增了 post-configuration-deployment hook (/opt/elasticbeanstalk/hooks/configdeploy/post/99_kill_default_nginx.sh)。這會移除預設配置,並重新啟動代理伺服器。

注意

在 Node.js 平台的未來版本中,預設組態可能會變更。請使用最新版本的組態來做為您自訂項目的基礎,以確保相容性。

如果您覆寫預設組態,則必須定義所有靜態檔案映射和 GZIP 壓縮。這是因為平台無法套用標準設定