Having a containerized database is one of the most helpful and convenient things that help developers during the development process. In this blog post we will show step by step how to setup a containerized PostgreSQL database, keep the data persistent and delete the container.

Download PostgreSQL in a Docker container

docker pull postgres:latest

NOTE: You can substitute latest for the version of PostgreSQL that you want (e.g. 17.2).

Setup the container and database

In this step we will do the following:

  • Assign the docker container we downloaded a name.
  • Create a user and password for the PostgreSQL database.
  • Assign the ports both for the host and internally so that we can connect to the database from our machine.
  • Create a volume in order to keep the data persistent.
  • Detach and tell docker which application we are trying to run (i.e. postgres).
docker run --name psql-latest -e POSTGRES_USER=psql-user -e POSTGRES_PASSWORD=somedbpassword -p 5440:5432 -v ./data:/var/lib/postgresql/data -d postgres

Access the database from the command line

We now try to access the database from the command line as follows:

docker exec -it psql-17.2 psql -U psql_user
psql (17.2 (Debian 17.2-1.pgdg120+1))
Type "help" for help.

psql_user=# \dt
Did not find any relations.

As you can see above, once we are able to access PostgreSQL, we type \dt to list tables, but since it’s a newly setup database there are no tables.

Delete the container

In order to delete our container we type the following command using the container name:

docker rm psql-latest