spring-boot-docker-secret
spring-boot-docker-secret copied to clipboard
"spring.datasource.password" is no more a plain text password store in application.yml
Introduction
This demo shows how to load the docker secrets into spring boot environment properties, it prevents the password property such as spring.datasource.password being exposed as plain text in your application.yml file.
"spring.datasource.password" in application.yml
The spring.datasource.password property in our demo refers to other property ${docker-secret-mysql-user-pw}, which is preload by our EnvironmentPostProcessor implementation. The prefix docker-secret- helps to identify that the property is loaded from docker secret, and mysql-user-pw is the filename bind within the docker container under the /run/secrets folder.
spring:
datasource:
url: jdbc:mysql://mysql:3306/testdb
username: dba
password: ${docker-secret-mysql-user-pw}
# The "docker-secret.bind-path" property trigger the EnvironmentPostProcessor to load
# the bind docker secrets as password property
docker-secret:
bind-path: /run/secrets
docker-compose.yml
The spring-boot service bind the secret mysql-user-pw which store the password of user dba.
version: '3.7'
services:
mysql:
image: mysql:8
environment:
- MYSQL_ROOT_PASSWORD=yes
- MYSQL_DATABASE=testdb
- MYSQL_USER=dba
- MYSQL_PASSWORD_FILE=/run/secrets/mysql-user-pw
secrets:
- mysql-user-pw
spring-boot:
image: kwonghung/spring-boot-docker-secret:latest
ports:
- "8080:8080"
environment:
- SPRING_PROFILES_ACTIVE=docker-stack
secrets:
- mysql-user-pw
secrets:
mysql-user-pw:
external: true
EnvironmentPostProcessor Implementation
The DockerSecretProcessor implements the EnvironmentPostProcessor interface, it loads all the files under the /run/secrets folder as environment properties.
For this demo, the docker secret my-user-pw is bind as file /run/secrets/mysql-user-pw" in the docker image, which is loaded as the spring boot property docker-secret-mysql-user-pw.
META-INF/spring.factories
And you have to declare your EnvironmentPostProcessor class in META-INF/spring.factories file
org.springframework.boot.env.EnvironmentPostProcessor=hung.org.DockerSecretProcessor
Run the demo as docker stack
- Get the docker swarm ready, or initiate a new swarm.
docker swarm init
- Define the docker secret in the manager node.
echo -n "password"|docker secret create mysql-user-pw -
- Download the docker-compose.yml.
wget -qO- --no-cache https://raw.githubusercontent.com/kwonghung-YIP/spring-boot-docker-secret/master/docker-compose.yml
- Start the docker stack.
docker stack deploy --compose-file docker-compose.yml demo
- Try the link.
curl http://localhost:8080/