PostgreSQL with Docker

From NovaOrdis Knowledge Base
Jump to navigation Jump to search

Internal

Overview

In its simplest form:

docker run postgres

command starts a transient Posgres container instance that does not expose any port on the local host, it is initialized on the fly to allow access to any user and uses an anonymous local volume that will not be reattached to during the next run. To get a usable Postgres instance we can shut down and restart and that regains access to stored data between restarts, we should use create a dedicated named volume or a bind mount, initialize the database with a username and a password during the first initialization run and map ports to the local host.

Dedicated Storage

We prefer using a bind mount as it gives easy access to the stored state, in case we need to troubleshoot. A named volume can be also used.

docker run ...  --mount type=bind,source=/Users/ovidiu/runtime/docker-volumes/postgres,target=/var/lib/postgresql/data --name postgres ... postgres

Authenticated Access

When the container is run the first time, it goes through an initialization sequence, and if no specific authentication configuration is provided in form of environment variables, it will configure itself to allow unauthenticated access. To prevent that from happening, start the container for the first time as shown:

docker run --mount type=bind,source=/Users/ovidiu/runtime/docker-volumes/postgres,target=/var/lib/postgresql/data -e POSTGRES_USER=admin -e POSTGRES_PASSWORD=<some-password> --name postgres postgres

This will initialized the database to allow access as admin/<some-password>.

Subsequent startups will not require specification of -e POSTGRES_USER and -e POSTGRES_PASSWORD, as long as we use the same local directory Postgres initialized its state on.

Exposing Ports on the Local Host

Postgres binds by default on port 5432 and this is the port published by the following command:

docker run ... -p 5432:5432/tcp  ...

Procedures

Initialization

Create a local directory /Users/ovidiu/runtime/docker-volumes/postgres and then execute the initialization run:

docker run --mount type=bind,source=/Users/ovidiu/runtime/docker-volumes/postgres,target=/var/lib/postgresql/data -e POSTGRES_USER=admin -e POSTGRES_PASSWORD=<some-password> --name postgres postgres

The container can be removed after initialization with:

docker stop postgres
docker rm postgres

Routine Start

Log Into the Container

docker exec -it <container-id> bash