How do you inject Docker secrets (files/data from /run/secrets) into the application.properties files? Is it safe to use environment variables?
Advertisement
Answer
First of all, usage of environment variables for secret data for the application.properties
isn’t safe.
You have mainly two options when talking about Secrets.
If you are using Docker Secrets without Docker Swarm then you can directly load the whole
application.properties
in a secret, mount it under/run/secrets
and refer to it as configuration file with the Spring flags.If you are using Docker Secrets with Docker Swarm then you can just store as secret the concrete fields that you’re interested in and relate to them using the Configuration Templates of Swarm.
Example:
echo -n "myUser" | docker secret create db_user - echo -n "myPass" | docker secret create db_password - echo -n "jdbc://..." | docker secret create db_url -
application.properties.tmpl
spring.datasource.url={{ secret "db_url" }} spring.datasource.user={{ secret "db_user" }} spring.datasource.password={{ secret "db_password" }}
docker-compose.yml
version: '3.9' services: api: image: yourapp:1.0.0 configs: - source: application.properties target: /usr/app/config/application.properties secrets: - db_url - db_user - db_password configs: application.properties: template_driver: golang file: ./application.properties.tmpl name: myapp.application.properties secrets: db_url: external: true db_user: external: true db_password: external: true
When you deploy with docker stack deploy -c docker-compose.yml myapp
, it will automatically populate the configuration with the contents of the secrets and it will mount it in the destination path.