使用nginx作为反向代理时连接被拒绝,而连接上游

设置如下:我有一个运行在0.0.0.0:8000 ,可通过浏览器访问的Gunicorn / Django应用程序。 为了提供静态文件,我使用nginx作为反向代理。 /etc/nginx/nginx.conf被configuration为转发请求,如下所示:

 server { location /static/ { alias /data/www/; } # Proxying the connections location / { proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_redirect off; proxy_pass http://0.0.0.0:8000; } } 

和我docker-compose.yml文件如下:

 version: '3.3' services: web: restart: always build: ./web expose: - "8000" ports: - "8000:8000" volumes: - staticdata:/usr/src/app/static_files command: gunicorn wsgi:application --workers 2 --bind 0.0.0.0:8000 depends_on: - postgres nginx: restart: always build: ./nginx ports: - "80:80" - "443:443" volumes: - staticdata:/data/www depends_on: - web postgres: image: postgres:9.2 restart: always volumes: - pgdata:/var/lib/postgresql/data ports: - "5432:5432" volumes: staticdata: pgdata: 

当我通过浏览器访问0.0.0.0:8000 ,应用程序工作正常(虽然没有提供静态文件),但是当我访问127.0.0.1:80时,出现以下错误:

 nginx_1 | 2017/09/17 13:59:46 [error] 6#6: *5 connect() failed (111: Connection refused) while connecting to upstream, client: 172.18.0.1, server: , request: "GET / HTTP/1.1", upstream: "http://0.0.0.0:8000/", host: "127.0.0.1" 

我知道这个错误表明在0.0.0.0:8000上运行的服务器不接受请求,但是因为我可以通过浏览器访问它,所以我有点困惑。

先谢谢你。

改变你的proxy_pass

 proxy_pass http://0.0.0.0:8000; 

 proxy_pass http://web:8000; 

您的nginx需要转发请求Web容器

编辑1:说明

0.0.0.0是一个特殊的IP地址,用来指代机器上任何可用的接口。 所以如果你的机器有一个loopback(lo),ethernet(eth0),Wifi(wlan0),其IP地址分别为127.0.0.1

所以现在,当听到传入的连接,你可以select任何上述的IP

 gunicorn wsgi:application --workers 2 --bind 10.0.0.100:8000 

这只能从你的Wifinetworking上获得。 但Lannetworking上的其他机器无法访问它。 所以,如果你想让你的应用程序在机器上的任何可用的networking上进行监听,你可以使用一个特殊的IP 0.0.0.0 。 这意味着绑定在所有networking接口上

 gunicorn wsgi:application --workers 2 --bind 0.0.0.0:8000 

现在,当您使用http://0.0.0.0访问应用程序时,它相当于使用127.0.0.1 。 所以你的proxy_pass http://0.0.0.0:8000; 相当于proxy_pass http://127.0.0.1:8000;

所以当你在nginx容器中运行它的时候,它会在同一个容器的端口8000上传递请求,而在你的nginx容器中没有任何东西在8000上运行。 所以你需要把这个请求发送到你的gunicorn容器。 这可以通过docker-compose的服务名称web访问。

有关更多详细信息,请参阅下面的文章https://docs.docker.com/compose/networking/