Introduction
In the previous chapter, we learned how to run our first Docker container by pulling a pre-built Docker image from the Docker Hub. While it is useful to get pre-built Docker images from Docker Hub, we must know how to create custom Docker images. This is important for running our applications on Docker by installing new packages and customizing the settings of the pre-built Docker images. In this chapter, we are going to learn how to create our custom Docker image and run a Docker container based on it.
This will be done using a text file called a Dockerfile
. This file consists of commands that can be executed by Docker to create a Docker image. Docker images are created from a Dockerfile
using the docker build
(or docker image build
) command.
Note
Beginning with Docker 1.13, the Docker CLI syntax has been restructured to the form of Docker COMMAND SUBCOMMAND. For example, the docker build
command was replaced by the docker image build
command. This restructuring was carried out to clean up the Docker CLI syntax and gain a more consistent grouping of commands. Currently, both syntaxes are supported, but the old syntax is expected to be deprecated in the future.
A Docker image consists of multiple layers, each layer representing the commands provided in the Dockerfile
. These read-only layers are stacked on top of one another to create the final Docker image. Docker images can be stored in a Docker registry, such as Docker Hub, which is a place where you can store and distribute Docker images.
A Docker container is a running instance of the Docker image. One or more Docker containers can be created from a single Docker image using the docker run
(or docker container run
) command. Once a Docker container is created from the Docker image, a new writeable layer will be added on top of the read-only layers from the Docker image. Docker containers can then be listed with the docker ps (or docker container list) command:
As illustrated in the preceding diagram, there can be one or more read-only layers that make up the Docker image. These read-only layers are generated for each command in the Dockerfile
during the Docker image build process. Once a Docker container is created from the image, a new read-write layer (known as the Container layer) will be added on top of the image layers and will host all the changes made on the running container.
In this chapter, we will write our first Dockerfile
, build the Docker image from the Dockerfile
, and run a Docker container from our custom Docker image. Before we can perform any of these tasks, however, we must first define a Dockerfile
.