📅  最后修改于: 2023-12-03 14:40:48.780000             🧑  作者: Mango
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.
Here are the steps to mount a volume during Docker build:
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
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" ]
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.
Run the Docker container and check that the file is included:
docker run --rm -it myapp ls /app/data
This should output sample.txt
.
Using mount volume in Docker build has several advantages:
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.