Home DockerDocker Secrets: Manage Sensitive Data Securely

Docker Secrets: Manage Sensitive Data Securely

by Knowledge Base Linux
Docker Secrets managing sensitive data for container services

Docker Secrets are the built-in way to hand sensitive data to containers without baking it into an image or leaving it visible in environment variables, and if you run Docker Swarm, they should be your default for passwords, API tokens, and TLS keys. The problem they solve is painfully common: a database password passed with -e ends up in docker inspect output, in shell history, and in any monitoring tool that dumps container configuration, while a secret baked into an image layer is visible to anyone who can pull the image, even after you delete the file in a later layer. Secrets avoid both traps. They are stored encrypted in the Swarm raft log, delivered to a container only over an encrypted channel, and mounted as a file under /run/secrets that the application reads at runtime. This guide shows how to create, rotate, and use Docker Secrets, and where they stop being enough.

Before going further, it is important to name the scope honestly. Docker Secrets are a Swarm feature, not a general Docker feature: docker run on a single host does not support –secret, and Docker Compose without Swarm mode ignores secrets unless you use the Compose file with swarm deployment or the newer Compose secrets support for local development. If you run standalone containers, you need a different pattern, such as a file mounted from a restricted directory or an external vault. For Swarm users, however, secrets are free, built in, and far safer than the environment-variable habit. If you are still learning Swarm fundamentals, our Docker Compose healthchecks guide is a useful companion for keeping the services that consume these secrets healthy.

Docker Secrets mounted as files inside a Swarm service container

Prerequisites

You need a Docker host with Swarm mode initialised, which you can do with docker swarm init on a single node for learning, and Docker Engine 20.10 or newer. You should be comfortable creating a service with docker service create and inspecting it with docker service inspect. The examples use a PostgreSQL service, but the pattern is identical for MySQL, Redis, web applications, and any service that needs a password or token at startup. You do not need a multi-node cluster: Swarm secrets work on a single-node swarm, and the same commands scale unchanged to a production cluster. Keep a terminal open on a manager node, because only managers can create and manage secrets.

Docker Secrets: Create and Use Your First Secret

Create a secret from a file, never from a command-line argument that could land in shell history. Write the password to a file with restricted permissions, create the secret from that file, and then delete or secure the file. The secret name is what services reference, so choose a name that describes the purpose and the target, such as db_password rather than a generic password that becomes ambiguous when a second service needs its own.

printf 'correct-horse-battery-staple' > db_password.txt
chmod 600 db_password.txt
docker secret create db_password db_password.txt
docker secret ls
rm db_password.txt

Now create a service that consumes the secret. The –secret flag mounts the secret as a file at /run/secrets/db_password inside every task container. The application reads that file instead of an environment variable. Many official images already support this pattern with a _FILE suffix: PostgreSQL reads POSTGRES_PASSWORD_FILE, MySQL reads MYSQL_PASSWORD_FILE, and similar conventions exist across the ecosystem. Using the _FILE variant keeps the secret out of the container environment entirely.

docker service create --name db   --secret db_password   -e POSTGRES_PASSWORD_FILE=/run/secrets/db_password   -e POSTGRES_USER=appuser   -e POSTGRES_DB=appdb   postgres:16

Verify that the secret is mounted and that it is not in the environment. Exec into a task container, list /run/secrets, and read the file to confirm the value arrived. Then inspect the service and confirm that docker service inspect shows only the secret name, not the value. That invisibility is the point: a secret that appears in inspect output is not a secret. The official Docker documentation on managing sensitive data with Docker Secrets describes the storage and delivery guarantees in full, including the encryption of secrets at rest in the raft log.

docker service ps db
docker exec $(docker ps -q -f name=db) ls -l /run/secrets/
docker exec $(docker ps -q -f name=db) cat /run/secrets/db_password

Docker Secrets: Compose Files, Rotation, and External Secrets

In a Compose file deployed as a stack, secrets are declared in two places: a top-level secrets section that defines where each secret comes from, and a per-service secrets list that mounts it. The file-based source is the cleanest for development, while the external option references a secret that already exists in the swarm, which is how you keep a stack file in version control without embedding the value. Note that a stack file that uses the file source creates the secret on deploy if it does not already exist, but it will not overwrite an existing secret, which is a safety feature during rotation.

services:
  db:
    image: postgres:16
    environment:
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password
    secrets:
      - db_password
secrets:
  db_password:
    external: true

Rotation is the part teams most often get wrong, because a Swarm secret is immutable: you cannot edit its value in place. The correct procedure is to create a new secret with a versioned name, update the service to use the new secret and drop the old one, and then remove the old secret once no service references it. Versioned names such as db_password_v2 make this explicit and let you roll back by pointing the service at the previous version. Update the service with docker service update –secret-rm and –secret-add, which triggers a rolling update so tasks restart one at a time with the new secret rather than all at once.

docker secret create db_password_v2 db_password_v2.txt
docker service update --secret-rm db_password   --secret-add db_password_v2 db
docker secret rm db_password

For a deeper comparison of storage choices for the services that use these secrets, see our guide to Docker volumes versus bind mounts, which explains when a volume, a bind mount, and a secret are each the right tool.

Docker Secrets: Limits, Standalone Containers, and Alternatives

Secrets have real limits you should plan around. They are only available to Swarm services, they are mounted read-only, and a secret is only delivered to nodes running tasks of a service that uses it, which is good for security but means a secret is not a general configuration store. Secrets are also not a substitute for a secrets manager when you need audit logs, fine-grained access policies, automatic rotation, or dynamic short-lived credentials: tools such as HashiCorp Vault or a cloud secrets manager provide those, and the right architecture often combines both, with Vault issuing a credential that a Swarm secret then delivers to the container. For standalone containers, the pragmatic equivalent is a file on the host with 600 permissions mounted read-only into the container, combined with the same _FILE environment pattern, and a host directory that only root and the service account can read.

Never store secrets in a Dockerfile with ENV or COPY, never commit them to git even in a private repository, and never pass them with docker run -e in a script that gets logged. If a secret has ever appeared in an image layer, treat it as compromised and rotate it: deleting the file in a later layer does not remove it from the earlier layer, and anyone with the image can extract it. The same rule applies to CI logs that print environment variables, so mask secret variables in your pipeline configuration before they can be echoed.

Troubleshooting

When a service fails to start with a secret error, check first that the secret exists with docker secret ls and that the service references the exact name, because a typo produces a clean error at service creation time rather than a confusing runtime failure. If the application reports that the password file is empty or missing, exec into the container and check /run/secrets: a missing mount usually means the service was created without the –secret flag or the Compose file declared the secret at the top level but forgot the per-service list. If the value is wrong, remember that secrets are immutable: you cannot fix a bad value by editing it, you must create a corrected version and update the service. And if docker secret rm refuses with an in-use error, list the services that reference it and update each one before retrying; Swarm protects you from deleting a secret that a running service still needs.

Permission errors inside the container usually trace back to the secret file mode: secrets are mounted with restrictive permissions by default, and an application running as a non-root user may need the secret to be readable by that user. You can set the target name, uid, gid, and mode in the Compose long syntax for a secret, which is the clean way to give a specific user access without loosening permissions for everyone. Finally, if a rotated secret does not take effect, confirm that the service actually updated: docker service ps shows whether tasks restarted, and an application that caches its database password at startup will not pick up a new value until it restarts, no matter how correctly the secret was delivered.

Conclusion

Docker Secrets give Swarm users a simple, built-in way to stop the two most common credential leaks: secrets in image layers and secrets in environment variables. Create secrets from files, consume them through _FILE environment variables, rotate them with versioned names and rolling updates, and reserve a full secrets manager for the audit and rotation features Swarm does not provide. With those habits, your stack files can live in version control, your images can be shared safely, and the only place a password exists in plaintext is the one file inside the container that actually needs it.

You may also like

KbLinux

Typically replies within a day

Hello, Welcome to the site. Please click below button for chatting me through Telegram.