You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AWS EC2 Ubuntu实例重启后Nginx报502 Bad Gateway错误排查求助

Ubuntu EC2重启后Nginx 502 Bad Gateway错误解决

问题概述

重启Ubuntu EC2实例后网站出现Nginx 502 Bad Gateway错误,重启前未修改任何配置,此前运行正常。

关键信息

Nginx错误日志(/var/log/nginx/error.log)

2022/12/06 21:10:54 [error] 1503#1503: *4 connect() failed (111: Unknown error) while connecting to upstream, client: ###.##.##.###, server: ##.#.###.###, request: "GET /favicon.ico HTTP/1.1", upstream: "http://127.0.0.1:8000/favicon.ico", host: "##.#.###.###", referrer: "http://##.#.###.###/"

Nginx站点配置(/etc/nginx/sites-available/)

server_tokens               off;
access_log                  /var/log/nginx/esms.access.log;
error_log                   /var/log/nginx/esms.error.log;

# This configuration will be changed to redirect to HTTPS later
server {
  server_name               .##.#.###.###;
  listen                    80;
  location / {
    proxy_pass              http://127.0.0.1:8000;
    proxy_set_header        Host $host;
  }
  location /static {
    autoindex on;
    alias /home/ubuntu/ESMS/esms/static/;
  }
}

端口监听状态(netstat -plnt)

sudo netstat -plnt
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      664/sshd: /usr/sbin 
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      1567/nginx: master  
tcp        0      0 127.0.0.53:53           0.0.0.0:*               LISTEN      420/systemd-resolve 
tcp6       0      0 :::22                   :::*                    LISTEN      664/sshd: /usr/sbin 
tcp6       0      0 :::80                   :::*                    LISTEN      1567/nginx: master  

问题原因

从日志和端口状态可明确:运行在127.0.0.1:8000的后端服务未启动,Nginx无法连接上游服务,因此返回502错误。重启实例后,该后端服务未自动启动。

解决步骤

1. 检查后端服务状态

  • 若用systemd管理服务,执行:
    systemctl status your-service-name
    
  • 若为手动启动进程,执行:
    ps aux | grep python
    
    替换为你的服务进程名称,排查是否有对应进程运行。

2. 启动后端服务

  • 以Django+Gunicorn为例,进入项目目录执行:
    cd /home/ubuntu/ESMS
    gunicorn esms.wsgi:application --bind 127.0.0.1:8000
    
  • 若为systemd服务,执行:
    systemctl start your-service-name
    

3. 设置开机自启

避免下次重启后问题复发:

  • systemd服务执行:
    systemctl enable your-service-name
    
  • 若为手动启动脚本,可将启动命令添加到/etc/rc.local(Ubuntu 18.04+需先启用rc-local服务),或通过crontab添加@reboot任务:
    crontab -e
    
    在文件末尾添加:
    @reboot cd /home/ubuntu/ESMS && gunicorn esms.wsgi:application --bind 127.0.0.1:8000
    

4. 验证修复

  • 再次执行netstat -plnt,确认127.0.0.1:8000处于LISTEN状态
  • 访问网站,确认502错误消失

内容的提问来源于stack exchange,提问作者tmorgan497

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 03:05:42