10

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) ?

Hedge
  • 16,142
  • 42
  • 141
  • 246

1 Answers1

15

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.

BMitch
  • 231,797
  • 42
  • 475
  • 450
  • But I can't use those ARGs with the .env file right? – Hedge Jan 30 '18 at 15:51
  • 1
    The `.env` file allows you to specify a variable to use inside your yml file. You can pass that through to the build process, created container, or just about any other line of the yml file. – BMitch Jan 30 '18 at 15:56