ブログタイトル募集中の新人SE記

ネットの片隅で非力を嘆く

dockerでnginxのロードバランシングを試す

dockerでnginxのロードバランシング

実際に動かしたコードはこちら

github.com

前提

  • dockerが動かせる環境

事前準備

docker-compose作成

./docker-compose.yaml を下記の内容で作成

version: '3.2'

services:
  loadbalancer:
    container_name: "wg-loadbalancer"
    image: nginx:alpine
    volumes:
      - ./loadbalancer:/etc/nginx/conf.d
    ports:
      - 8000:80
  web1:
    container_name: "wg-webserver1"
    image: nginx:alpine
    volumes:
      - ./web1:/usr/share/nginx/html
    # 本来必要ないが検証のため
    ports:
      - 8001:80
  web2:
    container_name: "wg-webserver2"
    image: nginx:alpine
    volumes:
      - ./web2:/usr/share/nginx/html
    # 本来必要ないが検証のため
    ports:
      - 8002:80

ロードバランシング用のnginx設定ファイル作成

./loadbalancer/nginx.conf を下記の内容で作成

upstream web {
    # コンテナ名で接続する
    server wg-webserver1;
    server wg-webserver2;
}

server {
    listen       80;
    location / {
           proxy_pass http://web;
    }
}

振り分け先サーバ1用のhtml作成

振り分けられたサーバがわかるよう ./web1/index.html を作成

<!DOCTYPE html>
<html>

<head>
    <title>Welcome to nginx!</title>
    <style>
        body {
            width: 35em;
            margin: 0 auto;
            font-family: Tahoma, Verdana, Arial, sans-serif;
        }
    </style>
</head>

<body>
    <h1>Welcome to nginx! server1</h1>
    <p>If you see this page, the nginx web server is successfully installed and
        working. Further configuration is required.</p>

    <p>For online documentation and support please refer to
        <a href="http://nginx.org/">nginx.org</a>.<br />
        Commercial support is available at
        <a href="http://nginx.com/">nginx.com</a>.</p>

    <p><em>Thank you for using nginx.</em></p>
</body>

</html>

同様にサーバ2用のhtml作成

./web2/index.htmlを作成

<!DOCTYPE html>
<html>

<head>
    <title>Welcome to nginx!</title>
    <style>
        body {
            width: 35em;
            margin: 0 auto;
            font-family: Tahoma, Verdana, Arial, sans-serif;
        }
    </style>
</head>

<body>
    <h1>Welcome to nginx! server2</h1>
    <p>If you see this page, the nginx web server is successfully installed and
        working. Further configuration is required.</p>

    <p>For online documentation and support please refer to
        <a href="http://nginx.org/">nginx.org</a>.<br />
        Commercial support is available at
        <a href="http://nginx.com/">nginx.com</a>.</p>

    <p><em>Thank you for using nginx.</em></p>
</body>

</html>

実行

docker実行

$ docker-compose up -d

検証

サーバ1にアクセス

  • http://localhost:8001 にアクセス
  • 何度アクセスしても server1 と表示される

サーバ2にアクセス

  • http://localhost:8002 にアクセス - 何度アクセスしても server2 と表示される

ロードバランサー経由でアクセス

  • http://localhost:8000 にアクセス
  • アクセスするたびに server1 server2 のどちらかが表示される

停止

$ docker-compose down

めも

各サーバへの接続

$ docker exec -it <コンテナ名> /bin/ash

nginx:alpineを使っているので /bin/bash でなく /bin/ash

ログ確認

$ docker logs -tf <コンテナ名> で各サーバのログが見れる

最後に

とりあえず超簡易的に作成

nginxでのロードバランシング設定など学ぶのに使っていく

へっぽこエンジニアなので実務で触ることは今の所ないが知っておかないと余計なことに困るので