📝

EC2 をロードバランサーとして使用してみた

に公開

ロードバランサー – Amazon Elastic Load Balancer (ELB) – AWS
AWS ではロードバランサーのサービスとして Elastic Load Balancing が提供されていますが、今回は ELB を使用せず EC2 を独自のロードバランサーとして使用してみました。

1. Web サーバー用 EC2 インスタンスの作成

ロードバランサーの背後で稼働する Web サーバー用の EC2 インスタンスを 2 台作成します。

  • プラットフォーム: Amazon Linux 2023
  • キーペア: なし
    • インスタンスコネクトで接続します
  • VPC 設定
    • デフォルトの VPC
    • パブリックサブネット
    • デフォルトのセキュリティグループ
      • インバウンドルールですべてのトラフィックを許可
  • インスタンスプロファイル: AdministratorAccess 権限を付与した IAM ロール
  • ユーザーデータ: 以下の通り
#!/bin/bash
dnf update -y
dnf install -y httpd

# シンプルなHTMLページを作成
cat > /var/www/html/index.html <<EOF
<!DOCTYPE html>
<html>
<head>
    <title>Web Server</title>
</head>
<body style="text-align: center; font-family: Arial;">
    <h1>Web Server</h1>
    <p>Hostname: $(hostname -f)</p>
    <p>IP Address: $(hostname -I)</p>
</body>
</html>
EOF

# Apacheを起動
systemctl start httpd
systemctl enable httpd

EC2 インスタンスの起動後にパブリック IP アドレスにアクセスして以下のページを確認できれば Web サーバーの作成は完了です。

2. ロードバランサー用 EC2 インスタンスの作成

手順 1 の EC2 インスタンスの設定でユーザーデータのみ変更します。

  • プラットフォーム: Amazon Linux 2023
  • キーペア: なし
    • インスタンスコネクトで接続します
  • VPC 設定
    • デフォルトの VPC
    • パブリックサブネット
    • デフォルトのセキュリティグループ
      • インバウンドルールですべてのトラフィックを許可
  • インスタンスプロファイル: AdministratorAccess 権限を付与した IAM ロール
  • ユーザーデータ: 以下の通り
#!/bin/bash
dnf update -y
dnf install -y nginx

# nginxを起動
systemctl start nginx
systemctl enable nginx

EC2 インスタンスの起動後にインスタンスコネクトなどで SSH 接続して以下のコマンドを実行します。
upstream backend の <Web Server1 Private IP> を手順 1 の EC2 インスタンスのプライベート IP アドレスに置換します。

$ sudo tee /etc/nginx/nginx.conf > /dev/null << 'EOF'
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log notice;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    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;
    types_hash_max_size 4096;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    # ========== ロードバランサー設定 ==========
    upstream backend {
        server <Web Server1 Private IP>;
        server <Web Server2 Private IP>;
    }

    server {
        listen       80;
        listen       [::]:80;
        server_name  _;

        location / {
            proxy_pass http://backend;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
        }
    }
    # ========== ロードバランサー設定ここまで ==========

# Settings for a TLS enabled server.
#
#    server {
#        listen       443 ssl;
#        listen       [::]:443 ssl;
#        http2        on;
#        server_name  _;
#        root         /usr/share/nginx/html;
#
#        ssl_certificate "/etc/pki/nginx/server.crt";
#        ssl_certificate_key "/etc/pki/nginx/private/server.key";
#        ssl_session_cache shared:SSL:1m;
#        ssl_session_timeout  10m;
#        ssl_ciphers PROFILE=SYSTEM;
#        ssl_prefer_server_ciphers on;
#        # Load configuration files for the default server block.
#        include /etc/nginx/default.d/*.conf;
#
#        error_page 404 /404.html;
#        location = /404.html {
#        }
#
#        error_page 500 502 503 504 /50x.html;
#        location = /50x.html {
#        }
#    }
}
EOF

$ sudo nginx -t
$ sudo systemctl restart nginx
$ sudo systemctl status nginx

3. 動作確認

手順 2 で作成した EC2 インスタンスのパブリック IP アドレスにアクセスしてリロードする度に異なる Web サーバーの情報が表示されれば OK です。

まとめ

今回は EC2 をロードバランサーとして使用してみました。
どなたかの参考になれば幸いです。

参考資料

Discussion