Table of Contents
How to use Spring Profiles with Docker Containers
Assuming that you are quite familiar with the spring profiles and looking for injecting profiles in a Docker environment. There are couple of ways of doing it namely
- Passing Spring Profile in Dockerfile
- Passing Spring Profile in Docker run command
- Passing Spring Profile in DockerCompose
In this tutorial, I will try to capture all these 3 scenarios.
Passing Spring Profile in a Dockerfile
From command prompt of your system, any spring boot application can be run with “java -jar” command.The profiles need to be passed as an argument like this “-Dspring.profiles.active=dev“. For Spring MVC applications other 2 below methods will work fine.
java -Djava.security.egd=file:/dev/./urandom -Dspring.profiles.active=dev -jar rest-api.jar
Similarly, when using dockerfile we need to pass the profile as an argument, have a look at one of the Dockerfile for creating a spring boot docker image
Below an example on spring boot project dockerfile
ADD target/my-api.jar rest-api.jar
RUN bash -c 'touch /pegasus.jar'
ENTRYPOINT ["java", "-Djava.security.egd=file:/dev/./urandom","-Dspring.profiles.active=dev","-jar","/rest-api.jar"]
Pay attention to the last line ENTRYPOINT, in this line we are passing the java command to execute the jar file and all arguments have been passed as comma separated values. “-Dspring.profiles.active=dev” is where we are passing the dev profile, you can replace dev with the profile name you want.
Passing Spring Profile in Docker run
You can also pass spring profile as an environment variable while using docker run command using the -e flag. The option -e “SPRING_PROFILES_ACTIVE=dev” will inject the dev profile to the Docker container.
docker run -d -p 8080:8080 -e "SPRING_PROFILES_ACTIVE=dev" --name rest-api dockerImage:latest
Passing Spring Profile in DockerCompose
If you are on DockerSwarm or using compose file for deploying docker images the Spring profile can be passed using the environment: tag in a docker-compose file, as shown below