docker-library / postgres

Docker Official Image packaging for Postgres
http://www.postgresql.org
MIT License
2.14k stars 1.11k forks source link

Multiple users with docker-compose #1149

Closed eldarj closed 7 months ago

eldarj commented 8 months ago

Given a simple docker-compose

version: '3.8'

services:
  psql:
    image: postgres:16-alpine
    container_name: my-psql
    ports:
      - "5432:5432"
    environment:
      - POSTGRES_USER=something
      - POSTGRES_PASSWORD=something
      - POSTGRES_DB=sample

What is the suggest approach for creating multiple users? Ideally with the logic in docker-compose alone. Or if not possible, perhaps with a sh script, but without custom Dockerfiles.

ImreSamu commented 8 months ago

( as a user ) You can effectively use an initialization script by mapping it in your Docker Compose file.

Here are the steps to follow:

1.) Add an Initialization Script: ( /docker-entrypoint-initdb.d/init-database.sh ) For guidance on how to set up this script, please refer to the official Postgres documentation in the Docker Library. They provide helpful examples, such as how to add additional users and databases. You can find these examples here:

2.) Configure Docker Compose:: Below is an example that you need to add to your docker-compose file for setting this up:

    volumes:
      - ./init-database.sh:/docker-entrypoint-initdb.d/init-database.sh    

This example is based on a solution found on Stack Overflow ( https://stackoverflow.com/a/61729115/20859909 )