Modifying files in a running container
In this step, we will learn how to modify files within a running container. This can be useful for debugging purposes, such as changing configuration files or adding temporary scripts to a container that is already running.
We will start by running a simple container based on the ubuntu
image, which is more feature-rich than alpine
and includes a shell and common utilities.
docker run -d --name my-ubuntu ubuntu sleep 3600
This command runs an Ubuntu container in detached mode (-d
) and keeps it running for an hour using the sleep 3600
command. We've named the container my-ubuntu
for easy reference.
Now, let's use docker exec
to get a shell inside the running container.
docker exec -it my-ubuntu /bin/bash
You should now be inside the bash shell of the my-ubuntu
container. The prompt will change to reflect that you are inside the container.
Inside the container, let's create a new file in the /tmp
directory.
echo "This is a test file." > /tmp/test_file.txt
Now, let's verify that the file was created and contains the correct content.
cat /tmp/test_file.txt
You should see the output This is a test file.
. This confirms that we were able to create and write to a file inside the running container.
To exit the container's shell, simply type exit
.
exit
You are now back in your LabEx VM terminal.
We can also copy files into and out of a running container using the docker cp
command. Let's create a file on our LabEx VM and copy it into the container.
First, create a file named local_file.txt
in your ~/project
directory.
echo "This file is from the host." > ~/project/local_file.txt
Now, copy this file into the /tmp
directory of the my-ubuntu
container.
docker cp ~/project/local_file.txt my-ubuntu:/tmp/
The format for docker cp
is docker cp <source_path> <container_name>:<destination_path>
or docker cp <container_name>:<source_path> <destination_path>
.
Let's verify that the file was copied into the container. Get back into the container's shell.
docker exec -it my-ubuntu /bin/bash
Inside the container, check for the presence of local_file.txt
in /tmp
.
ls /tmp/
You should see local_file.txt
listed along with test_file.txt
.
Now, let's view the content of local_file.txt
inside the container.
cat /tmp/local_file.txt
You should see the output This file is from the host.
.
Exit the container's shell again.
exit
Finally, let's clean up the container.
docker stop my-ubuntu
docker rm my-ubuntu
This step demonstrated how to modify files within a running container using docker exec
to get a shell and standard Linux commands, and how to copy files between the host and the container using docker cp
.