5

I am running a spring boot app on a docker swarm stack and would would like to use docker secrets for token secrets, api keys, etc... It was no problem to create the secrets and make them available in my running docker container with the following compose file:

version: "3.7"
services:
  app:
    image: myimage
    environment:
      tokenSecret: /run/secrets/tokenSecret
      apiKey: /run/secrets/apiKey
    secrets:
      - tokenSecret
      - apiKey

  frontend:
    .....

  db:
    .....

secrets:
  tokenSecret:
    external: true
  apiKey:
    external: true

The secrets were created by printf some_secret | docker secret create tokenSecret -

Before using docker secrets, I was storing the properties in my application.properties file:

tokenSecret: some_secret
apiKey: some_key

and could access them by:

@Component
public class AppProperties {

    private Environment environment;

    @Autowired
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    public String getTokenSecret(){
        return environment.getProperty("tokenSecret");
    }

    public String getApiKey(){
        return environment.getProperty("apiKey");
    }
}

Now, using docker secrets and deleting the application.properties, the getTokenSecret and getApiKey methods are returning the file location of the secrets in the docker container: "/run/secrets/tokenSecret" instead of the secret's content. It seems to be an easy task to load the secret's content from the container file system into my application but I have still no idea what would be the best way to do it.

puhlerblet
  • 113
  • 5

1 Answers1

2

The easiest way is to add a custom docker-entrypoint.sh to your Dockerfile which opens the file. Something like:

#!/bin/sh

export TOKEN_SECRET=${TOKEN_SECRET:=`cat ${TOKEN_SECRET_FILE}`}

java -noverify -XX:TieredStopAtLevel=1 -Djava.security.egd=file:/dev/./urandom -jar app.jar

And in your docker-compose.yml for the stack:

version: '3.7'

services:
  serviceName:
    ...
    environment:
      TOKEN_SECRET_FILE: /run/secrets/tokenSecret
    secrets:
      - tokenSecret

secrets:
  tokenSecret:
    external: true

In this way, for development environment (without Swarm), you can simply pass TOKEN_SECRET with your non-encrypted development secret, as you did before

HelLViS69
  • 299
  • 1
  • 4
  • 15