How to Create a Dev Container for PostgreSQL

PostgreSQL is a free and open-source relational database that I use for most of my private database projects. Today we explore the steps to put PostgreSQL into a dev container.

 

Get the PostgreSQL Docker image

You find the official Docker images for PostgreSQL on hub.docker.com. If you need a specific version, you can get everything from PostgreSQL 9.x up to the newest version (at the time of writing this post that is 14.1).

If you do not care about the specific version, you can use the postgres image for the newest one.

 

Create a folder for your database

As with the code we want to keep our database around when we restart the dev container. For that we need an empty folder in our repository, that we do not commit to Git.

If you have anything in this folder, PostgreSQL will not start and throw an error!

Do not forget to add this line to your .gitignore file:

 

Create a docker-compose.yml file

We can use this docker-compose.yml file to create a PostgreSQL container that puts its database files in our container_db folder:

 

Start the container

With the docker-compose file in place, we can start our database server with this command:

 

Create the database

Before we can use the database, we need to create it. Connect to the container and enter this command (replace DBNAME with the name you want to use):

If you want to restore your database, you can copy the *.dump file to your container_db folder. Then open the path that maps to container_db in the container and restore the database:

 

Access your database

We can now check if everything works by connecting our database management tool to our database in the container.

Host: localhost
Port: 5432
User: postgres
Password: password
Database: DBNAME (or how you named it)

 

Next

With our running database in place, we are ready to put our data-driven applications into a container. Next week we look what we need to do to develop a Rails application inside a dev container.

2 thoughts on “How to Create a Dev Container for PostgreSQL”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.