Hugh's Blog

Docker + Nginx 简单模拟负载均衡

只是简单的单机模拟负载均衡,做个记录。

建立相应的静态文件

mkdir html1
echo '<h1>Hello World 1</h1>' > ./html1/index.html
# 同样的建立 html2, html3

建立 Nginx 配置文件

default.conf

upstream app {
    server nginx1:80;
    server nginx2:80;
    server nginx3:80;
}

server {
    listen       80;
    server_name  localhost;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;

        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_pass http://app;
    }
}

建立 Docker 容器进行测试

# nginx1, nginx2, nginx3
docker run -d --name nginx1 -v `pwd`/html1:/usr/share/nginx/html nginx:alpine
docker run -d --name nginx2 -v `pwd`/html2:/usr/share/nginx/html nginx:alpine
docker run -d --name nginx3 -v `pwd`/html3:/usr/share/nginx/html nginx:alpine
# nginx0
docker run -d --name nginx0 -p 80:80 -v `pwd`/default.conf:/etc/nginx/conf.d/default.conf --link nginx1:nginx1 --link nginx2:nginx2 --link nginx3:nginx3 nginx:alpine

容器建立之后,打开浏览器就可以看到不同的静态页。

使用 docker-compose

version: '2'
services:
  nginx0:
    image: nginx:alpine
    container_name: nginx0
    restart: always
    volumes:
      # configs
      - ./default.conf:/etc/nginx/conf.d/default.conf
    ports:
      - "80:80"
    links:
      - "nginx1:nginx1"
      - "nginx2:nginx2"
      - "nginx3:nginx3"

  nginx1:
    image: nginx:alpine
    container_name: nginx1
    restart: always
    volumes:
      # html
      - ./html1:/usr/share/nginx/html

  nginx2:
    image: nginx:alpine
    container_name: nginx2
    restart: always
    volumes:
      # html
      - ./html2:/usr/share/nginx/html

  nginx3:
    image: nginx:alpine
    container_name: nginx3
    restart: always
    volumes:
      # html
      - ./html3:/usr/share/nginx/html

运行测试:docker-compose up -d

这里只是很简单的模拟测试,更多的负载均衡配置,可以看这里:Using nginx as HTTP load balancer