In this blog, I will explain how to use Docker to set environment variables which can be used to substitute URL’s in the configuration file at runtime.
Generally the practice is to keep URL’s in configuration files or properties file, but it can be tedious sometime when URL is very dynamic in nature. For every change in URL, you will need to build your code again and again and then redeploy changes. This can lead to unknown errors sometime, to avoid this we can pass such configuration at runtime. i.e. when Docker container is run, we can supply these URLs as a parameter and write a script to replace the constants in our properties file with this parameters.
To achieve this we would require to do following tasks:
- Write a Placeholder for URL in configuration file.
- Write a shell script which will have command to replace placeholder with runtime parameter.
- Modify Dockerfile to execute the given shell script at run command.
- Provide URL as parameter in Docker run command.
Step 1: Snippet of Placeholder for URL in Configuration file:
APIBASEURL : ‘##DYNA_API_URI##’
Here, “##DYNA_API_URI##” is the placeholder which our script will look at runtime.
Step 2: Shell Script to do the actual replacement (Name this script as run.sh):
#!/bin/sh
sed -i “s|##DYNA_API_URI##|$PARAM_API_URI|g” /scripts/bundle.js
Here,
- “|” is used as separater
- “##DYNA_API_URI##” is the placeholder to look upon
- “$PARAM_API_URI” is the Runtime parameter which is passed from Docker run command and script will use it for substitution
- “/scripts/bundle.js” is the code which contains the placeholder declared in Step 1.
Step 3: Modify Dockerfile to execute shell script (run.sh):
COPY . /usr/src/app/
RUN chmod +x /usr/src/app/run.sh
CMD sh /usr/src/app/run.sh && /usr/sbin/nginx -g “daemon off;”
Here, we have copied “run.sh” present in our local repo to inside docker, then given execution permissions and at last providing command to execute this script file.
Step 4:Provide URL as parameter during Docker run command:
docker run -p 80:80 -e “PARAM_API_URI=http://192.168.99.100:8080/MyApp/” webui
Here, we have passed URL of our backend API as runtime parameter using “-e” property of Docker.
With these changes, Docker will execute the script file (which substitutes the PARAM URL into DYNA URL inside bundle.js).