Creating a docker image

Creating a docker image

Let's discuss first what will we do for creating a docker image. First, we will pull the image from the docker hub (public registry for container images), then spin up the container using the image we pulled, add some files in the container then make an image of the container in which we added files, to verify whether the files are still present in the container we will spin the container from the image we created.

Step1: Pulling the image from DockerHub

Open up your Linux terminal and write the following command-

$ docker pull ubuntu

This command is used to download the image from the dockerhub, also if no version is specified then it will download the latest version of the image. To check whether the image is being downloaded, do

$ docker images

The output of the command will be like this:

Here we can see the ubuntu image with the latest version of it.

Step2:Creating a container

Let's spin the container using this image

$ docker run -it --name firstcontainer ubuntu /bin/bash

This command lets us inside the container named firstcontainer with ubuntu as the image.

Making some changes inside the container we are in, let's make a directory and some files inside it. To check the changes we made inside the container, exit the container and write the command-

$ docker diff firstcontainer

This will show the difference between the freshly prepared container and the updated container.

We made a directory named "Docker" and three files inside the docker directory i.e fileA, fileB and fileC.

Step3:Creating an image out of the container

Now let's create the image of the container in which we made these changes i.e the firstcontainer-

$ docker commit firstcontainer newimage

Here docker commit is the command used to create a new image from a container. It allows you to save the changes made to a container as a new image, which can then be used to create new containers with the same changes. And the 'newimage' is the name of the image formed from the container.

Step4:Spinning container with the committed image

Now we will spin up a container with newimage as the image using the command-

$ docker run -it --name newcontainer newimage /bin/bash

We will be able to see the Docker directory which we created earlier and even inside the directory we will be able to see the files that we created.

Hence in this one, we pulled the image from the dockerhub and ran a container of it and again created an image out of that container.