LoginSignup
2
2

More than 5 years have passed since last update.

CentOS7 に Nginx 入れてdocker コンテナにプロキシする

Last updated at Posted at 2017-12-22

前提

前回の記事の続き的なコンテンツ

サーバは CentOS7
docker コンテナでWEBサーバがすでに起動している。
ホストサーバ上に複数 docker コンテナでWEBサーバが起動しており、それらをホストサーバのバーチャルホスト経由でプロキシし、それぞれがどのポートにいるかを意識せずにブラウザから見えるようにしたい。
docker コンテナ上の WEBサーバは開発環境であることを想定し、basic 認証をかけたい。

Nginx インストール&自動起動設定

sudo yum install nginx
sudo systemctl start nginx
sudo systemctl enable nginx

ポートリッスンできてるか確認

# ミニマムインストールで入ってなかったのでインストール
sudo yum install lsof
sudo lsof -i :80
----
COMMAND  PID  USER   FD   TYPE  DEVICE SIZE/OFF NODE NAME
nginx   8754  root    6u  IPv4 3613680      0t0  TCP *:http (LISTEN)
nginx   8754  root    7u  IPv6 3613681      0t0  TCP *:http (LISTEN)
nginx   8755 nginx    6u  IPv4 3613680      0t0  TCP *:http (LISTEN)
nginx   8755 nginx    7u  IPv6 3613681      0t0  TCP *:http (LISTEN)
----

外部から見えるようにする

# firewall 80, 443アクセスできるようにする
sudo firewall-cmd --add-service=https --zone=public --permanent
sudo firewall-cmd --add-service=http --zone=public --permanent
# ブラウザから nginx の index.html が見えることを確認

htpasswd 設定

sudo mkdir -p /etc/nginx/htpasswd
sudo echo "ユーザ名:$(openssl passwd -apr1 パスワード)" > /etc/nginx/htpasswd/ユーザ名
sudo chown -R nginx:nginx /etc/nginx/htpasswd
sudo chmod 600 /etc/nginx/htpasswd/ユーザ名
sudo chmod 700 /etc/nginx/htpasswd
sudo vim /etc/nginx/nginx/conf
/etc/nginx/nginx/conf
# (省略)
http {
    auth_basic           "private site";
    auth_basic_user_file /etc/nginx/htpasswd/ユーザ名;
# (省略)
sudo nginx -s reload

ブラウザから basic 認証がかかっていることを確認

プロキシ

/etc/nginx/conf.d/hoge.conf
upstream hoge.fuga.com {
    # docker コンテナが10080でポートフォワーディングしてるとする
    server 127.0.0.1:10080 weight=1;
}

server {
    listen       80;
    server_name  hoge.fuga.com;

    access_log  /var/log/nginx/hoge.fuga.access.log  main;

    location / {
        proxy_pass http://hoge.fuga.com;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}
# 設定ファイルチェック
sudo nginx -t
# 設定読み込み
sudo nginx -s reload
# hoge.fuga.com にブラウザ上からアクセスして見れればOK(hostsに設定するのを忘れずに)

docker コンテナが増えたら プロキシ の部分を設定すればOK

2
2
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
2