使用Gunicorn绑定0.0.0.0:8000无法访问服务的问题求助
问题描述
执行python manage.py runserver 0.0.0.0:8000时,可通过域名和IP正常HTTP访问服务;但执行gunicorn --bind 0.0.0.0:8000 core.wsgi后,使用wget http://server_ip:8000或wget 127.0.0.1:8000测试,进程卡在“Connecting to 127.0.0.1:8000... connected. HTTP request sent, awaiting response...”。
当前UFW防火墙规则:
To Action From
Nginx Full ALLOW Anywhere
22/tcp ALLOW Anywhere
8000 ALLOW Anywhere
Nginx Full (v6) ALLOW Anywhere (v6)
22/tcp (v6) ALLOW Anywhere (v6)
8000 (v6) ALLOW Anywhere (v6)
排查与解决步骤
查看Gunicorn实时日志
启动Gunicorn时添加日志输出参数,直接打印请求和错误信息:gunicorn --bind 0.0.0.0:8000 core.wsgi --access-logfile - --error-logfile -观察是否有报错(如Django配置错误、依赖缺失、数据库连接超时等)。
验证WSGI模块路径正确性
确认项目根目录下存在core文件夹,且该文件夹内有wsgi.py文件。若项目结构不同(比如WSGI文件在myproject/wsgi.py),需将启动命令改为gunicorn --bind 0.0.0.0:8000 myproject.wsgi。确保加载正确的Django环境
- 若使用虚拟环境,先激活环境再启动Gunicorn:
source venv/bin/activate gunicorn --bind 0.0.0.0:8000 core.wsgi - 手动指定Django配置模块:
export DJANGO_SETTINGS_MODULE=core.settings gunicorn --bind 0.0.0.0:8000 core.wsgi
- 若使用虚拟环境,先激活环境再启动Gunicorn:
检查端口监听状态
使用以下命令确认8000端口是否被Gunicorn正确监听,且监听地址为0.0.0.0(允许外部访问):ss -tulpn | grep 8000排查服务器资源瓶颈
用top或htop查看CPU、内存占用情况,若资源耗尽会导致Gunicorn无法处理请求。测试最简视图排除业务代码问题
创建一个无依赖的测试视图:# 在urls.py中添加 from django.http import HttpResponse def test(request): return HttpResponse("Hello World") urlpatterns = [ # 原有路由 path('test/', test), ]重启Gunicorn后访问
http://server_ip:8000/test/,若能正常返回则说明问题出在业务代码中,需逐步排查。
内容的提问来源于stack exchange,提问作者SAVEPALASTINE

