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 officialpostgresimage refuses to start withoutPOSTGRES_PASSWORD;POSTGRES_DBasks 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/datastores 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.0Notice 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.
The shortcut
Before running any database image, fill in the three blanks: which settings does its page require, which path holds its data, and which network will its clients use?
Settings
The docs require
POSTGRES_PASSWORD. Add it, plusPOSTGRES_DB=quicknotes.
Drills
Answer fast — trust the rule.
Which environment variable must you set for the official postgres image to start?
quicknotes and notes-db share the network notes-net. What host name should quicknotes use?
Why mount a volume at /var/lib/postgresql/data?
When is -p 5432:5432 on the database container actually needed?
Remember
- A database container needs three things: settings (
-e), a volume for its data path, and a network. - Shortcut: fill in the three blanks from the image's docs before running it.
- Trap: using
localhostbetween containers, and forgetting the volume.
