Thaian
Thaian

Reputation: 1245

Docker how to use env_file variable in Dockerfile during build

I would like to use STAGE variable from env_file in my Dockerfile. Most posts suggest just use -e with docker-compose up command but I would like to achieve this by the env_file.

I tried add args but it's not working.

Env file

STAGE=DEV

docker-compose.yml

version: '2'

services:
  web:
    build: .
    env_file:
      - /etc/web.env
    command: python3 manage.py runserver 0.0.0.0:8000
    volumes:
      - ./backend:/code
    ports:
      - "8000:8000"

Dockerfile

FROM python:3.6
ENV PYTHONUNBUFFERED 1
(...)
RUN pip install -r project/requirements/$STAGE.txt

Result of this should be:

RUN pip install -r project/requirements/DEV.txt

I found that it is not possible during build but maybe exist some method to do this. I will be helpful for any tips.

Upvotes: 5

Views: 9757

Answers (1)

Maokai
Maokai

Reputation: 372

You can map the environment variable into the container by adding an environment option in your docker compose yaml file:

version: '2'

services:
  web:
    build: .
    env_file:
      - /etc/web.env
    command: python3 manage.py runserver 0.0.0.0:8000
    volumes:
      - ./backend:/code
    ports:
      - "8000:8000"
    environment:
      - STAGE: ${STAGE}

Upvotes: 2

Related Questions