How to Secure Docker Containers with Docker Secrets

How to Secure Docker Containers with Docker Secrets. Docker has made it much easier to package and run containerized applications. Offering unparalleled flexibility and efficiency, Docker is a fantastic tool for smaller or locally developed software projects. However, as your projects grow in complexity, you may discover that Docker can present a new challenge – managing and safeguarding sensitive data within your containers.

In this blog post, we’ll go over the essential aspects of securing Docker containers with Docker Secrets. We explore best practices for managing secrets in Docker, including how to store them securely and minimize their exposure to potential threats

What is Docker Secrets?

Docker Secrets is a feature within Docker that allows you to securely manage and store sensitive information (secrets), such as passwords, API keys, certificates, and other credentials. In short, it allows you to pass sensitive information to containers securely without having to hardcode it into container images. As a result, you achieve authorized access, centralized control, and overall integrity in your containerized environment.

Here’s a simplified overview of how Docker secrets work:

  1. Creation: You create secrets by using the Docker CLI or API, and they can encompass various sensitive data, such as passwords, API keys, or certificates.
  2. Distribution: Docker Swarm or Kubernetes orchestrators distribute the secrets to only the nodes that need them.
  3. Isolation: Secrets are stored securely and isolated from the filesystem, ensuring that they are only accessible by the Docker daemon and the specific services or containers that have been granted access.
  4. Mounting: Containers that require access to secrets can “mount” them as files or environment variables during runtime.

Creating Docker Secrets

Before creating Docker Secrets, you need access to the Docker CLI (Command-Line Interface). Ensure you’re logged in to your Docker host or cluster where you intend to create and manage secrets.

You’ll typically start by generating the sensitive data you want to protect. For example, if you want to create a secret for a database password, use an echo command in Linux or a similar approach in other environments:

					echo "mysecretpassword" | docker secret create db_password -

In this example, "mysecretpassword" is the sensitive information, and db_password is the name of the secret. The - at the end of the command indicates that the secret data should be read from the standard input.

After running the above command, Docker creates the secret and return a long, unique identifier for the secret. Verify that the secret was successfully created by running the following command:

					docker secret ls

Once the secret is created, use it in your services. You can associate the secret with one or more services running in Docker Swarm or Docker Compose. We’ll show you how to go about it below:

Using Docker Secrets with Docker Swarm

Docker Swarm is Docker’s native container orchestration platform. Designed to manage and deploy a cluster of Docker containers as a single, cohesive unit. One of the key features of Docker Swarm is its ability to handle secrets management through Docker Secrets. Here, we’ll dive deeper into how Docker Secrets can be effectively utilized within a Docker Swarm environment:

Access Docker Swarm

Ensure that you have initialized a Docker Swarm cluster. If not, you can initialize a Swarm cluster on your Docker host using the following command:

					docker swarm init

Create a Docker Secret

Create a docker secret via the process shown in the previous section. 

Associate Secrets with a Service

Define or modify a Docker Swarm service in your docker-compose.yml file or using the docker service create command. Add a secrets section to specify which secrets the service needs.

    image: myapp-image
      - source: db_password
        target: /app/db_password

Deploy the Service

Deploy the service to the Docker Swarm cluster using the docker stack deploy or docker service create command. For example:

					docker stack deploy -c docker-compose.yml myapp-stack


Access Secrets in Containers

The secrets you’ve associated with the service are available as files in the container. Access these secrets in your application code or scripts by reading the corresponding file. For instance, in a Python application:

					with open('/app/db_password', 'r') as file:
    db_password =

Using Docker Secrets with Compose

Using Docker Secrets with Docker Compose allows you to securely manage sensitive data for local development and testing purposes. Here’s a step-by-step guide on how to use Docker Secrets with Docker Compose:

Create Docker Secrets

First, create the Docker Secrets you need.

Define Your Docker Compose File

Create a Docker Compose file (e.g., docker-compose.yml) or modify an existing one to include your services and reference the secrets. Here’s an example:

					version: '3.8'
    image: myapp-image
      - db_password
    external: true

In this example, we have a service named “myapp”. The service has a secret named “db_password.”

Reference Secrets in Service Definitions

In your service definitions, specify the secrets you want to use. In the example above, the myapp service references the db_password secret.

Deploy the Docker Compose Stack

Deploy your Docker Compose stack using the following command:

					docker-compose up -d


This starts your services, and they have access to the Docker Secrets you defined.

Access Secrets in Containers

The secrets you’ve associated with the service will be available as files in the container. Access these secrets in your application code or scripts by reading the corresponding file. For instance, in a Python application:

					with open('/run/secrets/db_password', 'r') as file:
    db_password =


Local Testing and Development

Using Docker Secrets with Docker Compose is particularly useful for local development and testing environments, allowing you to keep your sensitive data secure without hardcoding it into your application code or configuration files.

Cleaning Up

When you’re finished testing, stop and remove the Docker Compose stack:

					docker-compose down


Docker Secrets Best Practices

In this section, we give you tips to minimize the risk of secrets exposure. You get insights into managing and protecting confidential data within Dockerized environments

1. Exclude any files containing secrets from being inadvertently added to your Git repository

When you mount secrets into containers from local files, there’s a potential risk of these files accidentally becoming part of your repository. To prevent this, specify the paths of files containing secrets in your .gitignore file. This ensures that when you run ‘git add .’, you won’t unintentionally stage these sensitive values, bolstering the security of your version-controlled codebase

2. Structure your Docker images with security in mind

You should adopt a design approach whereby applications consistently retrieve secrets from the filesystem rather than relying on environment variables. This way, you mitigate the potential for user errors and shortcuts.

3. Use secrets for all sensitive values

Often, your team of developers may struggle to decide whether a value needs to be treated as a secret. Deal with this issue by communicating your organization’s secrets requirements, including the identification of candidate values. Generally, a secret is anything that’s valuable to a malicious actor, or which might expose other data. Overall, secrets aren’t necessarily confined to certificates and passwords.

4. Rotate secrets regularly

Change or update sensitive information, such as passwords or cryptographic keys, on a scheduled basis. The goal is to limit the exposure window in case a secret is compromised, and it helps maintain a higher level of security over time.

5. Monitor and audit

Actively track and log events related to the creation, access, and use of secrets. This way, you get visibility into potential security incidents and ensure compliance with security policies.

Thank you for reading How to Secure Docker Containers with Docker Secrets. We shall conclude this article topic and summarize below,.

How to Secure Docker Containers with Docker Secrets Conclusion

Leveraging Docker secrets is a critical step in enhancing the security posture of your containerized applications. By responsibly managing sensitive information, you not only mitigate the risk of unauthorized access but also streamline the process of maintaining, updating, and auditing secrets. Docker secrets provide a robust mechanism for securing your containers, contributing to a more resilient and trustworthy deployment of Dockerized applications.

Avatar for Richard Kanyoro
Richard Kanyoro

The world’s biggest problems can be solved by progressively solving the little ones. I write to help people solve the “little” tech problems they face.

0 0 votes
Article Rating
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x