Docker ADD vs VOLUME

前端 未结 2 638
天命终不由人
天命终不由人 2021-01-29 18:31

I am learning Docker and I have doubts about when and where to use ADD and VOLUME. Here is what I think both of these do:

ADD

Copy fi

2条回答
  •  清酒与你
    2021-01-29 19:14

    The VOLUME instruction creates a data volume in your Docker container at runtime. The directory provided as an argument to VOLUME is a directory that bypasses the Union File System, and is primarily used for persistent and shared data.

    If you run docker inspect , you will see under the Mounts section there is a Source which represents the directory location on the host, and a Destination which represents the mounted directory location in the container. For example,

    "Mounts": [
      {
        "Name": "fac362...80535",
        "Source": "/var/lib/docker/volumes/fac362...80535/_data",
        "Destination": "/webapp",
        "Driver": "local",
        "Mode": "",
        "RW": true,
        "Propagation": ""
      }
    ]
    

    Here are 3 use cases for docker run -v:

    1. docker run -v /data: This is analogous to specifying the VOLUME instruction in your Dockerfile.
    2. docker run -v $host_path:$container_path: This allows you to mount $host_path from your host to $container_path in your container during runtime. In development, this is useful for sharing source code on your host with the container. In production, this can be used to mount things like the host's DNS information (found in /etc/resolv.conf) or secrets into the container. Conversely, you can also use this technique to write the container's logs into specific folders on the host. Both $host_path and $container_path must be absolute paths.
    3. docker run -v my_volume:$container_path: This creates a data volume in your container at $container_path and names it my_volume. It is essentially the same as creating and naming a volume using docker volume create my_volume. Naming a volume like this is useful for a container data volume and a shared-storage volume using a multi-host storage driver like Flocker.

    Notice that the approach of mounting a host folder as a data volume is not available in Dockerfile. To quote the docker documentation,

    Note: This is not available from a Dockerfile due to the portability and sharing purpose of it. As the host directory is, by its nature, host-dependent, a host directory specified in a Dockerfile probably wouldn't work on all hosts.

    Now if you want to copy your files to containers in non-development environments, you can use the ADD or COPY instructions in your Dockerfile. These are what I usually use for non-development deployment.

提交回复
热议问题