Working with Docker Containers
Introduction
Docker is a popular containerization tool used to provide software applications with a filesystem that contains everything they need to run. Using Docker containers ensures that the software will behave the same way, regardless of where it is deployed, because its run-time environment is ruthlessly consistent.
In this tutorial, we’ll provide a brief overview of the relationship between Docker images and Docker containers. Then, we’ll take a more detailed look at how to run, start, stop, and remove containers.
Overview of Working with Docker Containers
We can think of a Docker image as an inert template used to create Docker containers. Images typically start with a root filesystem and add filesystem changes and their corresponding execution parameters in ordered, read-only layers. Unlike a typical Linux distribution, a Docker image normally contains only the bare essentials necessary for running the application. The images do not have state and they do not change. Rather, they form the starting point for Docker containers.
Images come to life with the docker run
command, which creates a container by adding a read-write layer on top of the image. This combination of read-only layers topped with a read-write layer is known as a union file system. When a change is made to an existing file in a running container, the file is copied out of the read-only space into the read-write layer, where the changes are applied. The version in the read-write layer hides the original file but doesn’t remove it. Changes in the read-write layer exist only within an individual container instance. When a container is deleted, any changes are lost unless steps are taken to preserve them.
How to: Working with Docker Containers
- Create Two Docker Containers
- Restart the First Container
- Delete Both Containers
Step 1: Creating Two Containers
The following docker run
command will create a new container using the base Ubuntu image. The -t
flag gives us a terminal, and -i
allows interaction:
docker run -ti ubuntu
Once inside the container, create and verify a file:
echo "Example1" > /tmp/Example1.txt
cat /tmp/Example1.txt
Output:
Example1
Exit the container with:
exit
Step 2: Restarting the First Container
To restart the first container, use the docker start
command:
docker start -ai 11cc47339ee1
Verify the file inside:
cat /tmp/Example1.txt
Output:
Example1
Exit again with:
exit
Step 3: Deleting Both Containers
Delete the containers using the docker rm
command:
docker rm 11cc47339ee1 kickass_borg
Output:
11cc47339ee1
kickass_borg
Conclusion for Working with Docker Containers
We’ve taken a detailed look at the docker run
command to see how it automatically creates a new container each time it is run. We’ve also seen how to locate a stopped container, start it, and connect to it.