t.marcusの外部記憶装置

忘備録とかちょっとした考えとかをつらつらと...

NginxをL7 LBとして使う

名だたるメーカーのLBは数百万してしまうので、個人で使うには高過ぎる。
個人用途だと十分すぎる?のでnginxをアクティブスタンバイ構成のLBとして使う方法

やりたいことをまとめると

  1. /path1もしくは/path2以下のでアクセスが来た場合はweb2にproxyする
  2. 上記以外のリクエストはweb1にproxyする
  3. web1とweb2はそれぞれアクティブスタンバイ(active/passive)構成として、基本的にはactiveが受けるが、activeが応答しなかった場合はpassiveで処理を行う
  4. activeが復旧した場合はactiveが処理を行う

【テスト環境】

# サーバ環境
$ cat /etc/redhat-release
CentOS release 6.4 (Final)
$ nginx -v
nginx version: nginx/1.0.15

# ネットワーク環境
+ lb (192.168.56.20)
|
+- web1-active (192.168.56.30)
+- web1-passive (192.168.56.31)
|
+- web2-active (192.168.56.40)
+- web2-passive (192.168.56.41)

# LB以外のnginxのドキュメントルート配下の構成
# それぞれのファイルにはどのサーバのホスト名を書く
./
+ path1/
|   + index.html
+ path2/
|   + index.html
+ index.html
+ hoge.html
+ piyo.html

まずnginxにweb1とweb2のグループを登録してactive/passiveの設定を行う

$ cat /etc/nginx/nginx.conf
user              nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log;

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;

    keepalive_timeout  1;

    # web1の設定
    upstream web1 {
        server 192.168.56.30:80    fail_timeout=1s max_fails=1;
        server 192.168.56.31:80    backup;
    }

    # web2の設定
    upstream web2 {
        server 192.168.56.40:80    fail_timeout=1s max_fails=1;
        server 192.168.56.41:80    backup;
    }

    include /etc/nginx/conf.d/*.conf;
}

そして、rewriteの設定を行う

$ cat /etc/nginx/conf.d/default.conf
server {

    listen       80;

    location / {
        proxy_pass http://web1;
    }

    location ~ (\/path1|\/path2)(\/.*)? {
        proxy_pass http://web2;
    }

    error_page  404              /404.html;
    location = /404.html {
        root   /usr/share/nginx/html;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

そしてnginxを再起動すると、アクティブスタンバイ構成のLBとして機能するようになる。