使用nginx作負載均衡就是修改一個配置文件的事情,網上大部分教程都是在本機去安裝nginx作的,可是爲何不能使用docker更加方便的去作這件事情呢,今天個人想法就是用docker跑nginx而後來作一個負載均衡的實驗html
其實這個環境很簡單,就是四臺centos機器,而後都安裝上了docker,也就是下面這三臺機器nginx
注意最好安裝上ansible,由於這樣最集羣的操做就比較方便起來了web
以後集體pullnginx鏡像docker
ansible docker -m shell -a "docker pull nginx:1.15.1-alpine"
shell
我使用docker-master節點上的nginx作負載均衡centos
docker-slave的全部節點都是網頁服務器bash
首先編寫nginx的配置文件服務器
docker run -d nginx:1.15.1-alpine
app
把鏡像裏面的配置文件複製出來負載均衡
docker cp e08247c36eac:/etc/nginx/nginx.conf .
以後修改爲下面這個樣子
user nginx; worker_processes 1; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; #tcp_nopush on; keepalive_timeout 65; #gzip on; upstream 192.168.1.231 { server 192.168.1.232:8080; server 192.168.1.233:8080; server 192.168.1.234:8080; } server { listen 80; server_name 192.168.1.231; location /{ proxy_pass http://192.168.1.231; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } include /etc/nginx/conf.d/*.conf; }
其實就是加上了upstream和server這兩段
以後新建一個dockerfile,加入
FROM nginx:1.15.1-alpine COPY nginx.conf /etc/nginx
其實就是把配置文件拷貝到容器裏面去
以後新建一個docker-compose文件
加入
version: "3" services: nginx: container_name: "nginx" build: . ports: - "80:80" networks: app_net: ipv4_address: "172.16.11.11" restart: "always" networks: app_net: driver: "bridge" ipam: driver: "default" config: - subnet: "172.16.11.11/24"
這個很少解釋了
最後啓動起來
docker-compose -f docker-compose.yml up -d
此時若是你訪問231服務器會報502錯誤說明幾乎成功一半了
首先編寫compose文件
version: "3" services: nginx: container_name: nginx image: nginx:1.15.1-alpine volumes: - "/home/docker/nginx/html:/usr/share/nginx/html" ports: - "8080:80" networks: app_net: ipv4_address: "172.16.11.11" networks: app_net: driver: "bridge" ipam: driver: "default" config: - subnet: "172.16.11.11/24"
使用ansible分發文件
ansible docker-slave -m copy -a "src=/root/docker-compose.yml dest=/root/docker-compose.yml"
分發docker-compose這個命令
ansible docker-slave -m copy -a "src=/usr/local/bin/docker-compose dest=/usr/local/bin/docker-compose"
ansible docker-slave -m shell -a "chmod +x /usr/local/bin/docker-compose"
以後在全部節點啓動容器
ansible docker-slave -m shell -a "docker-compose -f /root/docker-compose.yml up -d"
以後編寫一個index.html文件,裏面隨便寫點什麼好比hello slave-1,而後分發給192.168.1.232,其餘的也都同樣
ansible slave-1 -m copy -a "src=/root/index.html dest=/home/docker/nginx/html/index.html"
最後的驗證就是輸入192.168.1.231的ip不斷的刷新,裏面會不斷重複hello slave-1或者hello slave-2或者hello slave-3
歡迎關注Bboysoul的博客www.bboysoul.com Have Fun