Cabrinha
Cabrinha

Reputation: 495

Dockerfile and environnement variables

I have a strange behavior with my Dockerfile. I try to make it write file with text coming from environment varibales :

FROM ubuntu:14.04

ENV KEY ''
ENV VAL ''

RUN echo "${KEY}:${VAL}" > /etc/test

CMD []

I built this image and run it like this :

docker run -it --rm -e KEY=aaa -e VAL=bbb mytest

If I display the /etc/test file, it is empty (it is present, but empty). It seems that when it creates the file, environment variables are not set.

Any idea?

Thank you

Upvotes: 0

Views: 72

Answers (2)

Mohamed Ali
Mohamed Ali

Reputation: 176

You can define KEY and VALUE as arguments and set their values when you're building the docker image.

FROM ubuntu:14.04

ARG KEY
ARG VAL

RUN echo "${KEY}:${VAL}" > /etc/test

CMD []

Then you can build the image using like this:

docker build --build-arg KEY=<value> --build-arg VAL=<value> .

https://docs.docker.com/engine/reference/builder/#using-arg-variables

Upvotes: 0

yamenk
yamenk

Reputation: 51768

The command in the docker file RUN echo "${KEY}:${VAL}" > /etc/test is executed when you build the image using docker build ...

Thus this is logical, since at that point the env variables are empty. You need to move the commad to the CMD command which will run when the image is started.

Upvotes: 2

Related Questions