LoginSignup
2
1

More than 1 year has passed since last update.

【サーバ構築】nginxでリバースプロキシを実装する

Posted at

はじめに

nginxでリバースプロキシを実装してみました。
http:[ipアドレス]/ ⇒ リバースプロキシサーバ兼webサーバ
http:[ipアドレス]/web2 ⇒webサーバ2

設定ファイル

docker-compose.yml
version: "3"
services:
 ngweb1:
  image: nginx:1.21.6
  ports:
   - 80:80
  volumes:
   - ./nginx/html:/usr/share/nginx/html
   - ./nginx/conf.d:/etc/nginx/conf.d

 ngweb2:
  image: nginx:1.21.6
  ports:
   - 81:80
  volumes:
   - ./nginx/html:/usr/share/nginx/html

「/」の場合は、ngweb1のコンテナで、「/ngweb2/」の場合はngweb2のコンテナに繋げてくれます。

server.conf
server {
    listen       80;
    server_name  localhost;

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

    location /web2/ {
        proxy_pass   http://ngweb2/;
    }

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

コンテナ間はコンテナのサービス名で通信することができます。
注意していただきたい点ですが、「proxy_pass http://ngweb2/」の最後のスラッシュ「/」がないとhttpステータス404になります。というのも最後のスラッシュ(trailing slash)が無い場合は、ngweb1のコンテナの/usr/share/nginx/html/web2のディレクトリに対してindex.htmlを探しにいきます。

ログ

なぜか、webサーバのアクセスログは空なので、確認したい場合は、
docker-compose logs サービス名でログ見れます。

最後に

port番号を意識せずに、webサーバを区別できるので便利ですね。
trailing slashについては勉強になりました。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1