AWS Elastic Beanstalk中Nginx配置未生效及504超时问题排查
问题背景
我的Elastic Beanstalk Web应用运行60秒后就会出现504错误,已经把/etc/nginx/nginx.conf里的各类超时参数改成了90,还按照日志提示把types_hash_max_size设为1024,但还是收到types_hash相关的警告。
修改后的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 200000; events { worker_connections 1024; } http { server_tokens off; 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 { listen 80 default_server; access_log /var/log/nginx/access.log main; client_header_timeout 90; client_body_timeout 90; keepalive_timeout 90; proxy_connect_timeout 90; proxy_send_timeout 90; proxy_read_timeout 90; send_timeout 90; types_hash_max_size 1024; 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; } }
日志警告内容
[warn] 13416#13416: 无法构建最优的types_hash,你应该增大types_hash_max_size(当前1024)或types_hash_bucket_size(当前64);忽略types_hash_bucket_size
排查与修复方案
一、Nginx配置的问题
types_hash_max_size放错位置了
你现在把types_hash_max_size写在server块里,但这个参数是Nginx的全局配置,必须放在http块下才会生效。把它移到http块里,比如紧跟在include /etc/nginx/mime.types;之后就行。同时调整
types_hash_bucket_size
如果调大types_hash_max_size到1024还是有警告,可以同时在http块里加上types_hash_bucket_size 128;(默认是64,翻倍调整基本就能解决)。修改后的http块片段:http { server_tokens off; include /etc/nginx/mime.types; default_type application/octet-stream; types_hash_max_size 1024; types_hash_bucket_size 128; # 其他原有配置... }别直接改默认配置文件,会被覆盖
Elastic Beanstalk重启实例或者重新部署时,直接修改的/etc/nginx/nginx.conf会被系统重置。正确做法是用.ebextensions配置来持久化修改:- 在项目根目录创建
.ebextensions/nginx/conf.d/custom.conf文件 - 在这个文件里添加需要的配置,比如全局的超时和types_hash参数:
http { types_hash_max_size 1024; types_hash_bucket_size 128; proxy_connect_timeout 90; proxy_send_timeout 90; proxy_read_timeout 90; client_header_timeout 90; client_body_timeout 90; keepalive_timeout 90; send_timeout 90; }
这样部署时系统会自动把这些配置合并到Nginx的主配置里,不会被覆盖。
- 在项目根目录创建
二、重点排查的日志
Nginx核心日志
/var/log/nginx/error.log:能看到Nginx的配置错误、超时触发的具体细节/var/log/nginx/access.log:查504请求的具体路径、客户端信息,确认是不是特定请求导致的超时
应用程序日志
/var/log/web.stdout.log:应用的标准输出,看应用处理请求时是不是真的跑了60秒以上,有没有卡住的情况/var/log/web.stderr.log:应用的错误输出,排查有没有代码层面的异常导致请求处理缓慢
AWS层面的关键日志与配置
- CloudWatch日志:在AWS控制台找对应Elastic Beanstalk环境的日志组,里面聚合了所有相关日志,方便搜索和回溯
- ELB超时配置:这很可能是你遇到60秒504的核心原因!Elastic Beanstalk默认的负载均衡器空闲超时是60秒,就算你改了Nginx的90秒,ELB到点就会断开连接返回504。需要在Elastic Beanstalk控制台的环境配置里,把负载均衡器的空闲超时改成90秒,和Nginx的参数匹配。
内容的提问来源于stack exchange,提问作者alangap23

