Understanding Docker Volumes: Dockerfile [VOLUME], docker-compose Volumes:, and shared data with Named Volumes

The DockerFile instruction VOLUME [ "/data" ] creates an anonymous volume mounted as /data that allows just 1 container to use it (unless you issue a docker run --volumes-from or bind mount it with docker run -v /var/lib/docker/volumes/9283:/data) until you docker rm that container. After docker rm, the volume remains but it's inaccessible by containers without a bind mount.

Demonstration:
1. mkdir test && cd test && vim Dockerfile (where you enter VOLUME [ "/data" ])
2. docker run -it --name test1 test /bin/bash
3. docker volume ls confirms a new directory in /var/lib/docker/volumes/<volume-name>
4. docker run -it --name test2 test /bin/bash
5. docker volume ls confirms a new directory in /var/lib/docker/volumes/<volume-name>
6. data is NOT shared between test1 and test2 (they will have different /data contents)
7. After docker rm test1, its volume remains but can't be accessed in a container without a bind mount
8. To bind mount it, do this: docker run -it -v /var/lib/docker/volumes/1234:/data ubuntu /bin/bash
9. To <i>share</i> data between test1 and test2, use a <i>named volume</i> (you give it a name) instead of an anonymous (Docker gives it a hex number) volume
a. docker run -v data:/data -it myimage bash  -- confirm creation with docker volume ls
OR
b. docker volume create data -- confirm creation with docker volume ls
10. In Dockerfile and docker-compose you can NOT use host-based volumes because that breaks portability
11. To use a named volume in docker-compose, do this:
version: '2.1'
  services:
    db:
      image: dev
    volumes:
      - data:/data
volumes:
  data:
    external: true

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.