Docker Secrets, Multiple Environments, and Java Spring Boot

Here’s an easy way to keep your Docker secrets in your version control, without having to create multiple Dockerfiles for each environment.

Before you continue, I assume you have a decent understanding of:

  1. Docker (compose)
  2. Java

We’ll create a Dockerfile with a generic secret name, and then we can map an environment specific secret to the generic secret name our Docker container is expecting.

First let’s go ahead and create the docker secrets in our environment:

➜  echo "devpwd" | docker secret create my-secret-DEV -
kgilm...
➜ echo "prdpwd" | docker secret create my-secret-PRD -
w8fbl...
➜ docker secret ls
ID NAME DRIVER CREATED UPDATED
kgilm... my-secret-DEV 13 seconds ago 13 seconds ago
w8fbl... my-secret-PRD 2 seconds ago 2 seconds ago

Here’s our (only) Dockerfile:

Only thing to take away from this is snippet on line 11:

-Dweb.security.api.password=”$(cat /run/secrets/my-secret)”

We tell the container to inject a variable called “web.security.api.password” into the environment. The value comes from “$(cat /run/secrets/my-secret)”. When we add a Docker Secret to our container, it is automatically added to a file under the /run/secrets directory.

Here’s our docker-compose (DEV):

The big take away from this is that we declare a secret called

my-secret-DEV

and we map it to the secret that the container was expecting which we declared in the Dockerfile above, called

my-secret

So the only difference between a production compose file would be the secret name.

So, to use them in our Java code, we just have to treat it like any other resource variable. We just use the property name

web.security.api.password

that we declared in the Dockerfile to have access to the environment variable.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade