配置代理服务器 - 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

以下示例将删除默认配置并添加一个将流量转发到端口 5000 (而不是 8081) 的自定义配置。

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 在每次配置部署期间都会重新创建默认配置。考虑到这一点,在下列示例中,添加了一个配置后部署挂钩 (/opt/elasticbeanstalk/hooks/configdeploy/post/99_kill_default_nginx.sh)。这删除了默认配置并重新启动代理服务器。

注意

在 Node.js 平台将来的版本中,默认配置可能会发生更改。请使用该配置的最新版本作为您自定义的基础,以确保兼容性。

如果要覆盖默认配置,您必须定义任何静态文件映射和 GZIP 压缩。这是因为平台无法应用标准设置