LoginSignup
8
3

More than 3 years have passed since last update.

docker上のnginx.confに環境変数を適用する方法

Last updated at Posted at 2020-07-16

備忘録です。

docker上のNGINXに環境変数を適用するいい方法が無いか探していました。

envsubstを使ってホニャララする方法がメジャーなのかなーと思って、Docker Hubのnginxのページを見てみると
なにやらversion1.19からいい方法ができてるっぽい??

dockerHub
https://hub.docker.com/_/nginx

ということで早速Google翻訳しながら試してみる。

全体図

├ docker-compose.yml
├ .env
├ nginx
        ├ templates
        │     └ default.conf.template //これがポイント
        └ Dockerfile

.envの中身

#.env
NGINX_PORT=8080

.envファイルをdocker-compose.ymlと同じ階層においておくと環境変数として読み込んでくれる。

#nginx/Dockerfile

FROM nginx:1.19.1
RUN rm /etc/nginx/conf.d/default.conf
  #docker-compose.yml

  nginx:
    container_name: nginx
    build: ./nginx

    ports:
      - ${NGINX_PORT:-80}:${NGINX_PORT:-80}
    depends_on:
      - django
    volumes: 
      - ./nginx/templates:/etc/nginx/templates

    environment:
      - NGINX_PORT=${NGINX_PORT:-80}

${NGINX_PORT:-80}の部分で.envに書かれているNGINX_PORTの値を取得しています。取得できない場合はデフォルト値で80を設定するようになっています。

#default.conf.template

server {
    # 環境変数の値を取得
    listen ${NGINX_PORT};
}

デフォルトでは、この関数は/etc/nginx/templates/*.template内のテンプレートファイルを読み取り、envsubstの実行結果を/etc/nginx/conf.dに出力します。

↑日本語翻訳の結果、なんかetc/nginx/templates内の.templateを上手いこと読み取って環境変数で置き換えてconf.dに出力するそうです。しらんけどw

あとは docker-compose build,docker-compose upしたら無事に接続できました。

8
3
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
8
3