先決條件
- 先將專案的 image 設置好,如果不知道怎麼設置 imgae 請參考這篇
 
介紹
這個 load balance 是將專案放在 docker 上並且用 docker 上的 nginx 做成 load balance
開始
在專案底下新增一個 nginx 的資料夾,並在裡面新增 2 個檔案
第一個檔案是 Dockerfile
1
2
3FROM nginx # 從 docker hub 抓 nginx 進來
RUN rm /etc/nginx/conf.d/default.conf # 把默認的 config 刪掉
COPY nginx.conf /etc/nginx/conf.d/default.conf # 把 專案/nginx 下的 nginx.config 複製到 container 中的 /etc/nginx/conf.d/ 並改名為 default.conf,nginx.config 就是等等下面新增的那個第二個檔案是 nginx.conf
1
2
3
4
5
6
7
8
9
10upstream loadbalance {
least_conn;
server 192.168.2.85:3000; # 前面是你本機的 ip 後面是你的專案在 container 中 on 的 port
}
server {
location / {
proxy_pass http://loadbalance;
}
}把 nginx 的 image 產生起來
cd 到剛剛新增的 nginx 資料夾並輸入docker build -t [username]/[imageName]像下面那樣1
docker build -t den19980107/load-balance .
再來回到專案根目錄新增一個 docker-compose.yml 的檔案
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32version: "3"
services:
nodeapp:
image: den19980107/ldl # 原本專案的 image
ports:
- 3000:3000 # 原本專案使用的 port
deploy:
replicas: 15 # 複製15個 ldl
restart_policy: # 當下面的 condition 時
max_attempts: 3 # 一次重啟 3 個 ldl
condition: on-failure # 當 sever 爆了
update_config: # 當更新時
parallelism: 3 # 一次關掉 3 個來更新 在啟動他們 3 個
delay: 10s # 每次啟動延遲10s
networks:
- balance
proxy:
image: den19980107/load-balance # nginx 的 image 名稱
ports:
- 80:80 # 使用 80 port
depends_on:
- nodeapp # 依賴我們原本的專案
deploy:
placement:
constraints: [node.role == manager]
networks:
- balance
networks:
balance:
driver: overlay最後回到專案根目錄並輸入
1
docker stack deploy -c docker-compose.yml [app名稱]
檢查有沒有 on 起來可以輸入
1
docker service ls
應該會看到類似下面的東西

如果想要把 service 刪掉的話可以輸入下面的指令,id 的看法就是
docker service ls1
docker service rm [node app id] [nginx load balance id]