Sidecar Containers and Init Containers in Kubernetes

0
3851
Sidecar containers and init containers in Kubernetes

So far, we have seen some advance topics on Kubernetes with Argo CD and Prometheus, now let’s step back and see some basic resources which is useful and may widely used in GitOps and any temporary jobs. In this we are going to see what is Init container and sidecar containers and where can use it.

Init containers run before applications containers run in a pod, by default it supports many features of application containers and sidecar containers run alongside application containers in a pod. You can define any number of sidecar containers to run alongside the main container.

What is Sidecar Container?

A sidecar is just a container that runs on the same Pod as the application container. It shares the same volume and network as the main container, it can “help” or enhance how the application operates. A Sidecar container is a second container to add the pod when it requires to use the any resources that use by the main container.

Sidecar container

Let’s say we have requirement to collect the log from existing container in pod, as we cannot stop/breaking existing setup. In this case sidecar helps more here. In this example assume, we have a webserver container running Nginx image. The logs produced by the main container are not enough to be placed on a persistent volume. However, developers need access to the last 24 hours of logs so they can trace issues and bugs. Therefore, we need to ship the access and error logs for the webserver to a log-aggregation service(s).

Following the separation of concerns principle, we implement the Sidecar pattern by deploying a second container that ships the Nginx error and access logs. Since containers are running on the same Pod, we can use a shared empty Dir volume to read and write logs.

apiVersion: v1
kind: Pod
metadata:
  name: sidecar
spec:
  volumes:
    - name: shared-logs
      emptyDir: {}

  containers:
    - name: nginx
      image: nginx
      volumeMounts:
        - name: shared-logs
          mountPath: /var/log/nginx

    - name: sidecar-container
      image: nginx
      command: ["bin/bash","-c","while true; do cat /var/log/nginx/access.log /var/log/nginx/error.log; sleep 30; done"]
      volumeMounts:
        - name: shared-logs
          mountPath: /var/log/nginx

The above definition is a standard Kubernetes Pod definition except that it deploys two containers to the same Pod. The sidecar container conventionally comes second in the definition so that when you issue the kubectl execute the command, you target the main container by default.

The main container is a Nginx container that stores its logs on a volume mounted on /var/log/nginx. Mounting a volume at that location prevents Nginx from outputting its log data to the standard output and forces it to write them to access.log and error.log files.

Use case of side-car container

These are some of the scenarios where you can use this pattern

  • To extend the functionality of the existing single container pod without touching the existing one.
  • To enhance the functionality of the existing single container pod without touching the existing one.
  • To synchronize the main container code with the git server, pull.
  • For ship log events to the external server.
  • Also, we can use sidecar for network-related tasks.

Best Practices of side-car container

It is crucial to follow sidecar best practices during implementation, both for security reasons and to maximize the sidecar’s efficiency and productivity. You’ll learn about some of those practices in this section.

  • Make sure there is a reason for separating the containers.
  • Strive to make them small, Modular Applications
  • Aware of the resource limits, it should not break the main containers.

What is Init Container?

A pod can have Init Containers in addition to application containers. Init containers allow you to reorganize setup scripts and binding code.

An init container is the one that starts and executes beforeother containers in the same Pod. It’s meant to perform initialization logic for the main application hosted on the Pod.

Properties of Init container

  • It contains utilities or setup scripts not present in an app image (making images light-weight)
  • They always run to completion
  • Init container executes sequentially and each of the init containers must succeed before the next can run.
  • They support all the fields and features of app containers, including resource limits, volumes, and security settings.
  • Init-containers do not support lifecycle, liveness probe, readiness probe, or startup probe because they must run to completion.

Use cases of Init container

  • Init containers can contain utilities or custom code for the setup that are not present in an app image.
  • They can be given access to Secrets that app containers cannot access, like pulling the secrets from vault or other apps.
  • Performing an automated restore from backup in case the data volume is empty (initial setup after a major outage) or contains corrupt data (automatically recover the last working version).
  • Doing database schema updates and other data maintenance tasks that depend on the main application not running.
  • Ensure that the application data is in a consistent and usable state, repairing it if necessary.
  • Clone a Git repository into a Volume
  • It can be used to wait for a service to start that is to be used by the main app
  • An init container is a good candidate for delaying the application initialization until one or more dependencies are available.

Create a pod with init-container

apiVersion: v1
kind: Pod
metadata:
  name: init-container
  labels:
    purpose: initContainers-demo
spec:
  initContainers:
  - name: init-container
    image: busybox
    command: ["echo","Hello, I am init-conatiner"]
  - name: init-busybox2
    image: busybox
    command: ["sleep","30"]

  containers:
  - name: main-container
    image: busybox
    command: ["echo","main container"]
  restartPolicy: Never

Output

# kubectl apply -f init-container.yml
pod/init-pod created

Check Status of init-container
# kubectl get pod init-container -o wide
NAME             READY   STATUS      RESTARTS   AGE   IP            NODE       
init-container   0/1     Completed   0          49s   x.x.x.x   

# kubectl get po init-container
NAME             READY   STATUS      RESTARTS   AGE
init-container   0/1     Completed   0          10m12s

Hope this is useful, as we are going to test more examples with sidecar and init containers in upcoming examples, this should gave heads up. If you like this please share and follow us on social media.

Facebook: https://www.facebook.com/foxutech/
Medium: https://foxutech.medium.com/
Twitter: https://twitter.com/foxutech

Google search engine