Skip to main content

How to use Spring Profiles with Docker Containers

 

How to use Spring Profiles with Docker Containers

Introduction

Spring Profiles are an effective way of implementing environment independent code. The properties file or @Beans can be selected dynamically at run time based on the profile injected.
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.

Read Here: How to create Docker image of Standalone Spring MVC project

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.

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

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.

 

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

 

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Bitnami