使用docker部署nginx的负载均衡
前言:
nginx做负载均衡使用权重轮训方式,1号服务器提供转发服务,2号和3号服务器实际使用。
过程:
创建文件夹:
mkdir -pv /lnmp/nginx/nginx_proxy/{data,conf/conf.d,logs}
mkdir -pv /lnmp/nginx/nginx_one/{data,conf/conf.d,logs}
mkdir -pv /lnmp/nginx/nginx_two/{data,conf/conf.d,logs}
创建配置文件
nginx负载均衡的转发模式有很多,本文选取的是权重轮训的方式
vi /lnmp/nginx/nginx_proxy/conf/conf.d/nginx_proxy.conf
upstream show {
server 192.168.59.135:70 weight=1;
server 192.168.59.135:71 weight=2;
}
server {
listen 80; #listen、server_name这些正常配置
#server_name www.test.com;
#access_log /var/log/nginx/test.access.log;
location / {
proxy_pass http://show; ##反向代理执行定义的upstream名字
}
}
-------------------------------------------------------------------------------------------------------
vi /lnmp/nginx/nginx_one/conf/conf.d/nginx_one.conf
{
listen 70;
location / {
root /lnmp/nginx/data;
index index.html index.html;
try_files $uri $uri/ /index.html;
}
error_log /var/log/nginx/nginx_one.error.log;
}
-------------------------------------------------------------------------------------------------------
vi /lnmp/nginx/nginx_two/conf/conf.d/nginx_two.conf
{
listen 71;
location / {
root /lnmp/nginx/data;
index index.html index.html;
try_files $uri $uri/ /index.html;
}
error_log /var/log/nginx/nginx_two.error.log;
}
-------------------------------------------------------------------------------------------------------
创建网页文件文件
echo 'hello_one' > /lnmp/nginx/nginx_one/data/index.html
echo 'hello_two' > /lnmp/nginx/nginx_two/data/index.html
-------------------------------------------------------------------------------------------------------
运行docker容器
nginx_proxy
docker run -d --name nginx_proxy \
-p 80:80 \
-v /lnmp/nginx/nginx_proxy/conf/conf.d:/etc/nginx/conf.d \
-v /lnmp/nginx/nginx_proxy/data:/lnmp/nginx/data \
-v /lnmp/nginx/nginx_proxy/logs:/var/log/nginx \
--restart=always \
nginx:1.2_food
--------------------------------------------------------------------------------------------------------
nginx_one
docker run -d --name nginx_one \
-p 70:70 \
-v /lnmp/nginx/nginx_one/conf/conf.d:/etc/nginx/conf.d \
-v /lnmp/nginx/nginx_one/data:/lnmp/nginx/data \
-v /lnmp/nginx/nginx_one/logs:/var/log/nginx \
--restart=always \
nginx:1.2_food
--------------------------------------------------------------------------------------------------------
nginx_two
docker run -d --name nginx_two \
-p 71:71 \
-v /lnmp/nginx/nginx_two/conf/conf.d:/etc/nginx/conf.d \
-v /lnmp/nginx/nginx_two/data:/lnmp/nginx/data \
-v /lnmp/nginx/nginx_two/logs:/var/log/nginx \
--restart=always \
nginx:1.2_food
--------------------------------------------------------------------------------------------------------
测试
浏览器输入http://192.168.59.135一直刷新,页面会出现hello_one或hello_two。这个时候我把nginx_two停了,屏幕会持续调用nginx_one服务,不会报错。