概要
Nginxコンテナによるリバースプロキシ設定手順を記載します。
環境
- マシン:Amazon EC2
- OS:Ubuntu 24.04
- Docker:28.0.1
- Docker Compose:2.33.1
前提条件
- DockerおよびDocker Composeがインストールされていること
- SSL証明書を保有していること
手順
以下のようなディレクトリ・ファイル構造を作成してください。
ルートをnginx
という名前にしていますが、任意の名前でも構いません。
cert.pem
はフルチェインの証明書、key.pem
は秘密鍵になります。
nginx
|-- compose.yaml
|-- config
| `-- mysite_nginx.conf
|-- certs
| `-- cert.pem
| `-- key.pem
compose.yamlの内容のサンプルを示します。
compose.yaml
services:
nginx:
image: nginx:latest
container_name: nginx
ports:
- "443:443"
restart: unless-stopped
volumes:
- ./config:/etc/nginx/conf.d
- ./certs:/etc/nginx/ssl
mysite_nginx.confの内容のサンプルが次になります。
パラメータの詳細説明は割愛しますが、HttpsおよびWebsockert通信に対応した内容となっています。
<ACCESS-FQDN>
には、クライアントから見たアクセスFQDNを記載して下さい。
<BACKEND-FQDN>
にはバックエンドのFQDNを記載して下さい。
mysite_nginx.conf
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
listen 443 ssl;
server_name "<ACCESS-FQDN>";
ssl_certificate /etc/nginx/ssl/cert.pem;
ssl_certificate_key /etc/nginx/ssl/key.pem;
location / {
proxy_pass "<BACKEND-FQDN>";
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
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;
}
}
必要なファイルが配置できたら、compose.yamlが存在するディレクトリにて、次のコマンドを実行すると、nginxコンテナが起動します。
docker compose up -d
以上でセットアップは完了です。