How to generate random PostgreSQL password in .env for docker-compose

Generate the password using

echo "POSTGRES_PASSWORD=$(pwgen 30)" >> .env

In your docker-compose.yml, you can then use the environment variable like this:

services:
  postgres:
    image: postgres:latest
    environment:
      - POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
    volumes:
      - ./postgres_data:/var/lib/postgresql/data
    restart: unless-stopped
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 1s
      start_period: 3s
      timeout: 5s
      retries: 30