Nginx USES a reverse proxy for load balancing process resolution

  • 2020-05-17 07:45:53
  • OfStack

Introduction to the

Based on the docker container and docker-compose, you need to learn the basic use of docker in the linux environment on your own

Use two tomcat as load balancing servers

1. Pull tomcat and nginx images using docker

Pull nginx reference

Pull the tomcat reference

2. Create two tomcat services using docker-compose

Create the docker-compose.yml file in the new tomcat directory and enter the following:


version: '3'
services:
  tomcat1:
    image: tomcat
    container_name: tomcat1
    ports:
      - 9090:8080

  tomcat2:
    image: tomcat
    container_name: tomcat2
    ports:
      - 9091:8080

Run the following command in the same directory as docker-compose.yml to start the container (-d for background running)


docker-compose up -d

View the docker container list after success

The command


docker ps

The resulting example has two containers, tomcat1 and tomcat2


CONTAINER ID  IMAGE    COMMAND    CREATED    STATUS    PORTS     NAMES
271dd3610d1d  tomcat    "catalina.sh run" 58 minutes ago  Up 58 minutes  0.0.0.0:9091->8080/tcp tomcat2
fa19d20f0022  tomcat    "catalina.sh run" 58 minutes ago  Up 58 minutes  0.0.0.0:9090->8080/tcp tomcat1

Interactively enter the container and modify the front page content to distinguish between the two tomcat(tomcat for example below)

The command


docker exec -it fa19d20f0022 bash

Add content to the home page


echo "9090" >> webapps/ROOT/index.jsp

3. Create the nginx service

Create the docker-compose.yml file in the new nginx directory and enter the following:


version: '3.1'
services:
  nginx:
    restart: always
    image: nginx
    container_name: nginx
    ports:
      - 81:80
    volumes:
      - ./conf/nginx.conf:/etc/nginx/nginx.conf

Since docker-compose automatically processes /conf/ nginx.conf as a folder, you need to create the conf directory under nginx directory and the nginx.conf file under conf directory before creating the container and enter the following:


user nginx;
worker_processes 1;

events {
 worker_connections 1024;
}

http {
 upstream myapp1 {
  server [ The server ip]:9090 weight=10;
  server [ The server ip]:9091 weight=10;
 }
 server {

  listen 80;
  server_name [ The server ip];
  location / {
   proxy_pass http://myapp1;
  }
 }
}

Run in the same directory as docker-compose.yml


docker-compose up -d

4. Visit [server ip]:81, refresh it several times, and observe the switch between the two tomcat services


Related articles: