Why data disappears
A container is meant to be replaceable. If you remove it, anything written only inside that container can go with it.
That is fine for code. It is bad for a database, uploaded images, SQLite files, or generated reports you need after a restart.
The core idea
Use a volume when data must outlive a container. The image gives the app its starting files; the volume keeps changing data outside the container lifecycle.
What volumes hold
A volume can store database files, user uploads, cache files, or local development data. For your hackathon repo, it matters most for the database.
Without a volume, your reviewer may run the app, create test data, restart containers, and lose everything. That looks broken even if your app code is fine.
Compose volume shape
You will build the full app plus database Compose file in the next lesson. For now, read the volume part.
This example uses a named volume called pgdata and mounts it where the database stores its files.
services:
db:
image: postgres
volumes:
- pgdata:/var/lib/postgresql/data
volumes:
pgdata:Named versus host path
Compose volumes can mount named volumes or host paths into service containers. Named volumes are usually easier for a shared college project because Docker manages the storage location.
Host paths are useful when you want a local folder from your laptop visible inside the container, like live source code during development. They are easier to mess up across Windows, macOS, and Linux laptops.
Mounting over app files
A common beginner mistake is mounting a volume onto the same folder where your image copied the app code. The mount can hide the files already in the image.
Mount data folders only. For example, mount a database data directory or uploads directory, not the whole app folder unless you know why.
Prefer clear names
Name volumes after what they store, not after the tool. pgdata, mongo-data, uploads, and redis-data are easier to review than data1.
In current Compose files, reusable volumes should also be declared in the top-level volumes section. Older examples may skip this or include an old top-level version field; you do not need that version field in current Compose examples.
Do this now
Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.
0 of 5 done