docker volume

Containers are thrown away, data shouldn't be: create a volume, mount it with -v, and see it survive docker rm.

>_ Try it: a simulated Linux, right here
Loading the terminal…

Examples

  • docker volume create db-data
  • docker run -d --name db -e POSTGRES_PASSWORD=secret -v db-data:/var/lib/postgresql/data postgres
  • docker volume ls
  • docker volume inspect db-data
  • docker rm -f db
  • docker volume ls

How it works

Files written inside a container disappear with it. A volume is storage Docker keeps outside the container: mount it with -v NAME:/path and whatever is written there stays.

That is how databases run in Docker: delete and recreate the container (a new version, new settings) and mount the same volume — the data is still there.

Syntax

docker volume create|ls|inspect|rm [NAME]  ·  docker run -v NAME:PATH IMAGE

Options

OptionWhat it does
create NAMEcreate a named volume
-v NAME:PATHmount it into a container at PATH
lslist volumes
inspect NAMEdetails, like where it lives on the host
rm NAMEdelete it (only when no container uses it)

Good to know

  • docker run -v db-data:/path creates the volume by itself if it doesn't exist yet.
  • With a folder path instead of a name (-v ./site:/usr/share/nginx/html) you mount a folder of your own machine — a bind mount.