Externalising Spring Boot properties when deploying to Docker Externalising Spring Boot properties when deploying to Docker docker docker

Externalising Spring Boot properties when deploying to Docker


DOCKER IMAGE CONFIGURATION

If you look to the way Spring recommends to launch a Spring Boot powered docker container, that's what you find:

FROM openjdk:8-jdk-alpineVOLUME /tmpARG JAR_FILECOPY ${JAR_FILE} app.jarENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"]

That means your image extends openjdk and your container has its own environment. If you're doing like that, it would be enough to declare what you want to override as environment properties and Spring Boot will fetch them, since environment variables take precedence over the yml files.

Environment variables can be passed in your docker command too, to launch the container with your desired configuration. If you want to set some limit for the JVM memory, see the link below.


DOCKER COMPOSE SAMPLE

Here you have an example of how I launch a simple app environment with docker compose. As you see, I declare the spring.datasource.url property here as an environment variable, so it overrides whatever you've got in your application.yml file.

version: '2'services:    myapp:        image: mycompany/myapp:1.0.0        container_name: myapp        depends_on:        - mysql        environment:            - SPRING_DATASOURCE_URL=jdbc:mysql://mysql:3306/myapp?useUnicode=true&characterEncoding=utf8&useSSL=false        ports:            - 8080:8080    mysql:        image: mysql:5.7.19        container_name: mysql        volumes:            - /home/docker/volumes/myapp/mysql/:/var/lib/mysql/        environment:            - MYSQL_USER=root            - MYSQL_ALLOW_EMPTY_PASSWORD=yes            - MYSQL_DATABASE=myapp        command: mysqld --lower_case_table_names=1 --skip-ssl --character_set_server=utf8

See also:


I personally would consider two options:

  1. Using an environment variable per config

    app:  image: my-app:latest  ports:    - "8080:8080"  environment:     SPRING_DATASOURCE_URL=jdbc:mysql://db:3306/table
  2. Using SPRING_APPLICATION_JSON

    app:  image: my-app:latest  ports:    - "8080:8080"  environment:    SPRING_APPLICATION_JSON: '{      "spring.datasource.url": "jdbc:mysql://db:3306/table",    }'


Personally I'd use Spring Cloud Config Server instead of trying to set up properties files all over the place.

tl;dr it allows you to hold properties in git (which allows version control, branching etc) at a per environment/profile level in a centralised location, which are then served up by REST. Spring Boot has full support for it; in effect it's just another property source that ends up in your Environment.

https://spring.io/guides/gs/centralized-configuration/