The Difference Between Docker Container and Docker Image
In this tutorial, we will learn the difference between a container and an image by showing the components that make up each and the features that make them different.
Understanding Layers in Docker
To create a custom image, we usually use a Dockerfile
that defines the instructions to create a custom image using a base image. The instructions that can be utilized to build an image in a Dockerfile
are as follows.
FROM node:16.17.0-alpine
WORKDIR /app
ADD package*.json ./
RUN npm install
ADD . .
CMD node index.js
A Docker image is created using layers that are stacked on top of each other. A new layer is added to the stack when the operation of an instruction in the Dockerfile is capable of adding or removing files.
Note that not all instructions defined in the Dockerfile create a new layer. For example, the CMD
instruction adds metadata to the image regarding the command to run within the container.
Also, note that the layers created using the Dockerfile are read-only except the last one.
When we create a container, a new thin layer is created. The difference between this layer and the previous layer is that we can read and write files from this layer.
After running a container, operations such as writing new files, modifying existing files, and deleting files are made in the thin read-write layer. The following is an image that shows a stack containing read-only layers of the image and a read-write layer of a container.
Difference Between Docker Container and Image
In the previous section, we have seen that the top layer on the stack is the thin read-write layer used by the container and the other layers are the read-only layers used to create the custom image.
This is the main difference between a Docker container and an image. Any changes that add or remove files from a container are made to the thin read-write layer of the specific container.
Note that deleting a container deletes its associated layer. However, the base image does not get deleted.
Each of the containers created has its read-write layer, allowing them to share the base image but maintain their data state. The following image shows how multiple containers share a base image.
Conclusion
We have learned in this tutorial how to differentiate a docker container from a docker image by using layers. We have learned that an image is created using the file named Dockerfile, and each instruction in the file forms a read-only layer stacked on top of another layer.
Finally, we have learned that the top layer is a read-write layer used by the container to add or modify file changes.
David is a back end developer with a major in computer science. He loves to solve problems using technology, learning new things, and making new friends. David is currently a technical writer who enjoys making hard concepts easier for other developers to understand and his work has been published on multiple sites.
LinkedIn GitHub