Docker

Docker Compose Secrets

Docker Compose Secrets is a feature introduced to Docker in version 1.31, allowing us to manage sensitive data separately from the application code and configuration. This ensures that sensitive data is not exposed in Dockerized applications.

Prerequisites

Ensure you have the following:

  • Docker installed on your system.
  • Docker Compose installed on your system.
  • A basic understanding of Docker Compose and YAML syntax.

Basic Docker Compose

Let us start by creating a Docker Compose project.

Create a directory for the project and create a docker-compose.yml file in it.

$ mkdir basics

$ cd basics

$ touch docker-compose.yml

We can then edit the docker compose file with docker secrets.

version: '3'
services
:
  app
:
    image
: app:latest
    environment
:
     - DB_PASSWORD_FILE=/run/secrets/db_password
secrets
:
  db_password
:
    file
: ./secrets/db_password.txt

In the example above, we define a service called ‘app’ and a secret called ‘db_password.’

In this case, DB_PASSWORD_FILE is an environment variable in the service that points to the location of the secret file.

Create Secret Files

In the next step, create a directory called ‘secrets’ within the project directory.

$ mkdir secrets

Next, add the secret files there. For example, create secrets/db_password.txt and add the database password in it.

$ touch secrets/db_password.txt

Using Secrets

Once we have defined all the secrets and files, we can use the secret environment variables in the docker-compose file.

We can access the secret file in the application, as shown in the example Python below:

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

db_password = file.read()

Conclusion

Docker Compose Secrets is a powerful feature for managing sensitive information in containerized applications.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list