What are Docker volumes and why do you need them?
- Technology:
- Docker
Quick answer
Volumes are storage managed by Docker that lives outside a container鈥檚 writable layer, so data such as database files survives when the container is removed or replaced.
Detailed explanation
A container鈥檚 writable layer is deleted with the container, and it is slower than native storage. Anything that must persist, such as a database, uploaded files or caches you want to keep, needs to live outside it.
There are three options. Named volumes are created and managed by Docker and are the default choice for persistent data. Bind mounts map a host directory into the container, which is handy in development for live-reloading source code. tmpfs mounts keep data in memory only.
Volumes are also how containers share data, and they can be backed by network storage in production. Back them up like any other data: removing the container does not remove a named volume, but docker volume rm or docker compose down -v does.
Example
docker volume create pgdata
docker run -d --name db \
-e POSTGRES_PASSWORD=secret \
-v pgdata:/var/lib/postgresql/data \
postgres:16
# the data survives replacing the container
docker rm -f db
docker run -d --name db -e POSTGRES_PASSWORD=secret \
-v pgdata:/var/lib/postgresql/data postgres:16Key points
- Container writable layers are temporary
- Named volumes for persistent data, bind mounts for development
- Volumes outlive containers until explicitly removed