Use File Secrets in Docker Compose

There is a way to use Docker secrets without Swarm. It is quite simple - to fake it with secret files stored locally.

Suppose we have the following in our work directory:

WorkDir
    └── Dockerfile
    └── docker-compose.yml
    └── secrets
      └── JENKINS_USER
      └── JENKINS_PASS

This way we will need to create a file for every secret we want to make available inside the service at /run/secrets

First, we add these secrets at the end of our docker-compose.yml file

secrets:
  jenkins-username:
    file: ./secrets/JENKINS_USER
  jenkins-password:
    file: ./secrets/JENKINS_PASS

Then we add them into the service we want to create:

version: '3.7'
services:
  jenkins:
    restart: ###
    user: ###
    build: ###
    image: ###
    ports: ###
    volumes: ###
    secrets: ###
      - jenkins-username
      - jenkins-password

There is a practical behind this whole theoretical exercise - to create an admin Jenkins user securely. So we edit the basic.security002.groovy file a bit to let it access the secrets we have created above:

// def adminUsername = System.getenv("JENKINS_USER")
// def adminPassword = System.getenv("JENKINS_PASS")
def adminUsername = new File("/run/secrets/jenkins-username").text.trim()
def adminPassword = new File("/run/secrets/jenkins-password").text.trim()

This is a good option to use during development. In production we will not be building images and mounting local files, but it is a whole different story anyway.

October 23, 2019   (v.35eeba0)