I got problem while using Nginx to direct requests

2019-08-24 13:26发布

I'm setting up an app with multiple containers, and use nginx to redirect requests to correct container. However, I got stuck with the 502 Bad Gateway error.

Actually, the code is from a course on Udemy: Docker and Kubernetes. I just copy and paste the code, it ran on instructor machine, but not mine. I tried on my windows and my macbook, restart docker, but still no hope. I looked for solutions on other stackoverflow posts, some other articles, but none of them tell me why it works on others' machines, but not mine.

Here is the repo of the code.

docker-compose.yml (full code):

version: "3"
services:
  postgres:
    ...
  redis:
    ...
  nginx:
    restart: always
    build:
      dockerfile: Dockerfile.dev
      context: ./nginx
    ports:
      - "3050:80"
  api:
    ...
  client:
    ...
  worker:
    ...

nginx/Dockerfile.dev

FROM nginx
COPY ./default.conf /etc/nginx/conf.d/default.conf

nginx/default.conf

upstream client {
  server client:3000;
}

upstream api {
  server api:5000;
}

server {
  listen 80;
  server_name  localhost;

  location / {
    proxy_pass http://client;
  }

  location /api {
    rewrite /api/(.*) /$1 break;
    proxy_pass http://api;
  }
}

It runs just fine on instructor's machine and other learners', but not on my machines. I got error when connecting http://localhost:3050 and http://localhost:3050/api:

nginx_1     | 2019/07/08 02:52:35 [error] 6#6: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.25.0.1, server: , request: "GET / HTTP/1.1", upstream: "http://125.235.4.59:3000/", host: "localhost:3050"
nginx_1     | 172.25.0.1 - - [08/Jul/2019:02:52:35 +0000] "GET / HTTP/1.1" 502 559 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36" "-"
nginx_1     | 2019/07/08 02:52:57 [error] 6#6: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.25.0.1, server: , request: "GET /favicon.ico HTTP/1.1", upstream: "http://125.235.4.59:3000/favicon.ico", host: "localhost:3050", referrer: "http://localhost:3050/"
nginx_1     | 172.25.0.1 - - [08/Jul/2019:02:52:57 +0000] "GET /favicon.ico HTTP/1.1" 502 559 "http://localhost:3050/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36" "-"

Any help is appreciated.

1条回答
来,给爷笑一个
2楼-- · 2019-08-24 14:08

Needed to amend the docker-compose.yml:

  1. the upstream services should expose their ports so that the nginx service can connect i.e.:
  api:
    expose:
    - '5000'

  client:
    expose:
    - '3000'

  1. the nginx service depends_on the upstream services:
  nginx:
    depends_on:
    - 'client'
    - 'api'
查看更多
登录 后发表回答