Nginx can't find upstream host in multi-container docker compose setup and also host can't be found on client:3000

Viewed 1669

Here is github repo: https://github.com/irahulsah/mutlicontainerapp please,visit it for more info,please help me to fix this error.

I'm running a multi-docker container locally with docker-compose, the containers are React front-end 'client', a Nodejs app 'api', and a Nginx proxy in sits in front of two. I have been using the docker-compose setup as follow for a while.

version: '3'
services:
  client:
    build:
      dockerfile: Dockerfile.dev
      context: ./client
    volumes:
      - /usr/app/node_modules
      - ./client:/usr/app
  api:
    build:
      dockerfile: Dockerfile.dev
      context: ./server
    volumes:
      - /usr/app/node_modules
      - ./server:/usr/app
  nginx:
    restart: always
    build:
      dockerfile: Dockerfile.dev
      context: ./nginx
    ports:
      - '8080:80'

and my Nginx setup is as follows

upstream client {
    server client:3000;
}

upstream api {
    server api:5000;
}

server {
    listen 80;
    server_name _;

    location / {
        if ($http_x_forwarded_proto != 'https') {
            return 301 https://$host$request_uri;
        }
        proxy_pass http://client;
    }

    location /api {
        if ($http_x_forwarded_proto != 'https') {
            return 301 https://$host$request_uri;
        }
        rewrite /api/(.*) /$1 break;
        proxy_pass http://api;
    }
}

Recently when I tried to start up the containers, i got following error:

nginx_1   | 2019/08/08 18:11:12 [emerg] 1#1: host not found in upstream "client:3000" in /etc/nginx/conf.d/default.conf:2
nginx_1   | nginx: [emerg] host not found in upstream "client:3000" in /etc/nginx/conf.d/default.conf:2

Any idea why nginx not able to find upstream?

I have tried to add links to nginx setup blocks as follows:

  nginx:
    restart: always
    build:
      dockerfile: Dockerfile.dev
      context: ./nginx
    links:
      - client:client
      - api:api
    ports:
      - '8080:80'

I also tried 'depends_on' ,but also am getting host can be found on client:300 error,any idea on how to fix this error,will be deeply appreciated.

Any help or direction are greatly appreciated!!!

1 Answers

I had this exactly same issue today. I solved it by attaching all containers that nginx upstream is referring to in the same docker virtual network.

Also, make sure to explicitly define the containers name. If I am not wrong, docker-compose prefix your services name with the yaml file name.

  service_one:
    networks:
     - app-network # define the network
      container_name: backend # the "backend" name must be used in the upstream directive in nginx configuration
Related