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 -
➜ echo "prdpwd" | docker secret create my-secret-PRD -
➜ docker secret ls
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:”$(cat /run/secrets/my-secret)”

We tell the container to inject a variable called “” 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


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


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

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store