0

According, to the docker documentation a volume can be created like this?

docker volume create myvol

is there a way to specify the source directory?

Luke101
  • 56,845
  • 75
  • 204
  • 330

1 Answers1

2

There are two kinds of Docker volumes: bind mount and named. A bind mount is done at runtime, and it's the one you're thinking about when you're talking about a source directory. It looks like this:

docker run -v /mydir:/app someimage

This would mount the /mydir directory on your host machine to /app in the running container.

A named volume doesn't have a source directory, it exists in the container space only. It's typically used to preserve data between container runs, because containers are ephemeral.

A common use case would be preserving the packages from an npm install, pip install or some other package manager for development. I may not want to re-download 100 packages every time I run my container. Instead, I could use a volume to persist them between runs:

docker run -v myvol:/app/node_modules someimage

The next time I start this container and mount myvol like this, myvol already has all of the installed packages from last time in /app/node_modules, so npm will simply scan over them quickly for updates and move along.

Also consider a named volume in the role of running a Dockerized database. Check this SO post, it has a very good answer: How to deal with persistent storage (e.g. databases) in Docker

Edit: bind mounts must start with a backslash for the host_src, otherwise docker run creates a named volume.

bluescores
  • 3,649
  • 1
  • 12
  • 28
  • Would '-v' work in docker swarm? I've tried but does not work – Luke101 Nov 20 '17 at 21:50
  • That I don't know, I haven't used Docker Swarm. Kubernetes and AWS ECS both support volumes, I have to think Swarm does as well. – bluescores Nov 20 '17 at 22:18
  • @bluescores Do you know how indicate the name of the volume when running `docker run -v mydir:/app someimage` because otherwise it creates a random number – Arturo Mar 30 '20 at 03:59
  • @Arturo is helping me see I made a mistake. Bind mounts must start with a backslash, otherwise `docker run` will create a named volume with whatever name is given. I will edit my response. Thanks! – bluescores Apr 12 '20 at 19:55