Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cant change content of a file using environment variable in docker image at run time

I am creating an image that will run a java application inside. Java application process creation command takes parameters from a configuration file inside of the image. I want to use environment variables to set those config file contents. I don't know how to modify those values. When I just simply copy the file it just copies the env variable name.

FROM base-image
ARG SERVICE=test
ENV SERVICE $SERVICE
COPY runtime.properties /tmp/
RUN chmod 700 /tmp/runtime.properties
# here i am creating java process using those properties

runtime.properties

# few lines
SERVICE_NAME='${SERVICE}'
# few lines
like image 625
Tamizharasan Avatar asked Oct 19 '25 14:10

Tamizharasan


1 Answers

Java will read static property files literally and doesn't do any interpolation of these files before running. There are a few options available to you.

One is to add to the Dockerfile a step to search and replace the value in the file.

FROM java:alpine
ARG SERVICE=test
ENV SERVICE $SERVICE
COPY runtime.properties /tmp/
RUN sed -i -e 's/${SERVICE}/asd/g' /tmp/runtime.properties 
RUN chmod 700 /tmp/runtime.properties

Another option is to change the properties file to a java class and read the environment variable directly. This gives the advantage of having the default value in the code for standalone running.

public enum LocalConfig {
    INSTANCE;

    private String service = System.getenv("SERVICE") ==null ? "test" : System.getenv("SERVICE");
}

Yet another option if you have lots of environment variables is to use envsubst, this will replace all of the environment variables in the file. But this depends on what your base image is. https://www.gnu.org/software/gettext/manual/html_node/envsubst-Invocation.html

FROM java
ARG SERVICE=test
ENV SERVICE $SERVICE
COPY runtime.properties /tmp/
RUN envsubst < /tmp/runtime.properties > /tmp/runtime.properties 
RUN chmod 700 /tmp/runtime.properties

The last option I can think of is interpreting the environment variables after you inport the file. There is a good thread on that here: Regarding application.properties file and environment variable

like image 196
Peter Grainger Avatar answered Oct 22 '25 05:10

Peter Grainger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!