Ubuntu18 上使用 docker 的 nginx 容器模擬負載均衡

summer-1994發表於2019-02-27

安裝Docker

建立sh檔案,也可以一條一條複製執行 vim install-docker.sh

sudo apt-get install apt-transport-https ca-certificates curl software-properties-common

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
sudo apt-get update
sudo apt-get install docker-ce

sudo systemctl enable docker
sudo systemctl start docker

執行安裝
file
檢視docker
file
換成國內源
vim /etc/docker/daemon.json 沒有則新建此檔案

{
    "registry-mirrors": [
        "https://registry.docker-cn.com"
    ]
}

儲存,然後重啟docker server
service docker restart

拉取nginx映象&執行容器例項

  1. 獲取nginx映象 docker pull nginx
  2. 然後使用 docker images可以檢視獲取的映象
  3. 在本地建立docker/nginx1/index.html檔案和docker/nginx2/index.html檔案,用於掛載專案檔案
  4. 在index.html檔案輸入內容 "hello,this is nginx1." 和 "hello,this is nginx2".
  5. 建立執行nginx容器
    file
    1.模擬轉發請求的nginx
    docker run  -d --name nginx -p 8081:80 nginx
    2.模擬第一臺伺服器的nginx
    docker run  -d --name nginx1 -p 8082:80 -v /root/docker/nginx1:/usr/share/nginx/html nginx
    3.模擬第二臺伺服器的nginx
    docker run  -d --name nginx2 -p 8083:80 -v /root/docker/nginx2:/usr/share/nginx/html nginx

-d:守護程式,在後臺執行
-v:掛載檔案,掛載剛剛建立的docker/nginx1目錄
-p:表示本地對映容器內的埠 (本地8081對映容器內的80)
--name :取名稱

在瀏覽器輸入127.0.0.1:8081、127.0.0.1:8082、127.0.0.1:8083可以訪問容器內的index.html
file
filefile
檢視容器狀態
docker ps -a
file
進入容器nginx,安裝vim
docker exec -it nginx /bin/bash
sudo apt-get update
sudo apt-gei install vim
file
到這裡環境就裝完了,接下來是nginx的配置.

修改nginx的配置

  1. 編輯vim /etc/nginx/nginx.conf 檔案,注意這裡的ip是宿主機的ip
    upstream webapp { 
      server 192.168.1.187:8082; 
      server 192.168.1.187:8083; 
    }

    file

  2. 編輯vim /etc/nginx/conf.d/default.conf檔案,在location / {}引入剛剛寫的webapp.

    proxy_pass http://webapp;

    file

  3. 重啟nginx service nginx restart

測試

file

upstream依照輪詢(預設)方式進行負載,每一個請求按時間順序逐一分配到不同的後端伺服器。假設後端伺服器down掉。能自己主動剔除。儘管這樣的方式簡便、成本低廉。但可靠性低和負載分配不均衡。

upstream有很多分配策略:如weight、ip_hash等。

相關文章