Deepthi
Deepthi

Reputation: 545

How to create a properties file via Dockerfile with dynamic values passed in docker run?

I am relatively new to Docker. Maybe this is a silly question.

My goal is to create an image which has a system.properties file, which as the name says, is a properties file with key value pairs. I want to fill the values in this file dynamically. So I think the values need to be passed as environment variables to the Docker run command.

For example, if this is what i want in my system.properties file:

buildMode=true
source=/path1

I want to provide the values to this file dynamically, something like:

$ docker run -e BUILD_MODE=true -e SOURCE='/path1' my_image

But I'm stuck at how I can copy the values into the file. Any help will be appreciated.

Note: Base image is linux centos.

Upvotes: 2

Views: 6211

Answers (1)

David Maze
David Maze

Reputation: 160013

As you suspect, you need to create the actual file at runtime. One pattern that’s useful in Docker is to write a dedicated entrypoint script that does any required setup, then launches the main container command.

If you’re using a “bigger” Linux distribution base, envsubst is a useful tool for this. (It’s part of the GNU toolset and isn’t available by default on Alpine base images, but on CentOS it should be.) You might write a template file:

buildMode=${BUILD_MODE}
source=${SOURCE}

Then you can copy that template into your image:

...
WORKDIR /app
COPY ...
COPY system.properties.tmpl ./
COPY entrypoint.sh /
ENTRYPOINT ["/entrypoint.sh"]
CMD ["java", "-jar", "app.jar"]

The entrypoint script needs to run envsubst, then go on to run the command:

#!/bin/sh
envsubst <system.properties.tmpl >system.properties
exec "$@"

You can do similar tricks just using sed(1), which is more universally available, but requires potentially trickier regular expressions.

Upvotes: 3

Related Questions