Docker模拟Nginx负载均衡
- 直接上dockerfile
- 目录结构:
├── build
│ ├── lb1
│ │ └── Dockerfile
│ ├── lb2
│ │ └── Dockerfile
│ └── slb
│ ├── Dockerfile
│ └── default.conf
└── docker-compose.yml
- vim build/lb1/Dockerfile
FROM daocloud.io/library/nginx:1.13.0-alpine
RUN echo "I am web1" > /usr/share/nginx/html/index.html
- vim build/lb2/Dockerfile
FROM daocloud.io/library/nginx:1.13.0-alpine
RUN echo "I am web2" > /usr/share/nginx/html/index.html
- vim build/slb/Dockerfile
FROM daocloud.io/library/nginx:1.13.0-alpine
RUN mv /etc/nginx/conf.d/default.conf /etc/nginx/conf.d/default.conf.bak
COPY default.conf /etc/nginx/conf.d/default.conf
- vim build/slb/default.conf
upstream allserver {
server lb1;
server lb2;
}
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://allserver;
}
}
- vim docker-compose.yml
version: '2.3'
services:
slb:
build:
context: ./build/slb
privileged: true
ports:
- "8080:80"
links:
- "lb1"
lb1:
build:
context: ./build/lb1
privileged: true
ports:
- "8081:80"
lb2:
build:
context: ./build/lb2
privileged: true
ports:
- "8082:80"
启动服务并在后台运行, 在 docker-compose.yml 所在目录执行:
docker-compose up -d
查看容器是否启动运行
docker ps -a
测试, 执行多次观察输出结果
curl localhost:8080
输出结果:
I am web1
I am web2