Use Nginx as a proxy server


After I deploy to docker hub, now I will try to run multiple containers of the same docker image. I will use Nginx image to create a reverse proxy server to do load balance.

And Nginx provides default access log for all incoming requests.

mkdir try-reverse-proxy
cd try-reverse-proxy
touch docker-compose.yml
version: "3.9"
services:
  nginx:
    image: nginx:latest
    restart: always
    volumes:
    - "./nginx.conf:/etc/nginx/nginx.conf"
    ports:
    - "8000:80"
  serverone:
    image: nuttawut503/mydocker:1.0
    environment:
    - name=Ant
  servertwo:
    image: nuttawut503/mydocker:1.0
    environment:
    - name=Bird
  serverthree:
    image: nuttawut503/mydocker:1.0
    environment:
    - name=Cat

I use three duplicated Go server with different name environment and there is only Nginx that expose on port 8000. Before run this docker compose, create nginx.conf file

worker_processes auto;

events {}

http {
  upstream apiserver {
    server serverone:8080;
    server servertwo:8080;
    server serverthree:8080;
  }

  server {
    listen 80;

    location / {
      proxy_pass http://apiserver;
    }
  }
}

I have created an upstream and register the three Go server. When you send a request to whatever paths to Nginx, the Nginx will transfer the request to those three server.

docker compose up

Try to access to localhost:8000, the first response will be from the first server and next will be the second's and then from the third. Nginx will send requests to the three servers equally (round-robin). To find more about the load balancer, check this

sources