September 27, 2020 ☼ Docker
I recently had to spin up a PostgreSQL database for a project I’m currently working on. In this post I’ll show you how to quickly do the same.
Download docker here.
We’re going to use Docker compose
to set up everything. It’s totally fine to run Postgres with a single Docker command but in this case I’d like to add PgAdmin as an admin tool and God only knows how many other services we’re going to add further down the line ;) …right?
It’s easier to manage multiple services with Docker compose. With Compose, you use a YAML file to configure your application’s services (works in all environments).
docker-compose.yml
fileversion: "3.1"
services:
db:
image: "postgres:13"
container_name: "db_postgres"
environment:
POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER}"]
interval: 30s
timeout: 30s
retries: 5
ports:
- "5432:5432"
restart: always
volumes:
- db_dbdata:/var/lib/postgresql/data
pgadmin:
container_name: pgadmin_container
image: dpage/pgadmin4
environment:
PGADMIN_DEFAULT_EMAIL: ${PGADMIN_DEFAULT_EMAIL}
PGADMIN_DEFAULT_PASSWORD: ${PGADMIN_DEFAULT_PASSWORD}
volumes:
- pgadmin:/root/.pgadmin
ports:
- "8000:80"
restart: always
volumes:
db_dbdata:
pgadmin:
What happens in that file:
db_postgres
and pull the Postgres image from Docker Hub.db_dbdata
so even if the container and image are deleted, the volume will remain. You can delete it via docker volume rm db_dbdata
.HEALTHCHECK
ensure that the container it is working. (https://docs.docker.com/compose/environment-variables/)The strings inside ${ }
refer to ENV variables. The PostgreSQL image uses several environment variables which are easy to miss. While none of the variables are required, they may significantly aid you in using the image.
In this case I exported the ENV variables in my shell so Compose will pick them up automatically.
# CHANGE them as you see fit
export POSTGRES_USER=myUser
export POSTGRES_PASSWORD=root
export POSTGRES_DB=db
export PGADMIN_DEFAULT_EMAIL=pgadmin4@pgadmin.org
export PGADMIN_DEFAULT_PASSWORD=admin
You can also create a .env
file or take a look at the documentation for more ways of handling ENV vars.
docker-compose up -d
(detached)docker exec -it db_postgres psql -U myUser
psql (13.0 (Debian 13.0-1.pgdg100+1))
Type "help" for help.
myUser=#
0.0.0.0:8000
in the browserYou are all set!
docker-compose stop
-> (stop services)docker-compose down
-> (delete services)docker volume prune
-> (delete all docker volumes)docker logs -f db_postgres
-> (see logs)If you have any suggestions, questions, corrections or if you want to add anything please DM or tweet me: @zanonnicolas