Passing dynamic variables into the docker image
I created an article before about how to create a spring boot application using dynamo DB. But configurable values are hardcoded. So, there should be a mechanism to change those values. Since we are running our Springboot application as a docker image, we need to pass those dynamic values into a docker container.
So we need to do 2 things.
- Change spring-boot project to accept value from environment variables
- Passing values into the docker container
Let’s start.
Change the code
First, we need to change the spring-boot application in order to accept environment variables
@Value("${DOCKER_PER_SMS_CHARGE:0.12921}")
private String PER_SMS_CHARGE = "" ;
In the above snippet, the variable ‘PER_SMS_CHARGE’ is replaced with an environment variable called ‘DOCKER_PER_SMS_CHARGE’.
It also has a default value. if the value is unset from environment variables, the default value will be used.
Passing values into the docker container
There are two ways we can pass data into the docker container.
- pass values as environment variables
we can use the following format to add variables
-e NAME=value
In this scenario, if I run the docker image without passing variables, the default value is applied. You can verify it by providing a console logging.
// without passing variables
docker run -d -p 80:9000 harshasira/restapp:tag//with passing values
docker run -d -p 80:9000 -e DOCKER_PER_SMS_CHARGE=0.15 harshasira/restapp:tag
If we pass the variable value as above, those values will be assigned to the variable.
we can pass multiple variable values with multiple -e tags
2. Pass values as a file into the docker container
There are scenarios where lots of environment variables need to be passed as environment variables. Passing them using a file is much more convenient in this case.
This is how the file is passed into the docker container
--env-file FILENAME.EXTENSION
Sample with a passing environment variable using a file.
docker run -d -p 80:9000 --env-file ./file.xml harshasira/restapp:tag
Simple file with data
DOCKER_PER_SMS_CHARGE=0.123
Features of file
- The file should have one variable per line
- Empty lines and lines starting with # are ignored
If we pass enviornment variable in both ways,with as inline variable and as variable file , inline pass variables will override variable applied in file
This is how we inject dynamic variables into docker images.
Thanks for reading! (A few 👏 are always appreciated. 😀)