Passing a variable from container to file

I have the following lines in a Docker file, where I want to set the value in the configuration file to the default value before the application starts at the end and provide an optional setting using the -e option when the container starts.

I am trying to do this using the docker ENV commando

  ENV CONFIG_VALUE default_value RUN sed -i 's/CONFIG_VALUE/'"$CONFIG_VALUE"'/g' CONFIG_FILE CMD command_to_start_app 

I have the CONFIG_VALUE line explicitly in the CONFIG_FILE file, and the default value from the Dockerfile is correctly replaced. However, when I start the container with -e CONFIG_VALUE=100 added, the substitution is not performed, the default value set in the Docker file is saved.

When i do

 docker exec -i -t container_name bash 

and echo $CONFIG_VALUE inside the container, the environment variable contains the required value of 100.

+5
source share
2 answers

This should not be possible in the Docker file: these instructions are static for creating the image.

If you need a run-time instruction when starting the container, you must encode them in a script called by the CMD directive.
In other words, sed will take place in the script that invoked CMD . When executing docker run , that script will have access to the environment variable set immediately before the specified docker run .

+5
source

The instructions in the Docker file are evaluated one at a time when you run docker build and are not reevaluated at run time.

You can still do this using a script entry point that will be evaluated at runtime after the environment variables are set.

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

 #!/bin/bash sed -i 's/CONFIG_VALUE/'"$CONFIG_VALUE"'/g' CONFIG_FILE exec " $@ " 

exec " $@ " will execute any installed CMD or command.

Add it to the Docker file, for example:

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

Note that if you have an existing entry point, you will need to combine it with this - you can have only one entry point.

Now you should find that the environment variable is respected ie:

 docker run -e CONFIG_VALUE=100 container_name cat CONFIG_FILE 

Should work as expected.

+7
source

All Articles