📜  docker build mount volume (1)

📅  最后修改于: 2023-12-03 14:40:48.780000             🧑  作者: Mango

Docker Build Mount Volume

When building Docker images, we often need to include files from outside the build context. To achieve this, we can use a technique called mount volume. In this way, we can mount a directory or file from the host machine into the Docker container during the build process.

How to use mount volume in Docker build

Here are the steps to mount a volume during Docker build:

  1. Create a directory on the host machine that contains the files you want to include in the Docker image. For example, let's create a directory called data with a file inside called sample.txt:

    mkdir data
    echo "Hello, World!" > data/sample.txt
    
  2. In your Dockerfile, add the VOLUME command to create a mount point:

    FROM python:3.9-slim-buster
    VOLUME /app/data
    WORKDIR /app
    COPY requirements.txt .
    RUN pip install -r requirements.txt
    COPY . .
    CMD [ "python", "./app.py" ]
    
  3. Build the Docker image and mount the directory using the --mount flag:

    docker build --tag myapp --mount type=bind,source="$(pwd)"/data,target=/app/data .
    

    Here, we specify the volume type as bind, which indicates that we want to mount a directory from the host machine. The source parameter specifies the path to the directory on the host machine, and the target parameter specifies the path to the mount point inside the container.

  4. Run the Docker container and check that the file is included:

    docker run --rm -it myapp ls /app/data
    

    This should output sample.txt.

Advantages of mount volume in Docker build

Using mount volume in Docker build has several advantages:

  • It allows us to include files from outside the build context without copying them inside the image, which can save time and disk space.
  • We can easily update the files outside the container and rebuild the image without needing to change the contents of the Dockerfile.
  • It enables us to separate the concerns of the build and runtime environments, as we can include files during build that are not needed during runtime.
Conclusion

Mount volume is a useful technique that can improve the efficiency and flexibility of Docker builds. By mounting directories or files from the host machine, we can easily include external resources in our images without increasing their size or complexity.