You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何将Docker外部的目录复制到Docker内部的容器中

Copying a Host Directory into a Docker Container

Hey there! Let me break down the most common and reliable ways to copy a directory from your local machine (outside Docker) into a Docker container. Whether you're working with a running container or setting things up during image build, there's a method for every scenario.

1. One-off Copy to a Running Container (Using docker cp)

This is the go-to method when you need to copy files/directories to a container that's already up and running. The syntax is straightforward:

docker cp /path/to/host/directory <container-name-or-id>:/path/inside/container

Example:

Suppose you have a directory /home/yourname/my-docs on your host, and you want to copy it into a container named my-notes-app at the path /app/docs. Here's the command:

docker cp /home/yourname/my-docs my-notes-app:/app/docs
  • Pro Tip: If the target path inside the container doesn't exist, Docker will automatically create it for you.
  • How to find your container name/ID? Run docker ps to list all running containers—you'll see the name under the NAMES column and the ID under CONTAINER ID.

2. Bind Mounts (Real-Time Sync, Not Just a One-Time Copy)

If you need the host directory to stay in sync with the container (any changes on the host reflect immediately in the container, and vice versa), use a bind mount when starting the container. This is different from a one-time copy, but it's super useful for development workflows.

Syntax:

docker run -v /path/to/host/directory:/path/inside/container your-image-name

Example:

Start a Node.js container and sync your local dev-project directory to /app inside the container:

docker run -d -v /home/yourname/dev-project:/app node:18

Note: This isn't a "copy" in the traditional sense—it's a direct link. If you only need to move files once, stick with docker cp.

3. Copy During Image Build (Using COPY in Dockerfile)

If you want the directory to be part of your Docker image (so every container started from this image has the directory by default), add a COPY instruction to your Dockerfile.

Example Dockerfile:

# Use a base image
FROM nginx:alpine

# Copy the host's ./static-files directory to /usr/share/nginx/html inside the image
COPY ./static-files /usr/share/nginx/html

Then build the image:

docker build -t my-custom-nginx .

Any container started from my-custom-nginx will have the static-files directory already in place.

Common Gotcha: Permissions

Sometimes after copying, the container's user might not have access to the directory. Fix this by running a command inside the container to adjust permissions:

docker exec -it <container-name> chown -R nginx:nginx /app/docs

(Replace nginx:nginx with the appropriate user/group for your container.)


内容的提问来源于stack exchange,提问作者Karthik Gujjar

火山引擎 最新活动