✦ For everyone, free.

Practical knowledge for real and everyday life

Home

9.2.5.3 File Secret Access

A focused guide to File Secret Access, connecting core concepts with practical Docker and container operations.

File secret access is the pattern an application follows to retrieve a sensitive value by reading it directly from its mounted secret file, rather than reading it from an environment variable, requiring the application's own code to specifically support this file-based access pattern.

The Basic File-Reading Pattern

An application reads the secret's value directly from its known, mounted file path at startup or whenever the value is actually needed.

def get_secret(name):
    with open(f'/run/secrets/{name}') as f:
        return f.read().strip()

db_password = get_secret('db-password')
Why Some Applications Need Adaptation to Support This Pattern

An application originally built to expect its configuration entirely through environment variables doesn't automatically know to look for a mounted secret file instead — adapting it to check for and prefer a secret file when present is sometimes necessary.

import os

def get_db_password():
    secret_path = '/run/secrets/db-password'
    if os.path.exists(secret_path):
        with open(secret_path) as f:
            return f.read().strip()
    return os.environ.get('DB_PASSWORD')

This pattern prefers the more carefully handled secret file when available, while still falling back to an environment variable for compatibility with environments not using Compose secrets at all.

Why Some Official Images Already Support This Pattern Natively

Certain official images are specifically built to recognize a _FILE-suffixed environment variable convention, pointing to a secret-mounted file, without requiring any custom application code changes at all.

services:
  db:
    image: postgres:16
    environment:
      - POSTGRES_PASSWORD_FILE=/run/secrets/db-password
    secrets:
      - db-password

This convention, supported natively by the postgres image, reads the actual password from the referenced secret file rather than expecting the password directly as an environment variable's value.

Why File Secret Access Matters

Understanding this file-based access pattern, and whether a given application or image already supports it natively, is essential to correctly and effectively making use of Compose's secrets mechanism for genuinely sensitive configuration values.