PostgreSQL Installation using Docker

Published: Monday, 6 July 2020
By:
  • Jurn Ho

This article covers Postgres specific steps in running postgreSQL in a docker container.

Choose your version

Pick an appropriate tag that matches the required version.

e.g. version 10

Pull the docker image

$ docker pull postgres:10
10: Pulling from library/postgres
047631b8ebb1: Pull complete
Digest: sha256:4753a0a58c1b2faf05251e61bac03087b9889187038a625b338973ed164b08c9
Status: Downloaded newer image for postgres:10
docker.io/library/postgres:10

Create a data volume

Data should be stored outside the container, so it can be managed separately and will survive an image upgrade.

Pick a name for the volume, e.g. postgres-data

$ docker volume create --name postgres-data
postgres-data

Alternatively, prepare a directory on the host where data will be stored.

Choose a database user and password

Choose a database user and password, it will have superuser privileges on the database.

e.g. my-app and my-app-password

Run the container

Choose a container name, e.g. example-postgres

$ docker run --name example-postgres \
-v postgres-data:/var/lib/postgresql/data \
-e POSTGRES_USER=my-app \
-e POSTGRES_PASSWORD=my-app-password \
postgres:10
  • /var/lib/postgresql/data is the default mount point for data storage
  • POSTGRES_USER and POSTGRES_PASSWORD are credentials for the database superuser.

The created database will have the same name as POSTGRES_USER. This can be changed via the POSTGRES_DB environment variable.

If everything is ok then successful log messages will appear:

PostgreSQL init process complete; ready for start up.

2020-07-06 11:07:44.031 UTC [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432
2020-07-06 11:07:44.031 UTC [1] LOG:  listening on IPv6 address "::", port 5432
2020-07-06 11:07:44.043 UTC [1] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
2020-07-06 11:07:44.073 UTC [64] LOG:  database system was shut down at 2020-07-06 11:07:43 UTC
2020-07-06 11:07:44.097 UTC [1] LOG:  database system is ready to accept connections

By default, TCP port 5432 is exposed.

Restart the container

Restart the container and check the logs

$ docker restart example-postgres
example-postgres
$ docker logs example-postgres
PostgreSQL Database directory appears to contain a database; Skipping initialization

It should skip initialization of the database as we have existing data.

References