4

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
Tamizharasan
  • 293
  • 1
  • 5
  • 18

2 Answers2

6

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

Peter Grainger
  • 4,539
  • 1
  • 18
  • 22
2

You can write the environment variable to runtime.properties by using bash:

RUN echo "SERVICE_NAME=$SERVICE" > /tmp/runtime.properties

or if static content already exists in that file, substitute > with >> to append.

Alwinius
  • 1,941
  • 1
  • 9
  • 12
  • This won't help, it simply replace all the content from the file by writing only the variable that I gave. – Tamizharasan Aug 08 '18 at 11:35
  • Please read my last sentence again. If you want to append instead of overwrite, use `RUN echo "SERVICE_NAME=$SERVICE" >> /tmp/runtime.properties` – Alwinius Aug 10 '18 at 07:43