To copy files from your host machine to a Docker container, you can use one of the following methods:
1. Using docker cp
(One-Time Copy)
The docker cp
command copies files/folders between the host and a running or stopped container.
Syntax:
docker cp <host-source-path> <container-name-or-id>:<container-destination-path>
Example:
# Copy a single file
docker cp /host/path/file.txt my-container:/container/path/
# Copy a directory
docker cp /host/path/folder my-container:/container/path/
Notes:
- The container does not need to be running.
- Changes are not persistent if the container is recreated (use volumes for persistence).
2. Build Files into the Image (Permanent)
Include the files in the container image during the build process using a Dockerfile
:
FROM base-image:tag
COPY /host/path/file.txt /container/path/file.txt # Use COPY or ADD
Build the image:
docker build -t my-image .
When to Use:
- Files are static and needed every time the container starts.
- Requires rebuilding the image for updates.
3. Mount a Volume/Bind Mount (Persistent/Real-Time Sync)
Mount a host directory into the container for real-time file sharing:
# Bind mount (-v syntax)
docker run -v /host/path:/container/path my-image
# Or using --mount (more explicit)
docker run --mount type=bind,source=/host/path,target=/container/path my-image
Advantages:
- Changes on the host are instantly visible in the container.
- No need to rebuild the image or restart the container.
Use Case:
- Development environments (e.g., syncing code).
4. Using docker exec
and Redirection (Advanced)
Redirect a file’s content into the container via stdin:
docker exec -i my-container sh -c 'cat > /container/path/file.txt' < /host/path/file.txt
Key Comparison
Method | Use Case | Persistence | Overhead |
---|---|---|---|
docker cp | Ad-hoc file transfer | ❌ | Low |
Image Build | Static files needed in every container | ✔️ | High |
Bind Mount/Volume | Real-time sync during development | ✔️ | Low |
Troubleshooting Tips
- Check Container Name/ID:
docker ps -a # List all containers
- Permissions: Ensure the container user has access to the copied files.
- Path Syntax: Use absolute paths, and for Windows hosts, adjust paths (e.g.,
C:\path
→/c/path
in Git Bash).
Example Workflow
- Copy a config file to a running container:
docker cp config.yaml my-container:/app/config.yaml
- Verify the file:
docker exec my-container ls /app
Choose the method based on your workflow needs!