2017-02-26 281 views
2

我试图设置容器中的nginx反向代理到另一个容器,我的应用程序正在运行。这里是我的nginx.conf:Docker nginx反向代理返回502坏网关“连接被拒绝,同时连接到上游”

daemon off; 

    user nginx; 
    worker_processes 1; 

    error_log /var/log/nginx/error.log warn; 
    pid  /var/run/nginx.pid; 


    events { 
     worker_connections 1024; 
    } 


    http { 
     include  /etc/nginx/mime.types; 
     default_type application/octet-stream; 

     log_format main '$remote_addr - $remote_user [$time_local] "$request" ' 
         '$status $body_bytes_sent "$http_referer" ' 
         '"$http_user_agent" "$http_x_forwarded_for"'; 

     access_log /var/log/nginx/access.log main; 

     sendfile  on; 

     upstream appserver { 
      server app:3000; 
     } 

     server { 
      listen 80; 
      server_name localhost; 

      location/{ 
       proxy_pass http://appserver/; 
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
       proxy_set_header Host $http_host; 
       proxy_redirect off;   
      } 
     } 
    } 

我的搬运工,compose.yml看起来是这样的:

version: '3' 
services: 
    db: 
    image: postgres 
    redis: 
    image: redis 
    web: 
    build: ./web 
    image: web 
    ports: 
     - "8080:80" 
    app: 
    build: ./app 
    image: app 
    command: puma 
    volumes: 
     - ./app:/app 
    expose: 
     - "3000" 
    ports: 
     - "3000:3000" 
    depends_on: 
     - db 
     - redis 
     - web 

的Dockerfile为反向代理只是拷贝配置文件并启动Nginx的服务。这是我的问题:

当访问主机浏览器上的localhost:8080时,nginx返回502 Bad Gateway。日志显示“web_1 | 2017/02/26 22:55:15 [错误] 12#12:* 1连接()失败(111:连接拒绝)连接到上游时,客户端:172.25.0.1,服务器:localhost,请求:“GET/HTTP/1.1”,上游:“http://127.0.53.53:3000/”,主机:“localhost:8080” web_1 | 172.25.0.1 - - [26/Feb/2017:22:55:15 +0000]“GET/HTTP /1.1“502 576” - “”Mozilla/5.0(Windows NT 10.0; Win64; x64)AppleWebKit/537.36(KHTML,如Gecko)Chrome/56.0.2924.87 Safari/537.36“” - “”

现在马上我在想,nginx无法访问我的应用程序容器,但是,在“web”容器中运行“curl app:3000”会返回正确的响应。端口转发时,我还可以直接在端口3000上访问应用程序。所以我觉得这个问题与我的nginx.conf文件是如何访问资源的。我一直在我的头上撞墙。有任何想法吗?

+0

我不知道“上游:”http://127.0.53.53:3000/“”来自日志中的错误消息。 nslookup返回'app'的正确IP为172.25.0。* – adam

+0

你的'web'容器不应该取决于'app'容器,而不是其他方式?您可能在开机时看到错误。 – jkinkead

+0

@jkinkead确实是这个问题。切换它们可以立即开始工作。谢谢。 – adam

回答

0

重写docker-compose.yml,通过确保应用程序在nginx反向代理之前启动,从而减轻了问题的发生。

version: '3' 
services: 
    db: 
    image: postgres 
    redis: 
    image: redis 
    web: 
    build: ./web 
    image: web 
    ports: 
     - "8080:80" 
    depends_on: 
     - app 
    app: 
    build: ./app 
    image: app 
    command: puma 
    volumes: 
     - ./app:/app 
    expose: 
     - "3000" 
    ports: 
     - "3000:3000" 
    depends_on: 
     - db 
     - redis 
相关问题