Saturday, February 17, 2024

Kubernetes "depends-on" solution

Docker supports "depends_on" feature to define dependency between containers.

Kubernetes deployment is more involved, since it is distributed, and equivalent features in not available directly. 

Instead, there is option to define "initContainers" that can implement logic to check if required services are available before starting the Pod's main container. The "init" could be a custom script with generic mini-shell container, or it could be a dedicated container.

There is also an option to add "annotations" that can help human understanding of dependencies, while not enforced directly by K8s.

What is the equivalent for depends_on in kubernetes - Stack Overflow

spec:
      initContainers:
      - name: wait-for-grafana
        image: darthcabs/tiny-tools:1
        args:
        - /bin/bash
        - -c
        - >
          set -x;
          while [[ "$(curl -s -o /dev/null -w ''%{http_code}'' http://grafana:3000/login)" != "200" ]]; do 
            echo '.'
            sleep 15;
          done
      containers:
          .
          .
  (your other containers)

Opsfleet/depends-on: Small utility & container to describe dependency relationship between Kubernetes deployments @GitHub (GoLang, MIT)

Kubernetes and Helm don't have a built-in mechanism to deploy pods in a specific order.

Solution: This small container allows you to add an InitContainer hook to all of your deployment YAML files to create a dependency relationship to other services and/or jobs in the same namespace:

initContainers:
- name: wait-for-services
  image: opsfleet/depends-on
  args:
  - "-service=mongodb"
  - "-service=rabbitmq"
  - "-job=myjob"

Declare dependencies between resource objects  |  Config & Policy  |  Google Cloud

# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: wordpress
 
namespace: default
 
labels:
    app: wordpress
 
annotations:
    config.kubernetes.io/depends-on: apps/namespaces/default/StatefulSet/wordpress-mysql

Annotating Kubernetes Services for Humans | Kubernetes

apiVersion: v1
kind: Pod
metadata:
  name: worker
  annotations:
    a8r.io/dependencies: “services: db, redis”

No comments: