Copy a local file into a container
In this step, you will learn how to copy a file from your local filesystem into a running Docker container. This is a common task when you need to add configuration files, scripts, or other data to a container after it has been started.
First, let's create a simple text file on your local machine within the ~/project
directory.
echo "This is a test file." > ~/project/test_file.txt
This command creates a file named test_file.txt
in your ~/project
directory and writes the text "This is a test file." into it.
Next, we need a running container to copy the file into. We will use a simple ubuntu
image for this purpose. Since the image might not be present locally, we will first pull it.
docker pull ubuntu:latest
This command downloads the latest version of the ubuntu
image from Docker Hub.
Now, let's run a container based on the ubuntu
image. We will run it in detached mode (-d
) and give it a name (my_ubuntu_container
) for easy identification.
docker run -d --name my_ubuntu_container ubuntu:latest sleep infinity
This command starts a new container named my_ubuntu_container
using the ubuntu:latest
image. The sleep infinity
command keeps the container running indefinitely, which is useful for demonstration purposes.
You can verify that the container is running using the docker ps
command.
docker ps
You should see my_ubuntu_container
listed in the output.
Now, we can copy the test_file.txt
from your local machine into the running container using the docker cp
command. The syntax is docker cp <local_path> <container_name>:<container_path>
.
docker cp ~/project/test_file.txt my_ubuntu_container:/tmp/
This command copies the file ~/project/test_file.txt
into the /tmp/
directory inside the my_ubuntu_container
.
To verify that the file was successfully copied, you can execute a command inside the container using docker exec
. We will use ls
to list the files in the /tmp/
directory of the container.
docker exec my_ubuntu_container ls /tmp/
You should see test_file.txt
listed in the output, confirming that the file was copied successfully.
Finally, let's clean up the container we created.
docker stop my_ubuntu_container
docker rm my_ubuntu_container
These commands stop and remove the container, respectively.