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

docker-composeのビルド中に環境変数が認識されない

More than 1 year has passed since last update.

問題

docker-composeでenv_fileで環境変数を渡し、ビルド中に環境変数を読み込もうとすると空になっている

docker-compose.yml
version: '3'
services:
  python:
    build: .
    env_file: .env
.env
PYTHON_VER=3.7.0
Dockerfile
FROM ubuntu:18.04
echo PYTHON_VER
結果
Building python
Step 1/2 : FROM ubuntu:18.04
 ---> 113a43faa138
Step 2/2 : RUN echo $PYTHON_VER
 ---> Running in 0ffe2bbdc963

Removing intermediate container 0ffe2bbdc963
 ---> 2a5bca18b8ae

environmentで個別にした場合も同様

原因

docker-composeのenv_file, environmentで指定する環境変数は、
ビルド後にコンテナで参照できるようになるため、ビルド中は参照できない。

解決策

DockerfileコマンドのARGで変数を用意し、docker-composeのbuildのargsオプションで引数として渡すことで、
ビルド中に参照する変数をdocker-compose.ymlから渡すことができる。

docker-compose.yml
version: '3'
services:
  python:
    build: 
      context: .
      args:
        PYTHON_VER: $PYTHON_VER
.env
PYTHON_VER=3.7.0
Dockerfile
FROM ubuntu:18.04
ARG PYTHON_VER
echo PYTHON_VER
結果
Building python
Step 1/3 : FROM ubuntu:18.04
 ---> 113a43faa138
Step 2/3 : ARG PYTHON_VER
 ---> Running in 197b6627ceb4
Removing intermediate container 197b6627ceb4
 ---> 7ac082e6fa40
Step 3/3 : RUN echo $PYTHON_VER
 ---> Running in eef3f4e39711
3.7.0
Removing intermediate container eef3f4e39711
 ---> cfc836b81063
katoosky
アカウント運用停止しました
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
ユーザーは見つかりませんでした