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
🌐
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".
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
Discussions

Containerised PostgreSQL and re-initializing databases

If 3&4 are designed to "reinit" the postgres from the bind mounted init data I think all you need to do is remove the service.

docker-compose stop
docker-compose rm postgres  # should remove the attached volumes
docker-compose up -d # should recreate the volume and run the initdb script

EDIT:

Personally I also feel like "just blowing it away" seems a little hasty, if there are any database writes you will lose them. Before you stop you could easily have made a backup.

docker-compose exec {servicename} pg_dumpall -c -U postgres > dump_`date +%d-%m-%Y"_"%H_%M_%S`.sql

And then go ahead and then stop/rm the service since you have a backup.

EDIT2:

You may need docker-compose rm -v postgres if you didn't explicitly declare the volumes. The flag tells it to also remove the anonymous volumes associated with the image.

More on reddit.com
🌐 r/docker
8
12
December 3, 2018
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
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
How to run a script PostgreSQL with Docker Compose in the initialization ?
The Docker way would be to simply spin up a second container with the dev database. services: prod: image: 11notes/postgres:16 restart: always environment: POSTGRES_PASSWORD: *********** volumes: - pg_prod:/postgres/var dev: image: 11notes/postgres:16 restart: always environment: POSTGRES_PASSWORD: *********** volumes: - pg_dev:/postgres/var volumes: pg_prod: pg_dev: More on reddit.com
🌐 r/docker
6
1
June 20, 2024
🌐
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
🌐
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 - db: image: postgres:latest volumes: - ./infrastructure/database/pgsql/create-testing-database.sql:/docker-entrypoint-initdb.d/10-create-testing-database.sql · The entry point only runs the scripts when the storage volume is empty
🌐
GitHub
gist.github.com › onjin › 2dd3cc52ef79069de1faa2dfd456c945
example docker compose for postgresql with db init script · GitHub
When I get a shell into my db container, the database rivers was created but is empty, with no tables, relations, or data from my batched inserts. I had the same issue but after a few hours of trying, I found a working combination of docker-compose and init script. Btw, I read here that the container shutting down and restarting is (apparently) part of the initialization process. This is part of my initdb.sh: #!/bin/bash psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" -d "$POSTGRES_DB" <<-EOSQL create schema if not exists $SCHEMA; create table $SCHEMA.todos ( id serial primary key, done boolean not null default false, task text not null, due timestamptz ); create role $ANON nologin; create role $AUTHENTICATOR noinherit login password '$POSTGRES_PASSWORD'; grant $ANON to $AUTHENTICATOR; EOSQL
🌐
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 - To create a PostgreSQL database in Docker, use the “CREATE DATABASE <database-name>;” command. Then, create a new table in it and insert values in the table.
Address   2950 Newmarket ST STE 101 - 231, 98226, Bellingham
Find elsewhere
🌐
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 guide will walk you through setting up a PostgreSQL database with a predefined dataset using Docker Compose. A more complicated example can be found here: ... Docker installed on your local machine or server. Docker Compose installed on your local machine or server. Download the predefined dataset in CSV format. Basic knowledge of Docker and SQL. ... Let’s call the directory postgres_csv_init. You can create ...
🌐
Medium
medium.com › @sandhyasrinivasan.1502 › starting-and-populating-postgres-db-in-docker-container-448f1af50777
Starting and Populating Postgres DB in docker container | Medium
March 24, 2023 - Now you have a Postgres container ... populate the DB on docker startup, we can do so by creating a simple SQL file and a Dockerfile and running the sql file on startup....
🌐
Bytearcher
bytearcher.com › articles › create-new-postgresql-database-instance-using-docker
Create new PostgreSQL database for local development using Docker
$ docker run --name app-postgres \ --env POSTGRES_USER=app_dev \ --env POSTGRES_PASSWORD=e1bc9e7f864d \ --publish 127.0.0.1:5432:5432 \ --detach \ --restart unless-stopped \ postgres:13 ... we publish the container's 5432 port to the host machine, but only to the localhost interface 127.0.0.1 and not the whole network · we let the container run in the background with --detach · normally Docker containers won't last over machine restarts, but we specifically ask for it with --restart unless-stopped · we also specifically bolt down database version with postgres:13 to avoid major version release changing from under us
🌐
Reddit
reddit.com › r/docker › containerised postgresql and re-initializing databases
r/docker on Reddit: Containerised PostgreSQL and re-initializing databases
December 3, 2018 -

I have an app that uses a small static database in PostgreSQL, using the postgres:10-alpine image and a volume mount for the data. This db needs to be refreshed every so often from an external source that the devs control.

At the moment, app and DB are managed with docker-compose. Devs can trigger a new deployment to prod (when tests pass), but they don't have access to prod themselves.

For deployment, we use a bash script that roughly does the following:

  1. stops and removes any existing instance of the postgres container using docker-compose stop && rm -f

  2. deletes the entire data directory with docker --rm -t ... rm -rf /var/lib/postgresql/data/

  3. initializes the db data again running a one-off docker run -d postgres -v init.sh:/docker-entrypoint-initdb.d/init.sh

  4. stops and kills the one-off instance after sleeping for a few seconds (docker stop && docker rm)

  5. brings up the docker-compose stack up again (docker-compose up -d)

Steps 2 and 3 are needed because the new db might come with different roles/privileges, and it's easier to just blow everything up and start again with a clean slate than trying to figure out a diff to apply.

This process works but I find it a bit convoluted, and potentially prone to failure (if the sleep in step 4 is not enough, or needs to become too long when the db grows).

I considered baking the db data into our own images FROM postgres, but I don't really feel like that would be ideal, particularly if the db becomes too big.

Can anyone think of a better solution?

🌐
Mkyong
mkyong.com › home › docker › how to run an init script for docker postgres
How to run an init script for Docker Postgres - Mkyong.com
September 22, 2023 - The official Docker postgres image will run all *.sh and *.sql scripts in its /docker-entrypoint-initdb.d directory automatically when it starts. ... 5.1 Creates an init.sql (can be any filename ending with the extension .sql) to create a table and insert three rows.
🌐
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 - Borrowing from our docs on controlling ... · To launch your Postgres database and supporting services, enter the docker compose -f [FILE NAME] up command....
🌐
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 - POSTGRES_PASSWORD sets the password to docker. This is the password that gives you access to your database · the —name property gives your container a name and means you can easily find it back · Now you can connect to this brand new Postgres database in any tool that allows you to communicate with databases. I tend to use RazorSQL or DBeaver. You need to use the following connection details to actually connect to the DB: ... Once connected you can do anything you want with the database (Create tables, load data etc).
🌐
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
🌐
Coding with Coffee
cadu.dev › creating-a-docker-image-with-database-preloaded
Creating a Docker image with a preloaded database | Coding with Coffee
January 29, 2021 - Initialization scripts If you would like to do additional initialization in an image derived from this one, add one or more *.sql, *.sql.gz, or *.sh scripts under /docker-entrypoint-initdb.d (creating the directory if necessary). After the entrypoint calls initdb to create the default postgres user and database, it will run any *.sql files, run any executable *.sh scripts, and source any non-executable *.sh scripts found in that directory to do further initialization before starting the service.
🌐
DEV Community
dev.to › bgord › multiple-postgres-databases-in-a-single-docker-container-417l
Multiple Postgres databases in a single Docker container - DEV Community
November 7, 2019 - However, if you want your container to include more than one database (e.g app and app_test), you have to reach for different solutions. One of them is to create a bash script that sets up multiple databases by psql command. Postgres will execute ...
🌐
Docker Community
forums.docker.com › general
Create docker container with postgres db and tables - General - Docker Community Forums
May 1, 2019 - 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 runni…
🌐
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...
🌐
Blog
blog.cadumagalhaes.dev › how-to-setup-a-postgresql-database-with-docker-compose
How to setup a PostgreSQL database with Docker Compose
February 5, 2025 - version: '3.8' services: postgres: image: postgres:15 environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=password volumes: - postgres-db-volume:/var/lib/postgresql/data ports: - 5432:5432 networks: - postgres-db-network pgadmin: image: dpage/pgadmin4 environment: PGADMIN_DEFAULT_EMAIL: 'teste@teste.com' PGADMIN_DEFAULT_PASSWORD: 'teste' ports: - 16543:80 volumes: - ./servers.json:/pgadmin4/servers.json networks: - postgres-db-network volumes: postgres-db-volume: driver: local driver_opts: type: none o: bind device: ./data networks: postgres-db-network: driver: bridge ... one for the database itself, which is based on the Postgres 15 image.