How to copy files from host to Docker container?

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

MethodUse CasePersistenceOverhead
docker cpAd-hoc file transferLow
Image BuildStatic files needed in every container✔️High
Bind Mount/VolumeReal-time sync during development✔️Low

Troubleshooting Tips

  1. Check Container Name/ID:
   docker ps -a  # List all containers
  1. Permissions: Ensure the container user has access to the copied files.
  2. Path Syntax: Use absolute paths, and for Windows hosts, adjust paths (e.g., C:\path/c/path in Git Bash).

Example Workflow

  1. Copy a config file to a running container:
   docker cp config.yaml my-container:/app/config.yaml
  1. Verify the file:
   docker exec my-container ls /app

Choose the method based on your workflow needs!

Leave a Reply

Your email address will not be published. Required fields are marked *