Kubernetes init container to verify dependent service(s) are online.

Init container to check if kubernetes service available

Kubernetes init container to verify dependent service(s) are online.
Page content

Introduction

With HELM Scripts containers all try to start at the same time. It depends on how the containers scripts were designed on if there is any sort of delay or dependency cchecking built into them. I wrote a very simple busybox script that can be used to prevent a container from starting until the kubernetes services is needs are available.

In this example there are 3 checks going on.

  • Is google on port 80 respeonding
  • Is Oracle on port 1521 responding
  • Is Oracle on port 8080 (apex) respending.

This very small init container will simple loop endlessly with the specified sleep delay until the services it needs are responding using netcat. There is no need to build another image, or even bother with a config map. The scripting can simple be passed in as a command to busybox. This small piece of yaml can be placed in your deployment and will be executed prior to the pod starting.

If you are using HELM the next step will be to remove the hard coded values in the bottom of this example and replace them with values passed in through HELM.

Init Container

      initContainers:
      - name: init-check
        image: docker.io/busybox:latest
        command:
         - sh
         - "-c"
         - |
           check_service () {
                   service=$1
                   delay=$2
                   echo "*** verifying ${service} is available ***"
                   nc -z -v -w5 ${service}
                   rc=$?
                   while [ ${rc} -ne 0 ]
                   do
                       echo sleeping ${delay}
                       sleep ${delay}
                       nc -z -v -w5 ${service}
                       rc=$?
                   done
                   echo "*** service online: ${service} ***"
            }
            check_service "google.com 80" "15"
            check_service "oracle.oracle121.svc.cluster.local. 1521" "15"
            check_service "oracle.oracle121.svc.cluster.local. 8080" "15"           

The paramaters on check_server are the following:

  1. Hostname and port number for service
  2. sleep delay between each attempt

The script will check the services in the order of the script, google -> oracle:1521 -> oracle:8080