luqo33
luqo33

Reputation: 8361

Mounting local directory into Docker container path that is not exposed as a VOLUME

Is there any difference between:

  1. Mounting a host directory into a container path (the path is not exposed as a volume), e.g.:

docker run -v /host/directory:/container/directory my_image command_to_run

Dockerfile of my_image does not include VOLUME ["/container/directory"]

  1. Mounting a host directory into a a container path exposed as a volume:

docker run -v /host/directory:/container/directory my_image command_to_run

Dockerfile of my_image includes VOLUME ["/container/directory"]

I know that volume data persists independent of the container life-cycle. However, since I want to work on my local data from within a container, does that make any difference if the mount-point inside the container is a volume?

Upvotes: 0

Views: 1461

Answers (1)

BMitch
BMitch

Reputation: 263746

There is no difference if you mount the path from the host into the container. The filesystem from the host will be mounted over top of that directory inside the container.

The difference between listing the volume and not listing it inside the image is the behavior of docker when you create an image without specifying a volume. When the volume is defined on the image, docker will create an "anonymous" volume you can see with docker volume ls as a long uuid string. These volumes are rarely useful, so I recommend against defining a volume in the image and instead only defining them on your docker run command or docker-compose.yml definition.

Downsides of defining a volume in the image include:

  1. Later lines in the Dockerfile or in descendant Dockerfile's may not be able to change the contents at this location. Docker's behavior with this varies by scenario and version, so for predictability, once a volume is defined in an image, I consider that directory off limits.

  2. Creation of anonymous volumes are difficult to use and are likely to clutter up the filesystem.

I posted a blog on this topic a while back if you're interested in more details.

Upvotes: 1

Related Questions