Postgres local development with Docker

I’m writing a small, toy application and plan to have a SQL database backing it. It’s a good opertunity to learn a more about PostgreSQL, but I don’t necissarily want to run the psql server locally on my laptop. Having all of the dev dependencies aside from the server I’m working on running on Docker makes it easier to shut down Docker and make sure I don’t have a lingering db service running.

The docs don’t make it clear how to do this. It’s either all local or all on docker, using docker-compose to run your dev servers as well. However this introduced a lot of complexity in your dev setup and isn’t really necessary.

You can start PostgreSQL running locally with:

docker run \
  --name some-postgres \
  -p 5432:5432 \
  -e POSTGRES_PASSWORD=mysecretpassword \
  -d postgres

The trick here is passing through the port with -p 5432:5432. Then you can connect to the server with something like:

sql -h localhost -U postgres -p 5432

and then using the mysecretpassword password you set above. To access this server from you application you can use the connection string:

postgresql://postgres:mysecretpassword@localhost:5432

When you are done either shutting down docker or doing:

docker stop some-postgres

will stop the server, and

docker start some-postgres

will start it again. Even your data will still be there! Docker is way more powerful than this, but I hope this helps you dip your toes into using docker on a development machine.