Docker化Django+Nginx+Gunicorn连接异常问题求助
Hey there, let's troubleshoot your Dockerized Django+Nginx+Gunicorn setup step by step. The "connection failed" issue when accessing http://example.dj usually boils down to network misconfigurations, incorrect proxy settings, or service startup problems. Here’s what to check first:
1. Confirm Docker Compose Network & Gunicorn Binding
- Make sure your Django/Gunicorn service and Nginx are on the same Docker network. By default, Docker Compose creates a shared network for all services in the file, but double-check that neither service is explicitly assigned to a separate network.
- Critical: Gunicorn must bind to
0.0.0.0:8000(not127.0.0.1:8000). The loopback address127.0.0.1only works inside the Django container—Nginx can’t reach it across containers. Your Gunicorn startup command should look like this:gunicorn your_project.wsgi:application --bind 0.0.0.0:8000
2. Validate Nginx Proxy Configuration
- Ensure your
nginx.confuses the Docker service name (notlocalhost) for theproxy_passdirective. If your Django service is namedwebindocker-compose.yml, the proxy rule should be:server { listen 80; server_name example.dj; location / { proxy_pass http://web:8000; # Use the Docker service name here 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_set_header X-Forwarded-Proto $scheme; } } - Verify the Nginx container’s port mapping in
docker-compose.ymlis set to"80:80"—this forwards traffic from your host’s port 80 to the Nginx container’s port 80.
3. Check Hosts File Accuracy
- Confirm your
/etc/hostsentry is correct:127.0.0.1 example.dj - Test the DNS resolution with
ping example.djon your host machine—you should see it resolve to127.0.0.1.
4. Inspect Service Logs & Status
- Check if all containers are running:
Look for "Up" status under both the Django and Nginx services.docker-compose ps - Check Gunicorn logs to confirm it’s listening correctly:
You should see a line likedocker-compose logs webListening at: http://0.0.0.0:8000. - Check Nginx logs for connection errors:
Messages likedocker-compose logs nginxconnection refusedmean Nginx can’t reach Gunicorn—this points to a network or binding issue.
5. Test Direct Access to Gunicorn
- Bypass Nginx temporarily to rule out Django/Gunicorn issues. If your Django service has a port mapping like
"8000:8000", visithttp://localhost:8000on your host. If the Django welcome page loads, the problem is isolated to Nginx or proxy configuration.
If you’ve gone through all these steps and still can’t connect, share snippets of your docker-compose.yml and nginx.conf (redact sensitive info) and we can dig deeper!
内容的提问来源于stack exchange,提问作者Михаил Павлов
相关产品推荐
相关产品推荐

