PostgreSQL in a docker container

You presumably want to make a database for your little project. I presumably want to tell how. Read on.

Creating and running the container

docker run -p 5432:5432 -d \
-e POSTGRES_USER=postgres \
-e POSTGRES_DB=database-example \
-v pgdata:/var/lib/postgresql/data \

The explanation:

  • -p 5432:5432 — port 5432 (left) is the port on the host machine that will be used to access the container. It will map to port 5432 (right) in the container.
  • -d — discrete. The container will run but will not print its log in the terminal. It will run discretely.
  • -e — Environmental variables. These variables will be available within the container. We are declaring the user, password, and name of the database.
  • -v pgdata:/var/lib/postgresql/data — we are creating a named volume called pgdata and mounting it at that location inside the container
  • postgres — name of the image we will be using

Connecting to the container

docker exec -it <container-id> psql -U postgres database-example

The explanation:

  • exec — Execute this command inside the container
  • -it — Effectively makes it appear as a terminal session, so you can keep typing psql queries
  • <container-id> — find by executing the command docker container ls and copying the id
  • psql -U postgres database-example — a postgres command, as you may already be familiar with it, to enter the “database-example” database as the user “postgres”

What now?


Good day

Directly copied from a tutorial by the significantly more capable Ben Awad



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store