Very Convenient to Do PostgreSQL Tests With Docker

Maciej
2 min readAug 5, 2022

--

Photo by Jan Antonin Kolar on Unsplash

Introduction

Sometimes It is necessary to acquire a DB dump, process it a little, and bring it to another DB server. It was very convenient to use the DB server with Docker when testing SQL, so below I will show how we can do this wit docker. Starting and destroying the DB server is fast and very convenient, there are official repositories for PostgreSQL and MySQL, so you don’t have to bother to create a Dockerfile. There are multiple versions depending on the tag, so it is easy to match the test environment, it is also possible to create an image of the DB server at any time using the docker commit command (after DDL definition, etc.). It seems very convenient to use Docker even for tests that involve DB

Let’s try

Assuming Docker is already installed, if not just install it.

[root@localhost vagrant]# docker pull postgres:latest
  • Place the file to omit the password for psql
[root@localhost vagrant]# echo "*:5432:*:*:P@ssw0rd_123" >> ~/.pgpass
  • DB server startup
[root@localhost vagrant]# docker run --name test-database -e POSTGRES_PASSWORD=mysecretpassword -d postgres:latest
  • Restore Database
[root@localhost vagrant]# psql -h $(docker inspect --format "{{ .NetworkSettings.IPAddress }}" test-database) -U postgres -f dump.sql
  • Connect to PostgreSQL and test Database
[root@localhost vagrant]# psql -h $(docker inspect --format "{{ .NetworkSettings.IPAddress }}" test-database) -U postgres
  • Stop and remove DB server
[root@localhost vagrant]# docker stop test-database
[root@localhost vagrant]# docker rm test-database
https://giphy.com/

--

--

Maciej

DevOps Consultant. I’m strongly focused on automation, security, and reliability.