Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 906
Hedge Avatar asked Mar 08 '23 01:03

Hedge


1 Answers

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.

like image 191
BMitch Avatar answered Mar 10 '23 10:03

BMitch