'How do I secure postgres Username and password in Docker compose

My docker-compose file is

version: '3.7'
services:
  postgres:
    image: postgres:10.18-alpine3.14
    container_name: postgres
    hostname: postgres
    environment:
      POSTGRES_USER : admin
      POSTGRES_PASSWORD : Pass@4321
      PGDATA: /var/lib/postgresql/data/pgdata

Here user name and password is plain text. How can I secure my credentials in docker-compose.



Solution 1:[1]

Rather than hardcoding your username and password in your docker-compose.yaml, one option is to replace them with variables, like this:

version: '3.7'
services:
  postgres:
    image: postgres:10.18-alpine3.14
    container_name: postgres
    hostname: postgres
    environment:
      POSTGRES_USER : $POSTGRES_USER
      POSTGRES_PASSWORD : $POSTGRES_PASSWORD
      PGDATA: /var/lib/postgresql/data/pgdata

And then set them in your .env file:

POSTGRES_USER=admin
POSTGRES_PASSWORD=Pass@4321

When you docker-compose up your application, docker-compose will substitute the appropriate values.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 larsks