How to pass Java options/variables to Springboot app in docker run command

TechiRik picture TechiRik · Jun 29, 2019 · Viewed 16.6k times · Source

I have a Spring Boot application which uses profiles to configure in different environments. I want to pass this profile information as a parameter to my docker run command. How do I go about doing it?

Here is my dockerfile

FROM openjdk:8-jdk-alpine
ARG JAR_FILE=target/demo-app-1.0-SNAPSHOT.jar

COPY ${JAR_FILE} /opt/lib/demo-app.jar

EXPOSE 80

# ENTRYPOINT ["java","-Dspring.profiles.active=dockerdev","-jar","/opt/lib/demo-app.jar"]
# Above line works, but not desired as profile will change in diff envs
ENTRYPOINT ["java","-jar","/opt/lib/demo-app.jar"]

I have tried the following, but, none works

docker run -p 8000:80 demo-app -Dspring.profiles.active=dockerdev

docker run -p 8000:80 demo-app --rm -e JAVA_OPTS='-Dspring.profiles.active=dockerdev'

Please help.

Clarification: I am using multiple profiles. Hence I do not want the active profile to be mentioned within the application or the docker file. Instead, I want to use the same application and docker file and run it in different environments, and pass the active profile to be used in the docker run command. Apologies if anything above did not clarify that.

Answer

Michał Krzywański picture Michał Krzywański · Jun 29, 2019

Solution 1

You can override any property from your configuration by passing it to docker container using -e option. As explained in Externalized configuration the environment variable name should be uppercased and splitted using underscore. So for example to pass spring.profiles.active property you could use SPRING_PROFILES_ACTIVE environment variable during container run :

docker run -p 8000:80 -e SPRING_PROFILES_ACTIVE=dockerdev demo-app

And this variable should be picked automatically by Spring from environment.

Solution 2

Change Dockerfile to :

FROM openjdk:8-jdk-alpine
ARG JAR_FILE=target/demo-app-1.0-SNAPSHOT.jar

# environment variable with default value
ENV SPRING_PROFILE=dev

COPY ${JAR_FILE} /opt/lib/demo-app.jar

EXPOSE 80

#run with environment variable
ENTRYPOINT ["java","-Dspring.profiles.active=${SPRING_PROFILE}","-jar","/opt/lib/demo-app.jar"]

and then run the container passing the environment variable :

docker run -p 8000:80 --rm -e SPRING_PROFILE=dockerdev demo-app