Building Docker Image in Kubernetes

Presently, containerization is one of the most trending concepts in the IT industry. When it comes to the most reliable system for managing, scaling, and deployment of containerized apps, Kubernetes is the name that you can rely on. Containerization is running the apps in an isolated space called containers. The process of containerization needs to have a base image that will be utilized to build a container.

This image can be pushed to a container registry which is used by Kubernetes to deploy containers in a cluster pod. Docker is one of the most renowned choices of container runtimes for Kubernetes where images can be created through Dockerfile. Furthermore, it contains all the necessary commands in the correct order of execution for building an image in Kubernetes. In this article, you will get to know about building Docker image in Kubernetes, and the most suitable tools to accomplish this task.

Building Docker Image in Kubernetes

What is a Docker Image?

Docker is a platform used for creating, running, and deploying applications in a container. A Docker container file comes with the right instructions that can help in building a Docker container and can be used in executing the code in the container. In addition, it includes tools, code, libraries, and dependencies, among other necessary files. 

One of the foremost perks of using a Docker file is the reduction in disk usage due to its multi-layer nature where each layer originates from the previous layer but has certain differences. Initially, these layers are read-only files, but a writable layer is added on top of unchangeable images after creating a container.

Working of Image Building in Docker

Before you move forward, it is essential to understand how image building works in Docker. Initially, in the FROM directive of the Dockerfile, the Docker will start a container with the base image. Now, Docker will implement all the commands inside the Dockerfile and take a snapshot. This snapshot of the container is called the Docker image. The entire process is followed by Docker to attain this Docker image. However, this is not the only way to get the image. Several tools can be used to get the same image but through different implementations.  

Top Tools for Building Docker Image in Kubernetes

Building Docker image in Kubernetes requires the execution of several actions and commands which can only be made easier through the right tools. Moreover, tools help in ensuring that the infrastructure of the application remains secure and uncompromised. Here are the tools that you for building Docker image in Kubernetes

1. Kaniko

Kaniko is among the most widely used tools for building Docker images in the Kubernetes cluster. Rather than relying on the Docker daemon for executing this task, this tool executes the command within a Dockerfile. In addition to Kubernetes, this tool is capable of working with Google Container Builder as well.

There are three arguments included in the image-building process; Dockerfile, build context, and the registry name. Using these three arguments, Kaniko can build a Docker image from scratch.

2.Buildah

Buildah is used to build Open Container Initiative images where it imitates commands of Dockerfile. With this tool, you can create an image, or container, mount and unmount the root filesystem on a container, delete an image or container or rename a container. This tool does not require Dockerfile or root privileges to build images. 

3. Docker in Docker

Not exactly a tool but a methodology to run Docker within the Docker to build images in a Kubernetes cluster. Here you can build a Docker container in Kubernetes through mounting /var/run/docker.sock file. One major benefit of this method is that it will have all the required Docker tools to complete the job. 

4. Sysbox

Developed by Nestybox, Sysbox is an open-source container runtime tool that is currently managed by Docker. With this tool, you can allow containers to run the same workloads as virtual machines. Sysbox will help you in locking the initial mount of a container, virtualization of syfs and procfs inside a container, and hiding the information of the host inside the container. 

5. img

Akin to Kaniko, img is also an Open Container Initiative and daemon-less image building tool. It uses BuildKit’s (another container image building tool) DAG solver as its image builder due to which it can execute several build stages at the same time efficiently. 

Building Docker Images in Kubernetes

Lets explore different ways of building docker images in Kubernetes. Though there are different ways of doing so, your priority is to determine the most suitable one for yourself. Below are the ways of building docker image in Kubernetes.

1. Kaniko

As stated earlier, Kanioko is a renowned tool for building Docker images where it builds container images from a Dockerfile within a Kubernetes cluster. You can build images in all such environments where running a Docker daemon is complicated or unsecured. 

To build images through Kaniko, you need to install Docker Desktop and enable Kubernetes in your system. Furthermore, you need a GitHub account to access Dockerfile and a Docker hub account. The following is the command code for building Docker images in Kubernetes using Kaniko.

FROM ubuntu

ENTRYPOINT [\”/bin/bash\”, \”-c\”, \”echo Hello to Kaniko from Kubernetes\”]

pod.yml contains this code for the kaniko configurations:

apiVersion: v1

kind: Pod

metadata:

  name: kaniko-demo

spec:

  containers:

  – name: kaniko-demo

    image: gcr.io/kaniko-project/executor:latest

    args: [\”–context=git://github.com/agavitalis/kaniko-kubernetes.git\”,

            \”–destination=agavitalis/kaniko-build-demo:1.0.0\”,

            \”–dockerfile=dockerfile\”]

    volumeMounts:

      – name: kaniko-secret

        mountPath: /kaniko/.docker

  restartPolicy: Never

  volumes:

    – name: kaniko-secret

      secret:

        secretName: reg-credentials

        items:

          – key: .dockerconfigjson

            path: config.json

How Kaniko Works?

Being an open-source image building tool, the functioning of Kaniko is uncomplicated and highly elaborated. The following is the process followed by Kaniko to build Docker images.

  • This tool comes with a specific Kaniko image executer which is responsible for building container images. 
  • Dockerfile, build context, and a remote Docker registry are the three arguments accepted by this tool.
  • Once the image is deployed, the tool reads the Dockerfile. Afterward, it uses the FROM instruction to extract the base image file system.
  • After that, Kaniko implements the instructions from the Dockerfile and snapshots of the same in the userspace. 
  • After taking the snapshot, it updates the metadata of the changed image layers in the Dockerfile.
  • Once all the necessary actions are done, Kaniko will push the image to the desired registry.

2. Docker in Docker

Docker in Docker is one of the commonest methods for building Docker images in Kubernetes in CI/CD pipelines. Here, a Docker container runs its specific Docker daemon which makes it uncomplicated to set up. Being easy to set up surely makes it popular, but it comes with a few security complications. 

Initially, Docker created containers so that they can function in privileged mode through this method where the container will run as root on the host. Any person with access to the Docker socket will automatically have access to create new users, run software, and access anything they want within the container, reducing the overall security of the architecture.

On the other hand, this process is uncomplicated and can be used to accelerate internal processes. The following is the YAML for Docker in Docker. After you launch the pod, my-container can access the Docker daemon in the container. 

 containers:

  – name: my-main-container

    # …

    # other container config here

    # …

    env:

    – name: DOCKER_HOST

      value: tcp://localhost:2375

  – name: dind

    image: docker:18.05-dind

    securityContext:

      privileged: true

    volumeMounts:

      – name: dind-storage

        mountPath: /var/lib/docker

volumes:

  – name: dind-storage

    emptyDir: {}

3. Docker Out of Docker

Another method of building images in the Kubernetes cluster is Docker out of Docker where the Docker inside the container will be connected to the Docker daemon used by the Kubernetes cluster. Among all the methods, the Docker out of Docker is the easiest to set up. However, as containers should run as privileged, it could potentially cause a security hazard. Furthermore, it also breaks Kubernetes scheduling.

Moving forward, here is the configuration that you can use in Docker out of Docker method of building Docker images in Kubernetes.

containers:

  – name: my-container

    # …

    # other container config here

    # …

    volumeMounts:

    – mountPath: /var/run/docker.sock

      name: docker-socket-volume

    securityContext:

      privileged: true

volumes:

  – name: docker-socket-volume

    hostPath:

      path: /var/run/docker.sock

      type: File

4. img

Img is another tool for building Docker images on Kubernetes. Along with img, Amazon EKS Cluster on AWS is used in this process. The foremost step is to create a configmap for Docker configuration (docker-config.yaml) with the following command.

apiVersion: v1

kind: ConfigMap

metadata:

  name: docker-config

data:

  config.json: |-

    {

      \”credHelpers\”: {

        \”123456789498.dkr.ecr.us-west-2.amazonaws.com\”: \”ecr-login\”

      }

    }    

Afterward, you need to place the following script in the section where pipeline scripts are added.

pipeline {

  agent {

    kubernetes {

      //cloud \’kubernetes\’

      yaml \”\”\”

kind: Pod

metadata:

  name: kaniko

spec:

  containers:

  – name: kaniko

    image: gcr.io/kaniko-project/executor:debug-539ddefcae3fd6b411a95982a830d987f4214251

    imagePullPolicy: Always

    command:

    – cat

    tty: true

    volumeMounts:

      – name: docker-config

        mountPath: /kaniko/.docker

  volumes:

    – name: docker-config

      configMap:

        name: docker-config

\”\”\”

    }

  }

  stages {

    stage(\’Build with Kaniko\’) {

      steps {

        git \’https://github.com/prabhatsharma/sample-microservice\’

        container(name: \’kaniko\’) {

            sh \’\’\’

            /kaniko/executor –dockerfile `pwd`/Dockerfile –context `pwd` –destination=123456789498.dkr.ecr.us-west-2.amazonaws.com/sample-microservice:latest –destination=123456789498.dkr.ecr.us-west-2.amazonaws.com/sample-microservice:v$BUILD_NUMBER

            \’\’\’

        }

      }

    }

  }

}

Now all you have to do is save the pipeline and build the image. Keep in mind that this code can be used on the Amazon EKS cluster to run Kubernetes. 

FAQ

Q1: Can Docker images store data?

Users can store data in Docker images, but it is not advised by professionals as the data can be lost or can compromise its security. The right practice is to use the host to store data.

Q2: How many images can be created from a Docker image base?

An unlimited number of Docker images can be created from a single image base.

Q3: What is the default Docker Image Registry?

The default Docker image registry is Docker Hub.

Q4: Can a base image be personalized?

Docker images can be personalized by the users. All they have to do is pull the image from the Docker hub to the local system using the following code.
$ docker pull <image_name>

Q5: What is the command to delete an image from the local storage?

To delete an image from the local storage system, you have to run the following command.
$ docker rmi <image-id>

Leave a Reply

Scroll to Top

Our team of experts would be delighted to meet you and learn all about your business.

Work at ThinkSys

Please attach your résumé / curriculum vitae below.
Only PDF files below 16mb accepted.
%d bloggers like this: