やりたいこと
.envを活用して色々やってみる。
使う時
前準備として、以下のようなファイルをdocker-compose.ymlと同じディレクトリに作っておく
SAMPLE_VAR=local.sample.jp
docker-compose.ymlで使う
${変数名}
で参照できる
version: 3
services:
name: sample
environments:
- SAMPLE_VAR: ${SAMPLE_VAR}
extra_hosts:
- 127.0.0.1: ${SAMPLE_VAR}
Dockerfileで使う
docker-compose.ymlのenvironmentsに書いておけば${SAMPLE_VAR}
を受け取れる。
docker-compose.yml
version: 3
services:
name: sample
environments:
- SAMPLE_VAR: ${SAMPLE_VAR}
Dockerfile
RUN echo $SAMPLE_VAR
# 出力: local.sample.jp
マウントしたファイルの中身に環境変数をセットさせる(番外編)
※envsubst
が必要
text.txt.template
${SAMPLE_VAR}
docker-compose.yml
version: 3
services:
name: sample
environments:
- SAMPLE_VAR: ${SAMPLE_VAR}
volumes:
- ./text.txt.template: ./text.txt.template
command:
- envsubst '$$SAMPLE_VAR' < ./text.txt.template > ./text.txt