Passing variable from container start to file Passing variable from container start to file docker docker

Passing variable from container start to file


Instructions in the Dockerfile are evaluated line-by-line when you do docker build and are not re-evaluated at run-time.

You can still do this however by using an entrypoint script, which will be evaluated at run-time after any environment variables have been set.

For example, you can define the following entrypoint.sh script:

#!/bin/bashsed -i 's/CONFIG_VALUE/'"$CONFIG_VALUE"'/g' CONFIG_FILEexec "$@"

The exec "$@" will execute any CMD or command that is set.

Add it to the Dockerfile e.g:

COPY entrypoint.sh /RUN chmod +x /entrypoint.shENTRYPOINT ["/entrypoint.sh"]

Note that if you have an existing entrypoint, you will need to merge it with this one - you can only have one entrypoint.

Now you should find that the environment variable is respected i.e:

docker run -e CONFIG_VALUE=100 container_name cat CONFIG_FILE

Should work as expected.


That shouldn't be possible in a Dockerfile: those instructions are static, for making an image.

If you need runtime instruction when launching a container, you should code them in a script called by the CMD directive.
In other words, the sed would take place in a script that the CMD called. When doing the docker run, that script would have access to the environment variable set just before said docker run.