Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

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に書く

https://docs.docker.com/compose/environment-variables/#the-env-file

.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に…

friedaji
文書書く癖つけるために適当に投稿中!
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした