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

DigitalOcean上Django+Selenium应用(gunicorn/nginx)502超时问题咨询

解决Nginx 502 Bad Gateway(超时)问题:延长响应等待时间的步骤

哥们,我之前刚好处理过类似的Django+Selenium爬取的生产环境问题,你遇到的这个502 Bad Gateway错误,十有八九是因为Nginx等待后端Gunicorn返回响应的时间超过了默认的60秒阈值,而且Gunicorn自身也可能有超时限制拖后腿。下面给你一步步的解决方法,亲测有效:

1. 修改Nginx的超时配置

首先找到你的Nginx站点配置文件,一般在/etc/nginx/sites-available/目录下,比如你的项目配置文件叫your_project.conf。

编辑这个文件,在对应Django应用的location块里(或者整个server块)添加/修改以下关键的超时参数:

  • proxy_read_timeout: Nginx等待后端响应的超时时间,默认是60秒,直接改成你需要的时长(比如300s=5分钟,或者更长)
  • proxy_connect_timeout: 连接Gunicorn服务器的超时时间,建议和上面保持一致
  • proxy_send_timeout: Nginx发送请求给后端的超时时间,同样同步调整
  • client_header_timeout/client_body_timeout: 防止客户端发送请求的过程超时

示例配置片段:

server {
    listen 80;
    server_name your_domain.com;

    location / {
        proxy_pass http://127.0.0.1:8000;  # 这里是你的Gunicorn监听地址
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        # 新增/修改超时配置
        proxy_connect_timeout 300s;
        proxy_send_timeout 300s;
        proxy_read_timeout 300s;
        client_header_timeout 300s;
        client_body_timeout 300s;
    }
}

修改完后,先测试Nginx配置是否合法,避免语法错误:

sudo nginx -t

如果输出显示test is successful,就重启Nginx服务让配置生效:

sudo systemctl restart nginx

2. 调整Gunicorn的超时设置

只改Nginx还不够!Gunicorn自身也有默认超时限制(一般也是60秒),如果它在规定时间内没处理完爬取任务,会主动断开和Nginx的连接,照样会触发502错误。

情况1:直接用命令启动Gunicorn

启动时添加--timeout参数,设置和Nginx一致的时长:

gunicorn your_project.wsgi:application --bind 127.0.0.1:8000 --timeout 300

情况2:用systemd管理Gunicorn(生产环境推荐)

找到Gunicorn的systemd服务文件,一般在/etc/systemd/system/gunicorn.service,编辑ExecStart行,加上--timeout 300:

[Unit]
Description=gunicorn daemon
After=network.target

[Service]
User=your_user
Group=www-data
WorkingDirectory=/path/to/your/project
ExecStart=/path/to/your/venv/bin/gunicorn --access-logfile - --workers 3 --bind 127.0.0.1:8000 --timeout 300 your_project.wsgi:application

[Install]
WantedBy=multi-user.target

然后重载systemd配置并重启Gunicorn:

sudo systemctl daemon-reload
sudo systemctl restart gunicorn

3. 针对Selenium爬取的额外优化建议

虽然延长超时能暂时解决问题,但Selenium爬取是阻塞性的慢操作,长时间占用请求连接并不是最优解,推荐你考虑这些优化方向:

  • 用异步任务队列(比如Celery+Redis):把爬取任务放到后台执行,前端先返回“任务已提交”,之后再通过轮询或WebSocket获取结果,避免长时间占用HTTP连接
  • 优化爬取逻辑:用Selenium的WebDriverWait精准等待元素加载,替换掉time.sleep()这种固定等待,减少不必要的耗时
  • 合理调整Gunicorn的worker数量:根据服务器CPU核心数调整,比如--workers 4(一般是CPU核心数×2+1),但别超过服务器资源上限

内容的提问来源于stack exchange,提问作者B. Okba

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 19:22:28