How to run instance of postgres db locally via docker

Updated on: Sun Feb 05 2023

There are lots of situations when you want to just try something quickly on fresh project and you need to quickly run postgres database locally. I find it useful to utilise docker and especially manage it via short and concise docker-compose configuration because we never sure if we'll come back to this test project or not.

So, here what I usually do. Create docker-compose.local.yml in your project directory or outside of it, doesn't matter. Add following content there:

copied yaml

services:
  db:
    image: postgres:12.3-alpine
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_DB=dbname_dev_db
      - POSTGRES_PASSWORD=123321
    volumes:
      - dbname_dev_db-volume:/var/lib/postgresql/data
    ports:
      - 8086:5432

volumes:
  dbname_dev_db-volume:

Here we just declare that we'll use postgres:12.3-alpine - which is small and good enough for almost everything we need. We also specify the volume dbname_dev_db-volume to not accidentally loose the data if at some point we stop container. Probably we'll need to change the port and db name as well there

We now can use following commands to spin instance up:

copied bash

docker-compose -f docker-compose.local.yml up -d

To shut it down use following command:

copied bash

docker-compose -f docker-compose.local.yml down