To create a docker image, following steps define the process:
Create a Dockerfile. A Dockerfile is a plain text file with a few lines of configuration inside it. This configruration is going to define how the container behaves, what different programs it is going to contain and what it does when it starts as a container.
The Dockerfile is then passed to the docker client.
Next, the docker client will pass the file to the docker server. The docker server will use the Dockerfile to build a usable image.
The below diagram illustrates the above process:
Creating a Dockerfile has the following flow:
Building a Dockerfile
As an example, we will create a Dockerfile to create an image that runs redis-server. Following is the content of the Dockerfile we will use to create an image:
# Use an existing docker image as a base
FROM alpine
# Download an install dependencies
RUN apk add --update redis
# Tell the image what to do when it starts as a container
CMD ["redis-server"]
Next, from the directory where the Dockerfile is created, run the following command:
docker build .
The output of the command would look some thing like below:
Next, we use the id of the build image to create and start the container using docker run:
docker run c5a737c182edf3e86517d93fff78126156a25373da067873642103e265933c90
Dockerfile Details
Following is the flow of what docker build command does using the Dockerfile:
Tagging an Image
Rather than starting and running a container using a id, we can tag an image during the build process with a name. Following is how it can be done:
The convention from tagging an image with a name is as follows:
So, the flow of commands for building an image with a tag name and running a container from the built image goes like below:
docker build -t amanalok/redis:latest .
docker run amanalok/redis
Image Generation with Docker Commit
Till now, we created and started a container using a docker image. We can also go the other way and create a docker image using a running container.
Following is an example how to go about image generation using a running container:
docker run -it alpine sh
/ # apk add --update redis
As can be observed above, we started a container using an alpine image and installed redis inside the container. Next, we get the id of this running container and use it to generate an image from it.
docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
5641b2fb1c27 alpine "sh" About a minute ago Up About a minute thirsty_hodgkin
docker commit -c 'CMD ["redis-server"]' 5641b2fb1c27
sha256:fe47718978513557c7d7fd9a3f27ba4e937a4e2cb1d9fb1f2dc8f7472ce5a6a2
Finally, using the id of the generated image, we can run a new container:
docker run fe47718978513557c7d7fd9a3f27ba4e937a4e2cb1d9fb1f2dc8f7472ce5a6a2