TIL how to run postgresql in docker and persist the database

1 minute read Published:

Today I needed a postgres database for development that persisted its data when recreating the container. That’s not docker’s default behaviour, but docker volumes to the rescue!

This is the command to run a postgres container that persist it’s data in /var/yourpgdata:

docker run \
   --name pgresql \
   -d \
   -p 5432:5432 \
   -e POSTGRES_USER=yourpguser \
   -e POSTGRES_PASSWORD=yourpgpass \
   -e POSTGRES_DB=yourpgdb \
   -v /var/yourpgdata:/var/lib/postgresql/data

Fine… but what does this mean? Let me explain:

  • --name pgresql give the container a name (for linking to other containers, etc.)
  • -d daemonizes the container
  • -p 5432:5432 maps the host port 5432 (left) to the containers port 5432 (right)
  • -e POSTGRES_USER=yourpguser sets the postgres username
  • -e POSTGRES_PASSWORD=yourpgpass sets the postgres password
  • -e POSTGRES_DB=yourpgdb sets the postgres database name (if omitted this is the same as POSTGRES_USER)

Fine! That’s it!