Run Postgresql inside Docker container for local development

Run Postgresql inside container with persistent data in docker volume. Useful for local development.

docker run --name my_postgres -e POSTGRES_PASSWORD=mysecretpassword -p 5433:5432 -d -v pgdata:/var/lib/postgresql/data postgres:14.5
  • –name Name you container
  • -e POSTGRES_PASSWORD=mysecretpassword Option for postgres user password
  • -p 5433:5432 Option to expose port, 5433 will be exposed to the local machine
  • -d Option for detached mode, running in background
  • -v pgdata:/var/lib/postgresql/data Option to create pgdata volume and connect it inside container folder /var/lib/postgresql/data
  • postgres:14.5 Postgres image and version. Find more here.

If you do not believe me that the data will be saved even when container is deleted, try this:

##Connect to database
psql -h localhost -p 5433 -U postgres -d postgres

##Create a database
CREATE DATABASE dvdrental;

### import testing database. Download and extract this one for example: http://blog.twis7.com/dvdrental.zip
pg_restore -h localhost -p 5433 -U postgres -d dvdrental /path/to/downloaded/dabase/dvdrental.tar

## connect to database
\c dvdrental

## display all tables
\dt

## stop and remove the container
docker stop my_postgres
docker rm my_postgres

## start the container again
docker run --name my_postgres -e POSTGRES_PASSWORD=mysecretpassword -p 5433:5432 -d -v pgdata:/var/lib/postgresql/data postgres:14.5

##Check the database again. Everything will be inside as expected.