Skip to main content

How does Docker create a volume automatically?

Docker creates a volume automatically if the container run command specifies mounting a volume by a name that doesn't exist yet. In that case, Docker creates a new volume itself and mounts it.

Example

bash
docker run -v mydata:/app/data nginx

If the mydata volume didn't exist, Docker:

  1. creates the mydata volume
  2. puts it in /var/lib/docker/volumes/...
  3. mounts it into the container at the /app/data path

The same in Compose

yaml
services: app: image: nginx volumes: - mydata:/app/data volumes: mydata:

On docker compose up, a volume that doesn't exist will be created automatically.

Summary: Docker creates a volume "on the fly" as soon as it encounters a volume mount with a new name. No separate commands need to be run for this.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.