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.
1 |
mkdir container_db |
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:
1 |
/container_db/ |
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:
1 2 3 4 5 6 7 8 9 10 |
version: "3.2" services: db: image: postgres volumes: - ./container_db:/var/lib/postgresql/data environment: POSTGRES_PASSWORD: password ports: - 5432:5432 |
Start the container
With the docker-compose file in place, we can start our database server with this command:
1 |
docker-compose up |
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):
1 |
createdb -T template0 DBNAME |
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:
1 2 |
cd /var/lib/postgresql/data psql -U postgres DBNAME < DBNAME.dump |
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”