-
Step 1 — Create a file on the host
Description: Prepare a file on the host machine that you want to copy into the container.
Command:
echo "This is a file inside container" > myfile.txt
-
Step 2 — Run a background Ubuntu container
Description: Start an Ubuntu container in detached mode so it can run in the background while you copy files into it. Name the container testcopyfile.
Command:
docker run -dit --name testcopyfile ubuntu
Explanation:
-d → run container in background
-i -t → allocate an interactive terminal
--name testcopyfile → assign a name to the container
Verify it’s running:
docker ps
-
Step 3 — Copy file from host to container
Description: Transfer the myfile.txt from your host machine into the container’s /root directory.
Command:
docker cp myfile.txt testcopyfile:/root/
-
Step 4 — Open the container’s terminal
Description: Access the container to check if the file exists.
Command:
docker exec -it testcopyfile bash
-
Step 5 — Verify the file inside the container
Description: List the contents of /root to confirm the file is copied, and optionally read its contents.
Commands:
ls /root/
cat /root/myfile.txt
Expected Output:
myfile.txt
This is a file inside container
-
Step 6 (Optional) — Copy file back from container to host
Description: Create a new file inside the container and transfer it back to the host machine.
Commands:
Inside container:
echo "File coming back to host" > /root/return.txt
exit
Back on host:
docker cp testcopyfile:/root/return.txt .
ls
cat return.txt
Expected Output:
return.txt
File coming back to host
-
This demonstrates bidirectional file transfer between host and Docker containers, a critical skill for container-based development and debugging.