Hedge
Hedge

Reputation: 16748

How to use an environment variable from a docker-compose.yml in a Dockerfile?

My docker-compose.yml looks something like this:

version: '2'
services:
  myapp:
    build:
      context: .
    environment:
      - GITLAB_USER=myusername

I want to use that environment variable inside a Dockerfile but it does not work:

FROM node:7
ENV GITLAB_USER=${GITLAB_USER} \
RUN echo '${GITLAB_USER}' 

echos just: ${GITLAB_USER}

How can I make this work so I can use variables from an .env file inside Docker (via docker-compose) ?

Upvotes: 10

Views: 7895

Answers (1)

BMitch
BMitch

Reputation: 263489

There are two different time frames to understand. Building an image is separate from running the container. The first part uses the Dockerfile to create your image. And the second part takes the resulting image and all of the settings (e.g. environment variables) to create a container.

Inside the Dockerfile, the RUN line occurs at build time. If you want to pass a parameter into the build, you can use a build arg. Your Dockerfile would look like:

FROM node:7
ARG GITLAB_USER=default_user_name
# ENV is optional, without it the variable only exists at build time
# ENV GITLAB_USER=${GITLAB_USER}
RUN echo '${GITLAB_USER}' 

And your docker-compose.yml file would look like:

version: '2'
services:
  myapp:
    build:
      context: .
      args:
      - GITLAB_USER=${GITLAB_USER}

The ${GITLAB_USER} value inside the yml file will be replaced with the value set inside your .env file.

Upvotes: 15

Related Questions