Skip to the workspace
Pebellslearn by building
Using Third-Party Images  ›  Lesson

Running a Database in a Container

Databases 14 minA database container needs its settings as environment variables, a volume for its data directory, and a network path from the app, usually a shared user-defined network.

docker / Running a Database in a Container

Explore each scene at your own pace.

01 · The rule

The rule

Running a Database in a Container

Installing PostgreSQL directly on a laptop means services, users, config files and a cleanup you will never quite finish. With Docker, quicknotes gets a real PostgreSQL 16 in one command, and removing it later leaves nothing behind. Getting that one command right is what this lesson is about.

The rule

A database container needs three things: settings, a volume, a network.

docker network create notes-net

docker run -d --name notes-db \
  --network notes-net \
  -e POSTGRES_PASSWORD=devsecret \
  -e POSTGRES_DB=quicknotes \
  -v notes-data:/var/lib/postgresql/data \
  postgres:16
  • Settings come as environment variables with -e. The official postgres image refuses to start without POSTGRES_PASSWORD; POSTGRES_DB asks it to create a database on first start. These first-start variables are used only when the data folder is empty.
  • A volume keeps the data. -v notes-data:/var/lib/postgresql/data stores the database files in a named volume, so removing or upgrading the container does not remove the notes. (The data persistence section explains volumes fully.)
  • A network lets quicknotes reach it. On a user-defined network like notes-net, Docker runs a small DNS service, so containers find each other by name.

Then start quicknotes on the same network and point it at the database by its container name:

docker run -d --name notes --network notes-net \
  -e DATABASE_HOST=notes-db -p 8080:5000 quicknotes:1.0

Notice there is no -p on the database. Containers on the same network already reach each other on port 5432. Add -p 5432:5432 only if a tool on your own machine must connect.

For real deployments, avoid typing passwords on the command line; images like postgres also accept secrets from a file. For local development, the pattern above is fine.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.