updated: 22nd of December 2022
published: 21st of December 2022
This is a short post to show you how to run a PostgreSQL database with Docker to quickly connect to during development.
This allows you to utilize PostgreSQL without installing it on your host machine and also helps prevent having stale database tables laying around.
The following software versions were used in this post.
Start the container by running the below docker container run command. This will start the PostgreSQL container based on the postgres image on Docker Hub.
docker container run \
--detach \
--rm \
--name pgdev \
--env POSTGRES_USER=postgres \
--env POSTGRES_PASSWORD=postgres \
--env POSTGRES_DB=dev \
`# Optionally, mount a local volume into the container` \
`# --volume ${PWD}/tmp/pgdata:/var/lib/postgresql/data` \
--publish 5432:5432 \
postgres
The above command switches are explained as follows:
You can attach to the container using the docker container exec command.
docker container exec -it pgdev bash
Connect to PostgrSQL with the psql command. Use the -U postgres switch to connect as the postgres user.
psql -U postgres
To clean up the container, use the docker container kill command. This will stop the container, and because we started the container with the --rm switch, it will be automagically deleted.
docker container kill pgdev
I usually create a shell script that allows me to start and destroy the container without having to type so much or copy and paste.
Create a file named pgdev.sh with the following contents.
#! /usr/bin/sh
ACTION=$1
if [ $ACTION = "up" ]; then
docker container run \
--detach \
--rm \
--name pgdev \
--env POSTGRES_USER=postgres \
--env POSTGRES_PASSWORD=postgres \
--env POSTGRES_DB=dev \
--publish 5432:5432 \
postgres;
elif [ $ACTION = "rm" ]; then
docker container kill pgdev;
elif [ $ACTION = "con" ]; then
docker container exec -it pgdev bash -c "psql -U postgres";
else
echo "unknown action '$ACTION'";
fi
Then, make the file executable with the chmod +x pgdev.sh command.
Now you can start the container with the ./pgdev.sh up command, destroy the conatiner with the ./pgdev.sh rm command, and connect to the container with the ./pgdev.sh con command.
This post is mostly documentation for future Brad so that's it for now. Keep being awesome, and say hi to your mum for me ✌️
https://towardsdatascience.com/local-development-set-up-of-postgresql-with-docker-c022632f13ea