PostgreSQL Installation using Docker
This article covers Postgres specific steps in running PostgreSQL in a docker container.
Choose your version
Section titled “Choose your version”Pick an appropriate tag that matches the required version.
e.g. version 10
Pull the docker image
Section titled “Pull the docker image”$ docker pull postgres:1010: Pulling from library/postgres047631b8ebb1: Pull completeDigest: sha256:4753a0a58c1b2faf05251e61bac03087b9889187038a625b338973ed164b08c9Status: Downloaded newer image for postgres:10docker.io/library/postgres:10Create a data volume
Section titled “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-datapostgres-dataAlternatively, prepare a directory on the host where data will be stored.
Choose a database user and password
Section titled “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
Section titled “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/datais the default mount point for data storagePOSTGRES_USERandPOSTGRES_PASSWORDare 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 54322020-07-06 11:07:44.031 UTC [1] LOG: listening on IPv6 address "::", port 54322020-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 UTC2020-07-06 11:07:44.097 UTC [1] LOG: database system is ready to accept connectionsBy default, TCP port 5432 is exposed.
Restart the container
Section titled “Restart the container”Restart the container and check the logs
$ docker restart example-postgresexample-postgres$ docker logs example-postgresPostgreSQL Database directory appears to contain a database; Skipping initializationIt should skip initialization of the database as we have existing data.