EDIT - since Jul 23, 2015

The official postgres docker image will run .sql scripts found in the /docker-entrypoint-initdb.d/ folder.

So all you need is to create the following sql script:

init.sql

CREATE USER docker;
CREATE DATABASE docker;
GRANT ALL PRIVILEGES ON DATABASE docker TO docker;

and add it in your Dockerfile:

Dockerfile

FROM library/postgres
COPY init.sql /docker-entrypoint-initdb.d/

But since July 8th, 2015, if all you need is to create a user and database, it is easier to just make use to the POSTGRES_USER, POSTGRES_PASSWORD and POSTGRES_DB environment variables:

docker run -e POSTGRES_USER=docker -e POSTGRES_PASSWORD=docker -e POSTGRES_DB=docker library/postgres

or with a Dockerfile:

FROM library/postgres
ENV POSTGRES_USER docker
ENV POSTGRES_PASSWORD docker
ENV POSTGRES_DB docker

for images older than Jul 23, 2015

From the documentation of the postgres Docker image, it is said that

[...] it will source any *.sh script found in that directory [/docker-entrypoint-initdb.d] to do further initialization before starting the service

What's important here is "before starting the service". This means your script make_db.sh will be executed before the postgres service would be started, hence the error message "could not connect to database postgres".

After that there is another useful piece of information:

If you need to execute SQL commands as part of your initialization, the use of Postgres single user mode is highly recommended.

Agreed this can be a bit mysterious at the first look. What it says is that your initialization script should start the postgres service in single mode before doing its actions. So you could change your make_db.ksh script as follows and it should get you closer to what you want:

NOTE, this has changed recently in the following commit. This will work with the latest change:

export PGUSER=postgres
psql <<- EOSQL
    CREATE USER docker;
    CREATE DATABASE docker;
    GRANT ALL PRIVILEGES ON DATABASE docker TO docker;
EOSQL

Previously, the use of --single mode was required:

gosu postgres postgres --single <<- EOSQL
    CREATE USER docker;
    CREATE DATABASE docker;
    GRANT ALL PRIVILEGES ON DATABASE docker TO docker;
EOSQL
Answer from Thomasleveil on Stack Overflow
Top answer
1 of 10
654

EDIT - since Jul 23, 2015

The official postgres docker image will run .sql scripts found in the /docker-entrypoint-initdb.d/ folder.

So all you need is to create the following sql script:

init.sql

CREATE USER docker;
CREATE DATABASE docker;
GRANT ALL PRIVILEGES ON DATABASE docker TO docker;

and add it in your Dockerfile:

Dockerfile

FROM library/postgres
COPY init.sql /docker-entrypoint-initdb.d/

But since July 8th, 2015, if all you need is to create a user and database, it is easier to just make use to the POSTGRES_USER, POSTGRES_PASSWORD and POSTGRES_DB environment variables:

docker run -e POSTGRES_USER=docker -e POSTGRES_PASSWORD=docker -e POSTGRES_DB=docker library/postgres

or with a Dockerfile:

FROM library/postgres
ENV POSTGRES_USER docker
ENV POSTGRES_PASSWORD docker
ENV POSTGRES_DB docker

for images older than Jul 23, 2015

From the documentation of the postgres Docker image, it is said that

[...] it will source any *.sh script found in that directory [/docker-entrypoint-initdb.d] to do further initialization before starting the service

What's important here is "before starting the service". This means your script make_db.sh will be executed before the postgres service would be started, hence the error message "could not connect to database postgres".

After that there is another useful piece of information:

If you need to execute SQL commands as part of your initialization, the use of Postgres single user mode is highly recommended.

Agreed this can be a bit mysterious at the first look. What it says is that your initialization script should start the postgres service in single mode before doing its actions. So you could change your make_db.ksh script as follows and it should get you closer to what you want:

NOTE, this has changed recently in the following commit. This will work with the latest change:

export PGUSER=postgres
psql <<- EOSQL
    CREATE USER docker;
    CREATE DATABASE docker;
    GRANT ALL PRIVILEGES ON DATABASE docker TO docker;
EOSQL

Previously, the use of --single mode was required:

gosu postgres postgres --single <<- EOSQL
    CREATE USER docker;
    CREATE DATABASE docker;
    GRANT ALL PRIVILEGES ON DATABASE docker TO docker;
EOSQL
2 of 10
63

By using docker-compose:

Assuming that you have following directory layout:

$MYAPP_ROOT/docker-compose.yml
           /Docker/init.sql
           /Docker/db.Dockerfile

File: docker-compose.yml

version: "3.3"
services:
  db:
    build:
      context: ./Docker
      dockerfile: db.Dockerfile
    volumes:
      - ./var/pgdata:/var/lib/postgresql/data
    ports:
      - "5432:5432"

File: Docker/init.sql

CREATE USER myUser;

CREATE DATABASE myApp_dev;
GRANT ALL PRIVILEGES ON DATABASE myApp_dev TO myUser;

CREATE DATABASE myApp_test;
GRANT ALL PRIVILEGES ON DATABASE myApp_test TO myUser;

File: Docker/db.Dockerfile

FROM postgres:11.5-alpine
COPY init.sql /docker-entrypoint-initdb.d/

Composing and starting services:

docker-compose -f docker-compose.yml up --no-start
docker-compose -f docker-compose.yml start
🌐
Docker
docs.docker.com › guides › pre-seeding database with schema and data at startup for development environment
Pre-seeding database with schema and data at startup for development environment | Docker Docs
3 weeks ago - $ cat seed.sql | docker exec -i postgres psql -h localhost -U postgres -f- Once the query is executed, you will see the following results: CREATE DATABASE You are now connected to database "sampledb" as user "postgres".
Discussions

postgresql - Create a postgres database within a docker-compose.yml file - Stack Overflow
I want to create a postgres database named bank within a docker-compose.yml file just after the postgres container has started but when i run docker-compose --env-file .env -f docker-compose.yaml u... More on stackoverflow.com
🌐 stackoverflow.com
Create docker container with postgres db and tables
Hi, I am trying to create a Postgres Docker container. I want to connect to this container from Python. I need to create a database and some tables while Docker is being created. I attached my docker files. I am running the command below: docker build -t postgres . More on forums.docker.com
🌐 forums.docker.com
8
0
May 1, 2019
Docker Makes Setting Up PostgreSQL Super Easy!
Your page doesn't load for me but I just use a basic docker compose file like below for my container. This uses best practices, enables persistent volume, uses SSL, logging & enables pg_stat_statements. --- services: postgres: image: postgres:17.4 container_name: postgres hostname: postgres environment: POSTGRES_USER_FILE: /run/secrets/pg_user POSTGRES_DB: postgres POSTGRES_PASSWORD_FILE: /run/secrets/pg_pw TZ: America/Chicago PGTZ: America/Chicago secrets: - pg_user - pg_pw volumes: - ./data:/var/lib/postgresql/data - ./logs:/var/log/postgresql - ./certs:/var/lib/postgresql/certs command: > postgres -c ssl=on -c ssl_cert_file=/var/lib/postgresql/certs/server.crt -c ssl_key_file=/var/lib/postgresql/certs/server.key -c logging_collector=on -c log_directory=/var/log/postgresql -c log_filename=postgresql.log -c log_statement=all -c log_connections=on -c log_disconnections=on -c log_destination=stderr,csvlog -c log_rotation_age=1d -c shared_preload_libraries=pg_stat_statements -c pg_stat_statements.track=all restart: unless-stopped network_mode: "host" secrets: pg_user: file: ./secrets/pg_user.txt pg_pw: file: ./secrets/pg_pw.txt ... More on reddit.com
🌐 r/docker
18
50
March 26, 2025
Creating a NEW DB in a running PostgreSQL container
Hello Sameer, I'm using the docker-postgresql with Wordpress and it work very well so far :) At the moment, I'm running Gitlab 7 on bare-metal and I found your docker-gitlab project. Great ... More on github.com
🌐 github.com
12
March 23, 2016
🌐
Docker
docker.com › blog › how to use the postgres docker official image | docker
How to Use the Postgres Docker Official Image | Docker
November 6, 2024 - Enter the following docker run command to start a new Postgres instance or container: docker run --name some-postgres -e POSTGRES_PASSWORD=mysecretpassword -d postgres · This creates a container named some-postgres and assigns important environment ...
🌐
CommandPrompt Inc.
commandprompt.com › education › how-to-create-a-postgresql-database-in-docker
How to Create a PostgreSQL Database in Docker — CommandPrompt Inc.
June 12, 2024 - Then, create and start the Postgres ... connection with the desired database. Next, create a Database utilizing the “CREATE DATABASE <database-name>;” command....
Address   2950 Newmarket ST STE 101 - 231, 98226, Bellingham
🌐
Docker
hub.docker.com › _ › postgres
postgres - Official Image | Docker Hub
For example, to add an additional user and database, add the following to /docker-entrypoint-initdb.d/init-user-db.sh: #!/usr/bin/env bash set -e psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL CREATE USER docker; CREATE DATABASE docker; GRANT ALL PRIVILEGES ON DATABASE docker TO docker; EOSQL Copy
🌐
DataCamp
datacamp.com › tutorial › postgresql-docker
PostgreSQL in Docker: A Step-by-Step Guide for Beginners | DataCamp
April 14, 2025 - POSTGRES_DB: Creates a new database with this name (defaults to the username if not specified). Port mapping (-p 5432:5432) maps the container's PostgreSQL port (5432) to the same port on your host machine, allowing you to connect to PostgreSQL using localhost:5432. Volume mounting (-v postgres-data:/var/lib/postgresql/data) creates a Docker volume named postgres-data that persists the database files outside the container.
🌐
DEV Community
dev.to › andre347 › how-to-easily-create-a-postgres-database-in-docker-4moj
How to easily create a Postgres database in Docker - DEV Community
January 28, 2021 - Next step is to create our image by typing this command in the terminal: ... The above line tells Docker to build an image from the Dockerfile and give it a name of 'my-postgres-db'. In order to see your images you can run ... Great, now we got our own image called 'my-postgres-db'. We can run it as a container by doing the following: docker run -d --name my-postgresdb-container -p 5432:5432 my-postgres-db · You can now connect to this database by using the login details specified in the Dockerfile.
Find elsewhere
🌐
Docker Community
forums.docker.com › general
Create docker container with postgres db and tables - General - Docker Community Forums
May 1, 2019 - I want to connect to this container from Python. I need to create a database and some tables while Docker is being created. I attached my docker files. I am running the command below: docker build -t postgres .
🌐
Charles Desneuf
blog.charlesdesneuf.com › articles › creating-databases-when-starting-the-postgres-docker-ontainer
Creating databases when starting the Postgres Docker container | Charles Desneuf
November 21, 2023 - SELECT 'CREATE DATABASE testing' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'testing')\gexec · And here is an example of what to change in à docker-compose.yaml file: db: image: postgres:latest volumes: - ./infrastructure/database/pgsql/create-testing-database.sql:/docker-entrypoint-initdb.d/10-create-testing-database.sql
🌐
Medium
wkrzywiec.medium.com › database-in-a-docker-container-how-to-start-and-whats-it-about-5e3ceea77e50
Database in a Docker container — how to start and what’s it about | by Wojciech Krzywiec | Medium
September 21, 2021 - As a result we’ve enter the command line of the Docker container, so we can login to the database as a postgres user. root@377ef2b9b13e:/# psql -U postgrespsql (11.4 (Debian 11.4-1.pgdg90+1)) Type "help" for help.postgres=# Here you can do whatever you want, create new databases, new tables populate them with data and so on.
🌐
DEV Community
dev.to › codewithluke › create-and-seed-your-postgres-database-in-minutes-with-docker-1i11
Create and Seed Your Postgres Database in Minutes with Docker - DEV Community
December 14, 2022 - So to start we want to create our bare bone Postgres container: docker run --name my-db -e POSTGRES_PASSWORD=pwd -e POSTGRES_DB=database -d -p 5432:5432 postgres
🌐
Medium
medium.com › @codewithluke › create-and-seed-your-postgres-database-in-minutes-with-docker-32c303702b1a
Create and Seed Your Postgres Database in Minutes with Docker | by Luke Babich | Medium
December 14, 2022 - This will create 2 tables called *rooms* and *users*. You can create your structure however you want but this is just to show as an example. ... You can use the CLI to run a migration script while connecting to the DB directly. However in this example I am going to show you the code version. ... package main import ( "database/sql" "fmt" "github.com/golang-migrate/migrate/v4" "github.com/golang-migrate/migrate/v4/database/postgres" _ "github.com/golang-migrate/migrate/v4/source/file" "github.com/joho/godotenv" _ "github.com/lib/pq" "log" "os") func main() { db, err := sql.Open("postgres", "pos
🌐
Medium
medium.com › @asuarezaceves › initializing-a-postgresql-database-with-a-dataset-using-docker-compose-a-step-by-step-guide-3feebd5b1545
Initializing a PostgreSQL Database with a Dataset using Docker Compose: A Step-by-step Guide | by Asuarezaceves | Medium
June 25, 2023 - This approach provides a reproducible and portable way of setting up databases, ideal for development, testing, and continuous integration environments. In your docker-compose.yml file, add this extra bit: version: '3.8' services: postgres: image: postgres:latest env_file: - .env volumes: - ./data:/var/lib/postgresql/data networks: - initexample metabase: image: metabase/metabase:latest depends_on: - postgres ports: - 3000:3000 networks: - initexample networks: initexample: driver: bridge
🌐
Towards Data Science
towardsdatascience.com › home › latest › getting started with postgres in docker
Getting started with Postgres in Docker | Towards Data Science
March 5, 2025 - We can "inject" all variables from this file into the Docker container upon running it (more information in this article). Let’s first create our environment file that’ll contain our database credentials. We’ll call the file dbcredentials.env and add the following content: POSTGRES_HOST=my_db POSTGRES_USER=mike POSTGRES_PASSWORD=supersecretpassword POSTGRES_DB=my_project_db
🌐
DB Vis
dbvis.com › thetable › how-to-set-up-postgres-using-docker
How to Set Up Postgres using Docker
March 27, 2025 - In this blog post, we will walk you through setting up PostgreSQL using Docker. By the end of this tutorial, you will have a PostgreSQL database running in a Docker container, ready for application development.
🌐
GitConnected
levelup.gitconnected.com › creating-and-filling-a-postgres-db-with-docker-compose-e1607f6f882f
Creating and filling a Postgres DB with Docker compose | by José David Arévalo | Level Up Coding
April 14, 2022 - In this case, we mapped our local port 5438 to the port 5432 (Postgres default port) inside the container., also we will persist the data in our machine, preventing data loss when deleting the containers, for this, we add the volume using the folder postgres-data as the place where Postgres data are stored. To create the tables in our database we need to copy our create_tables.sql script to/docker-entrypoint-initdb.d/
🌐
Reddit
reddit.com › r/docker › docker makes setting up postgresql super easy!
r/docker on Reddit: Docker Makes Setting Up PostgreSQL Super Easy!
March 26, 2025 -

I wrote up a blog post detailing how to set up a PostgreSQL database easy with Docker, as well as some small things to watch out for to make it easier to figure out why you can't connect to your database that we all forget sometimes :)

https://smustafa.blog/2025/03/26/docker-made-setting-up-postgresql-super-easy/

🌐
Baeldung
baeldung.com › home › docker › postgresql with docker setup
PostgreSQL with Docker Setup | Baeldung on Ops
July 23, 2025 - First, we’ll run a Docker container with a PostgreSQL database using the PostgreSQL Public Image. Then, we’ll create a customized Dockerfile to install the PostgreSQL server in the Docker container.
🌐
GitHub
github.com › sameersbn › docker-postgresql › issues › 58
Creating a NEW DB in a running PostgreSQL container · Issue #58 · sameersbn/docker-postgresql
March 23, 2016 - docker run --name=redmine -d \ --link=postgresql-redmine:postgresql --publish=10083:80 \ --env='REDMINE_PORT=10083' \ --volume=/srv/docker/redmine/redmine:/home/redmine/data \ sameersbn/redmine:3.2.1-2
Author   sameersbn