Skip to content

Using secrets with docker compose in PSS®X development

Compose’s secrets system is the most accessible for everyday use. It’s also your only option if you’re not using Docker Swarm.

Secrets are defined in Compose files within the top-level secrets field. Each named secret references a file in your working directory. When you run docker compose up, Compose will automatically mount that file into the container.

Secrets are mounted to a predictable container path: /run/secrets/<secret_name>. You should configure your containerized application to read the secret’s value from that path.

Use secrets

Getting a secret into a container is a two-step process;

  • Define the secret using the top-level secrets element in your Compose file.
  • Update your service definitions to reference the secrets they require with the secrets attribute.

Step 1 : Top-level secrets element

Services can only access secrets when explicitly granted by a secrets attribute within the services top-level element.

The top-level secrets declaration defines or references sensitive data that is granted to the services in your Compose application. The source of the secret is either file or environment.

  • file: The secret is created with the contents of the file at the specified path.
  • environment: The secret is created with the value of an environment variable.

Example : file

secrets:
  mssql_sa:
    file: ./mssql_sa.pwd

Example : environment

secrets:
  token:
    environment: "OAUTH_TOKEN"

Step 2: Update your service definitions

Update your service definitions to reference the secrets they require with the secrets attribute. Compose grants access to secrets on a per-service basis.

Unlike the other methods, this permits granular access control within a service container via standard filesystem permissions.

services:
  sqlserver:
    ...
    environment:
      - MSSQL_SA_PASSWORD_FILE=/run/secrets/mssql_sa
    secrets:
      - mssql_sa

secrets:
  mssql_sa:
    file: ./mssql_sa.pwd

In the following example, the npm_token secret is made available at build time. Its value is taken from the NPM_TOKEN environment variable.

services:
  myapp:
    build:
      secrets:
        - npm_token
      context: .

secrets:
  npm_token:
    environment: NPM_TOKEN

Secrets in Docker without Swarm?

Note

If you’re using Docker Compose without a Swarm cluster or if you just want to work with secrets without Swarm, you can do that.

Docker Compose was originally meant for development, not production. That’s why secrets weren’t a big concern initially. If you use secrets without Swarm, they will still work, but they won’t be as secure as in Swarm. They’ll be just like regular files mounted on your computer, not encrypted. So, it’s okay for development, but in production, it’s not secure.