docker -nginx2

y_d_g發表於2024-04-11

使用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服務,不會報錯。

相關文章