Docker Copy Data Between Host and Container

DockerDockerBeginner
Practice Now

Introduction

In this lab, we are transported to the enchanting Royal Magic Academy, where we take on the role of a Royal Wizard. As a wizard, we are charged with the task of mastering the art of Docker magic to seamlessly transport valuable data between the mystical realms of the host and the container. Our ultimate goal is to wield the docker cp command to transfer data back and forth with finesse and precision.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL docker(("`Docker`")) -.-> docker/VolumeOperationsGroup(["`Volume Operations`"]) docker/VolumeOperationsGroup -.-> docker/cp("`Copy Data Between Host and Container`") subgraph Lab Skills docker/cp -.-> lab-271457{{"`Docker Copy Data Between Host and Container`"}} end

Transferring Data from Host to Container

In this step, we will harness the power of docker cp to transfer a magical spell script from the host to the container.

  1. First, let's create a file named spell.sh in the host's project directory with the following content:
#!/bin/bash
echo "Abracadabra! The spell is cast."
  1. Now, we will transfer this spell to the /var directory within a running Docker container named magic-app using the docker cp command:
docker cp ~/project/spell.sh magic-app:/var/spell.sh

Retrieving Data from Container to Host

In this step, we will tap into the arcane abilities of docker cp to transport a mystical potion recipe from the running container back to the host.

  1. Let's first ensure that the container magic-app has the file potion_recipe.txt in its /var directory by using the following command:
docker exec magic-app /bin/sh -c 'echo "hello" > /var/potion_recipe.txt'
docker exec magic-app ls /var/potion_recipe.txt
  1. Now, we will prestidigitate the potion_recipe.txt from the /var directory within the magic-app container to the host's project directory:
docker cp magic-app:/var/potion_recipe.txt ~/project/potion_recipe.txt

Mastery Challenge (Optional)

As a wizard seeking mastery, take on the challenge of transferring a whole directory of mystical artifacts between the host and the container using the docker cp command. Stun the instructors with your magical prowess!

Summary

In this lab, we delved into the enchanting world of Docker magic, mastering the art of seamlessly copying data between the host and the container using the docker cp command. By creating a captivating scenario within the Royal Magic Academy, we empowered aspiring wizards to harness this powerful Docker skill, ensuring they can wield it with confidence and finesse.

Other Docker Tutorials you may like