Docker - Replacing appsettings.json values with environment variables (using Sed)



Create a shell script file to modify variables on the appsettings.json file, the script will read Environment Variables from the deploy docker image and replace values


Add a command to the build dockerfile to copy the shell script to the /docker-entrypoint.d/ folder in the docker deployed image (shell scripts in this folder will be executed automatically when the container is started)


1. Prepare the appsettings.json

We will replace the text {APP_BASE_URL} with the environment variable APP_BASE_URL:

{

  "AppBaseUrl": "{APP_BASE_URL}",

}

2. Create a shell script file


update-appsettings.sh:


# Replace the base URL in appsettings.json

sed -i "s@{APP_BASE_URL}@$APP_BASE_URL@g" appsettings.json


If you are using Windows, remember to convert from Windows-style to UNIX-style line endings:
in Notepad++, Go to Edit > EOL Conversion > UNIX/OSX Format. The next time you save the file, it will have UNIX-style line endings.


The sed (stream editor) utility is a line-oriented text parsing and transformation tool.

The syntax to find and replace text using the sed command is:

sed -i 's/<search regex>/<replacement>/g' <input file>


The command consists of the following:


  • -i tells the sed command to write the results to a file instead of standard output.
  • s indicates the substitute command.
  • / is the most common delimiter character. The command also accepts other characters as delimiters, which is useful when the string contains forward slashes.
  • <search regex> is the string or regular expression search parameter.
  • <replacement> is the replacement text.
  • g is the global replacement flag, which replaces all occurrences of a string instead of just the first.
  • <input file> is the file where the search and replace happens.

3. Copy shell script file to /docker-entrypoint.d/ folder


Add the following line to dockerfile:

COPY update-appsettings.sh /docker-entrypoint.d/


4. Build the dockerfile:


 docker build -f .\YourDockerfile.dockerfile -t yourimagename . --no-cache


5. Run the docker image in Docker Desktop:


 Add the APP_BASE_URL variable:



No comments:

Theme images by merrymoonmary. Powered by Blogger.