How to make nginx proxy reverse line load balance between two docker containers?

I am trying to do a load balancing reverse nginx proxy between two containers with the same nodejs application.

Directory structure:

.
+-- docker-compose.yml
+-- nginx
+-- nodejs
|   +-- index.js
|   +-- …
+-- php

docker-compose.yml:

version: "3.1"

services:

  nginx-proxy:
    image: nginx:alpine
    ports:
      - "8000:80"
    volumes:
      - ./nginx/default.conf:/etc/nginx/conf.d/default.conf
    links:
      - php:php-app
      - nodejs:nodejs-app

  nodejs:
    image: node:alpine
    environment: 
      NODE_ENV: production
    working_dir: /home/app
    restart: always
    volumes:
      - ./nodejs:/home/app
    command: ["node", "index.js"]

  php:
    image: php:apache
    volumes:
      - ./php:/var/www/html

index.js bugged in port 8080

nginx conf default.conf:

upstream nodejs-upstream {
  server nodejs-app:8080;
}

server {
  listen 80;
  root /srv/www;

  location / {
    try_files $uri @nodejs;  
  }

  location @nodejs {
    proxy_pass http://nodejs-upstream:8080;
    proxy_set_header Host $host;
  }

  location /api {
    proxy_pass http://php-app:80/api;
    proxy_set_header Host $host;
  }
}

Now I launch the application using

docker-compose up  --scale nodejs=2

Is it a load balance?

  • I don’t think so, because two instances of the nodejs application are listening on the same port 8080.

How can I balance the load of a nginx server between two instances of a nodejs application?

Is there a better way to do this?


EDIT 1

I'm still curious to know how to do this without jwilder / nginx-proxy. Thanks


EDIT 2

I have something like:

default.conf:

upstream nodejs-upstream {
  server nodejs_1:8080;
  server nodejs_2:8080;
}

, nodejs . docker stop nodejs_2, (, ), ( 1 localhost). , ...

+4
1

Q. ?

, . jwilder/nginx. , .

https://github.com/jwilder/nginx-proxy

version: "3.1"

services:

  nginx-proxy:
    image: jwilder/nginx
    ports:
      - "8000:80"
     volumes:
      - /var/run/docker.sock:/tmp/docker.sock:ro

  nodejs:
    image: node:alpine
    environment: 
      NODE_ENV: production
      VIRTUAL_ENV: localhost
      VIRTUAL_PORT: 8080
    working_dir: /home/app
    restart: always
    volumes:
      - ../nodejs:/home/app
    command: ["node", "index.js"]

Nginx . VIRTUAL_ENV env var . var nginx. . ( .conf )

+5

Source: https://habr.com/ru/post/1680917/


All Articles