Postgres in Docker

You could install Postgres on your machine with Homebrew or apt. It would work, but every dev on your team would have a slightly different setup, version drift would bite you, and onboarding a new contributor would take an afternoon. Docker fixes all of it. One command to start, one command to stop, identical on every machine.

What Docker is actually doing

Your Node app on the host talks to Postgres running inside a container. The named volume keeps the data on disk across restarts.

docker-compose.yml
yaml
services:
  postgres:
    image: postgres:16
    container_name: book-api-postgres
    ports:
      - "5432:5432"
    environment:
      POSTGRES_USER: book_api
      POSTGRES_PASSWORD: book_api
      POSTGRES_DB: book_api
    volumes:
      - postgres_data:/var/lib/postgresql/data

volumes:
  postgres_data:

A single Postgres service with a named volume so the data survives between container restarts.

docker compose up -d starts Postgres in the background. docker compose down stops it. Add -v to the down command and you also delete the volume, which wipes the data. The named volume is what gives you durability between restarts.

The way your code finds Postgres is a connection string. It looks like postgres://book_api:book_api@localhost:5432/book_api. Pieces: protocol, user, password, host, port, database name. Read it like a URL and it makes sense. Store it in an environment variable, never in source.

Quiz: Quiz

Loading practice…

Validation checklist: Spin up Postgres locally

Loading practice…