如题,我们将使用docker创建nginx容器去搭建一个负载均衡
为了方便于搭建和管理,我们将使用docker-compose去创建多个nginx容器,以下是相关的docker-compose.yml文件
version: '3'
services:
nginx-1:
image: nginx:alpine
ports:
- "81:81"
volumes:
- ./nginx-1.conf:/etc/nginx/nginx.conf
depends_on:
- nginx-2
- nginx-3
nginx-2:
image: nginx:alpine
ports:
- "82:82"
volumes:
- ./nginx-2.conf:/etc/nginx/nginx.conf
nginx-3:
image: nginx:alpine
ports:
- "83:83"
volumes:
- ./nginx-3.conf:/etc/nginx/nginx.conf
启动前,除了配置好docker-compose文件外,还需要提前准备好nginx的配置文件。
包括nginx-1.conf,nginx-2.conf,nginx-3.conf等。其中nginx-2,nginx-3的模块配置一个虚拟主机,使其能够访问就可以。而nginx-1需要配置upstream模块以实现负载均衡。nginx-1的配置如下
#负载均衡策略--在http{}模块里面加入以下代码
upstream backend {
least_conn;
server nginx-2:82;
server nginx-3:83;
}
server {
listen 81;
server_name localhost;
location / {
#root /usr/share/nginx/html;
proxy_pass http://backend;
}
proxy_set_header Host $host:$server_port;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
配置好后,运行docker-compose up -d 即可。