0

I hope you are well. I have some questions about Docker secrets:

  • How can I work with secrets securely using Docker Compose, given that their content is exposed in /run/secrets and can be easily accessed with cat both inside and outside the containers?

Additionally, to run as a user with minimal permissions inside the container, I need to keep the permissions of the secret files open on the host machine, because if I set them as root-only, the non-root user inside the container will not be able to read their content and the application will not be able to work with the information.

This is how I have been working with secrets in my Docker Compose.

services:
  app:
    [...]
    depends_on:
      - db
    secrets:
      - postgres_db
      - postgres_server
      - postgres_user
      - postgres_password
    [...]
    networks:
      - app_net
      - db_net
  
  db:
    image: postgres:16.3-alpine3.20
    restart: always
    environment:
      POSTGRES_DB_FILE: /run/secrets/postgres_db
      POSTGRES_USER_FILE: /run/secrets/postgres_user
      POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
    secrets:
      - postgres_db
      - postgres_user
      - postgres_password
    [...]

secrets:
  postgres_db:
    file: ./secrets/postgres_db.txt
  postgres_server:
    file: ./secrets/postgres_server.txt
  postgres_user:
    file: ./secrets/postgres_user.txt
  postgres_password:
    file: ./secrets/postgres_password.txt

1 Answer 1

0

Use environment variables, like this example:

.env

# remember to set correct permissions to protect this file
SERVER='dbserver.example.com'
POSTGRES_USER=admin
POSTGRES_PASSWORD='p@$$w0rd'

docker-compose.yml

---
version: '3'
services:
  postgresql:
    image: postgres:12.16-bookworm
    container_name: postgresql
    restart: unless-stopped
    volumes:
      - /var/lib/postgresql/data:/var/lib/postgresql/data
    ports:
      - 5432:5432
    environment:
      SERVER: ${SERVER}
      POSTGRES_USER: ${POSTGRES_USER}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
3
  • Thank you, my friend, but I have some questions. Why use .env and not secrets? And what would be the correct permissions to protect the .env file?
    – user981
    Commented Jun 4 at 17:37
  • @user981 set .env to 600 Commented Jun 4 at 19:01
  • and, as far as using secrets vs .env, secrets appears to be designed to work with Swarm Commented Jun 4 at 19:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.