Kubernetes - wait for other pod to be ready

You can use initContainers. Following is an example of how you can do in your YAML file

initContainers:
- name: wait-for-other-pod
  image: docker.some.image
  args:
  - /bin/sh
  - -c
  - >
    set -x;
    while [ $(curl -sw '%{http_code}' "http://www.<your_pod_health_check_end_point>.com" -o /dev/null) -ne 200 ]; do
      sleep 15;
    done

I have used curl to hit the health check endpoint, you can use any other UNIX command to check if the other pod is ready.

If you have a dependency on k8s resources, you can make use of stackanetes/kubernetes-entrypoint example:

initContainers:
- command:
  - kubernetes-entrypoint
  name: init-dependency-check
  env:
  - name: POD_NAME
    valueFrom:
      fieldRef:
        apiVersion: v1
        fieldPath: metadata.name
  - name: NAMESPACE
    valueFrom:
      fieldRef:
        apiVersion: v1
        fieldPath: metadata.namespace
  - name: DEPENDENCY_SERVICE
  - name: DEPENDENCY_DAEMONSET
  - name: DEPENDENCY_CONTAINER
  - name: DEPENDENCY_POD_JSON
    value: '[{"labels":{"app.kubernetes.io/name":"postgres"}}]'
  - name: COMMAND
    value: echo done
  image: projects.registry.vmware.com/tcx/snapshot/stackanetes/kubernetes-entrypoint:latest
  securityContext:
    privileged: true
    runAsUser: 0

In the above example, the pod with initContainer init-dependency-check will wait until pod with label "app.kubernetes.io/name":"postgres" is in the Running state. Likewise you can make use of DEPENDENCY_SERVICE, DEPENDENCY_DAEMONSET, DEPENDENCY_CONTAINER


Yes, it's possible using Init Containers (also, see this blog post for some background re timing) but a better, more Kubernetes-native pattern is to use retries and timeouts rather than hard-coding dependencies in this way.

Tags:

Kubernetes