Nginx http-load-balancer

. . . .
.

當網站的流量較大時可以透過設定讓它分散流量到不同的機器,或是其中一台主機出現問題無法,也不會造成服務的中斷。

環境架構

  • load balancer
    • name: web
    • ip: 172.18.0.4
  • web server 1
    • name: web1
    • ip: 172.18.0.2
  • web server 2
    • name: web2
    • ip: 172.18.0.3

實做流程

1. 用docker建立兩台測試主機

web1和web2的設定

~/web1$ cat nginx.conf 
server {
    listen       80;
    server_name  web1.tw;

    location / {
        root   /usr/share/nginx/html;
        index  index.html;
    }
}

web1和web2的網頁

~/web1$ cat index.html
server1
~/web2$ cat index.html
server2

2. 設定load balancer主機

[email protected]:~/web$ cat nginx.conf 
upstream myapp1 {
    server web1 max_fails=1 fail_timeout=5s;
    server web2 max_fails=1 fail_timeout=5s;
}

server {
    listen 80;
    server_name web.tw;

    location / {
        proxy_pass http://myapp1;
    }
}

3. 分別建立dockerfile

web1 and web2

~/web1$ cat dockerfile 
FROM nginx

COPY index.html /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf

load balancer

~/web$ cat dockerfile 
FROM nginx

COPY nginx.conf /etc/nginx/conf.d/default.conf

4. build

web1 and web2

~/web1$ docker build -t web1 .

load balancer

~/web$ docker build -t web .

5. docker-compose

~/web$ cat docker-compose.yaml
version: '2.0'

services:
  web1:
    image: web1
    container_name: web1
    ports:
      - "801:80"
  web2:
    image: web2
    container_name: web2
    ports:
      - "802:80"
  web:
    image: web
    container_name: web
    ports:
      - "800:80"

6. run

~/web$ docker-compose up -d

7. test

現在它是輪流呼叫web1跟web2

$ curl localhost:800
server1
$ curl localhost:800
server2

source:


load balance - CDN : flexbalancer