Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 231 of 8023. Docker Orchestration and StorageFree lesson

Injecting Secrets into Distributed Swarm Services

Learners will safely distribute sensitive configuration data, such as API keys and database credentials, directly to containers using Swarm secrets.

In this lesson, you will learn how to securely inject sensitive credentials directly into your distributed Swarm services so that your containers can access them without ever exposing them in your source code or image layers.

The Problem with Environment Variables

In earlier lessons, we learned how to externalize configurations using .env files. While useful for non-sensitive data, environment variables are often visible to any process with root access to the container or through inspection commands. When running services across a multi-node Swarm cluster, we need a way to distribute sensitive data—like database passwords or API keys—that remains encrypted during transit and is only visible to the specific containers that need it.

How Swarm Secrets Work

Docker Swarm treats secrets as first-class citizens. When you create a secret, Docker stores it in the Raft consensus log, encrypted at rest. When you assign a secret to a service, the Swarm manager securely distributes that data to the specific worker nodes running your tasks.

Crucially, the secret is not mounted as a file on the host machine. Instead, it is mounted as a temporary, in-memory filesystem inside the container at /run/secrets/<secret_name>. This means the sensitive data never touches the container's disk or the underlying host's persistent storage.

Practical Implementation

To use a secret, you first create it via the CLI: echo "my-db-password" | docker secret create db_password -

Then, you grant your service access to that secret within your deployment configuration:

services:
  database:
    image: postgres
    secrets:
      - db_password

secrets:
  db_password:
    external: true

Once the service starts, your application code can simply read the file /run/secrets/db_password to retrieve the credential. Because this happens in memory, it is significantly more secure than passing plain-text strings through environment variables. If a container is compromised, the secret exists only in volatile memory, reducing the risk of credential leakage.

Key Takeaway: By using Docker Secrets, you decouple sensitive credentials from your container images and ensure they are only delivered to authorized tasks in-memory, keeping your production environment locked down.