How do you inject Docker secrets (files/data from /run/secrets) into the application.properties files? Is it safe to use environment variables?
CodePudding user response:
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.
CodePudding user response:
If you subscribe to the Twelve-Factor App philosophy on configuration, environment variables are the appropriate place to store secrets for your app.
With Spring Boot, specifically, it is possible to set them as env vars in your container following an UPPER_SNAKE_CASE
naming convention which maps to the keys in your application.properties
or application.yml
file. For example, if you wanted to set a database password as if it were defined as database.password=i-am-the-password
in your application.properties
file but omit this from version control, you could do:
$ export DATABASE_PASSWORD=i-am-the-password
(Or another method of injecting the env var into your container runtime.)
The database password would then be accessible in Java code as:
import org.springframework.beans.factory.annotation.Value;
public class Example {
private final String databasePassword;
public Example(
@Value("${database.password}") String databasePassword) {
this.databasePassword = databasePassword;
}
}