Volumes and persistent data
Keep data alive when a container is replaced, and know when a bind mount is the better tool.
Open this lesson in the learning hubKey points
- Containers are disposable. Anything written to the container filesystem dies with
docker rm. - A named volume is Docker-managed storage that outlives containers. The right choice for databases.
- A bind mount maps a host directory in. Perfect for local dev, awkward in production where paths and uids differ.
--mountis explicit and fails loudly on a typo.-vis shorter but silently invents directories.- Add
,readonlyfor config you never want the container to rewrite.
Example
docker volume create pgdata
# named volume: the data survives replacing the container
docker run -d --name db \
--mount type=volume,src=pgdata,dst=/var/lib/postgresql/data \
-e POSTGRES_PASSWORD=secret \
postgres:16
# bind mount: a host directory, mounted read-only
docker run --rm \
--mount type=bind,src="$PWD/config",dst=/app/config,readonly \
myapp:1.0
docker volume ls
docker volume rm pgdata # this deletes the data. no undo.
If it has to survive a redeploy, it belongs in a volume.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Docker course, and every lesson in it is listed on the Docker contents page.