# docker load balance ###### tags: `docker` `deploy` `load-balance` # 先決條件 * 先將專案的 image 設置好,如果不知道怎麼設置 imgae 請參考[這篇](https://hackmd.io/7kTvn4WKRQGpGCddJtR-xw) # 介紹 這個 load balance 是將專案放在 docker 上並且用 docker 上的 nginx 做成 load balance # 開始 * 在專案底下新增一個 nginx 的資料夾,並在裡面新增2個檔案 * 第一個檔案是 Dockerfile ``` dockerfile FROM 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 ``` conf upstream 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]` 像下面那樣 ``` docker build -t den19980107/load-balance . ``` * 再來回到專案根目錄新增一個 docker-compose.yml 的檔案 ``` yml version: '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 ``` * 最後回到專案根目錄並輸入 ``` docker stack deploy -c docker-compose.yml [app名稱] ``` * 檢查有沒有 on 起來可以輸入 ``` docker service ls ``` 應該會看到類似下面的東西 ![](https://i.imgur.com/29C7AxR.png) * 如果想要把 service 刪掉的話可以輸入下面的指令,id 的看法就是 `docker service ls` ``` docker service rm [node app id] [nginx load balance id] ``` # 參考文章 https://levelup.gitconnected.com/load-balance-and-scale-node-js-containers-with-nginx-and-docker-swarm-9fc97c3cff81