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) ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With