Externalising Spring Boot properties when deploying to Docker
I personally would consider two options:
Using an environment variable per config
app: image: my-app:latest ports: - "8080:8080" environment: SPRING_DATASOURCE_URL=jdbc:mysql://db:3306/table
Using
SPRING_APPLICATION_JSON
app: image: my-app:latest ports: - "8080:8080" environment: SPRING_APPLICATION_JSON: '{ "spring.datasource.url": "jdbc:mysql://db:3306/table", }'
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-alpine
VOLUME /tmp
ARG JAR_FILE
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["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:
- How do I pass environment variables to Docker containers?
- Limit JVM memory consumption in a Docker container