Docker is widely used to containerize applications. There are also other containerization platforms such as Containerd, Rkt (Rocket), etc., but Docker is dominating the market.
In this article, we will see what is Docker image?, the layers of a Docker image, and how to write a custom Docker image.
• What is Docker Image?
Docker Image is like a readymade template. It contains predefined code, libraries that help you to create containers. All are combined in a single file. So, there's no need to create an explicitly environment because that Docker Image is providing you that type of environment. So just need to run the Docker Image that's it.
Remember 📝 -
The Docker Image is written in a file that does not have an extension, and the name of that file is Dockerfile.
Remember the hierarchy -
Dockerfile creates a Docker Image
Docker Image creates a container
Before going to understanding the layers of a Docker Image, let's see what exactly the Dockerfile looks like.
FROM openjdk:17-slim
WORKDIR ./app
COPY . .
RUN javac HelloWorld.java
CMD ["java", "HelloWorld"]
The above code is the simple Docker Image code, which will create a java image with the Hello World Program. So, when we create the container from this image, we will be able to see the output.
• What are layers in Docker Image
Every line in the Dockerfile acts as a layer for the Docker Image
From the above code, let's break it down.
FROM openjdk:17-slim
This line acts as a base layer for the Docker Image. On the above, those remaining lines will execute. In some Docker Images, the base layer is ubuntu also. In our case, it is OpenJDK.
WORKDIR ./app
This line is the working directory for the Dockerfile. It will create a working directory where all the files related to the Dockerfile will be stored. This line will act as a second layer for the Docker Image.
COPY . .
This line will copy all the files in the working directory that are required to create the Docker Image. This is the third layer for the Docker Image.
RUN javac HelloWorld.java
After copying all the files in the working directory, this line will execute, and the Docker Image will be created. This is the fourth layer for the Docker Image.
CMD ["java", "HelloWorld"]
This line will execute during container creation. It is the fifth layer for the Docker Image.
Now, let's create a Docker Image of the Simple Java Hello World Program from the code which is mentioned above.
Command to create a Docker Image
docker build -t java-image .
Docker Image has been created.
Lastly, let's create a container. So, we will be able to see the output of the Java Code.
In this way, we have seen each layer of the Docker Image.