部署Django到AWS Elastic Beanstalk遇502 Bad Gateway报错求助
我已经在网上找了各种解决方案,试了多种方法还是没头绪。我想把原生Django项目部署到AWS Elastic Beanstalk(AWS EB),作为新手肯定漏了简单配置。我跟着官方教程、YouTube教程和Stack帖子操作,还是解决不了这个502错误。
我的配置情况
- 项目结构:根目录包含ebdjango项目文件夹、.ebextensions文件夹、requirements.txt等文件
- django.config(位于
.ebextensions目录):
option_settings: aws:elasticbeanstalk:container:python: WSGIPath: ebdjango.wsgi:application
- config.yml:
branch-defaults: default: environment: django-env2 group_suffix: null global: application_name: django-tut branch: null default_ec2_keyname: null default_platform: Python 3.9 default_region: us-west-2 include_git_submodules: true instance_profile: null platform_name: null platform_version: null profile: eb-cli repository: null sc: null workspace_type: Application
- Settings.py修改:
ALLOWED_HOSTS = ['django-env2.eba-wftrfqr2.us-west-2.elasticbeanstalk.com']
- requirements.txt:
asgiref==3.7.2 Django==3.1.3 pytz==2023.3.post1 sqlparse==0.4.4 typing_extensions==4.8.0
本地运行情况
本地服务器运行正常,能看到Django默认页面(修改ALLOWED_HOSTS前的状态)。
错误信息
控制台环境状态变为“Severe”,警告事件:
Environment health has transitioned from Pending to Severe. ELB processes are not healthy on all instances. None of the instances are sending data. 50.0 % of the requests to the ELB are failing with HTTP 5xx. Insufficient request rate (2.0 requests/min) to determine application health (4 minutes ago). ELB health is failing or not available for all instances.
日志标签页无内容,已经困扰多日,求帮助。
排查与解决方案
1. 验证WSGI路径正确性
确认ebdjango.wsgi:application和实际项目结构匹配:
- 检查根目录下的项目文件夹是否确实为
ebdjango,且内部存在wsgi.py文件,文件中定义了application对象 - 如果项目结构是
根目录/ebdjango/ebdjango/wsgi.py,则WSGIPath需改为ebdjango/ebdjango/wsgi:application
2. 调整ALLOWED_HOSTS配置
先放宽配置测试,避免域名匹配问题:
ALLOWED_HOSTS = ['*']
测试正常后,再改回精准配置:
ALLOWED_HOSTS = ['django-env2.eba-wftrfqr2.us-west-2.elasticbeanstalk.com', '.elasticbeanstalk.com']
3. 拉取完整日志排查
EB控制台日志为空时,用EB CLI拉取全量日志:
eb logs --all
重点查看:
/var/log/httpd/error_log:Apache错误日志,可定位WSGI启动失败原因/var/log/web.stdout.log:Django应用日志,检查应用启动报错
4. 检查依赖兼容性
当前EB平台为Python 3.9,Django 3.1.3虽支持该版本,但建议升级到更稳定的LTS版本:
Django==3.2.25
5. 配置静态文件(可选)
若后续涉及静态文件,需添加以下配置:
- 在Settings.py中添加:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
- 在
.ebextensions/django.config中补充静态文件映射:
option_settings: aws:elasticbeanstalk:container:python: WSGIPath: ebdjango.wsgi:application aws:elasticbeanstalk:container:python:staticfiles: /static/: static/
6. 检查EC2实例状态
进入EC2控制台,查看对应实例的状态检查是否通过;若实例启动失败,通过「操作→监控→获取系统日志」排查启动错误。
内容的提问来源于stack exchange,提问作者Ronan Jones

