LoginSignup
74
48

More than 5 years have passed since last update.

docker-compose.ymlの中で環境変数を展開する

Last updated at Posted at 2017-10-06

https://docs.docker.com/compose/compose-file/#env_file
https://docs.docker.com/compose/compose-file/#environment

docker-compose.ymlの中で環境変数を別で定義しておきたかったけれど
中々動かなかったので試行錯誤したまとめ

現象

サンプル

docker-compose.yml
version: "3.3"
services:
  test:
    image: ubuntu:${VER}
    env_file: test.env
    ports:
      - $PORT:$PORT
    command: "echo $PORT"

の、ように変わりそうな値は別に定義しておきたくなるのです…が

どうやっても値が空

env_file:
  - ./test.env
test.env
PORT=8080
VER=17.10

>>>The PORT variable is not set. Defaulting to a blank string.<<<

とか出る

仕方がないので

environment:
  - PORT=8080

等もためしてみる

>>>The PORT variable is not set. Defaulting to a blank string.<<<

この時点で考えたこと

  • composeからdockerfileに値を渡すならば、enviromentは機能している
  • composeファイル内でenviromentの定義を参照しようとしても空

結局、どうすれば読み込めるか?

  • .envに書く

.env
PORT=8080
VER=17.10
docker-compose.yml
version: "3.3"
services:
  test:
    image: ubuntu:${VER}
    ports:
      - $PORT:$PORT
    command: "echo $PORT"
$Recreating test_test_1 ...
Recreating test_test_1 ... done
Attaching to test_test_1
test_1  | 8080
test_test_1 exited with code 0

おまけ

LongSyntaxとは相性がわるいらしい

intとか

services.hoge.ports.published contains "8080", which is an invalid type, it should be an integer

泣く泣くshort syntaxに…

74
48
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
74
48