jbrown
jbrown

Reputation: 7986

How to create a post-init container in Kubernetes?

I'm trying to create a redis cluster on K8s. I need a sidecar container to create the cluster after the required number of redis containers are online.

I've got 2 containers, redis and a sidecar. I'm running them in a statefulset with 6 replicas. I need the sidecar container to run just once for each replica then terminate. It's doing that, but K8s keeps rerunning the sidecar.

I've tried setting a restartPolicy at the container level, but it's invalid. It seems K8s only supports this at the pod level. I can't use this though because I want the redis container to be restarted, just not the sidecar.

Is there anything like a post-init container? My sidecar needs to run after the main redis container to make it join the cluster. So an init container is no use.

What's the best way to solve this with K8s 1.6?

Upvotes: 24

Views: 19617

Answers (3)

Clintm
Clintm

Reputation: 4867

Adding postStart as an optional answer to this problem:

https://kubernetes.io/docs/tasks/configure-pod-container/attach-handler-lifecycle-event/#define-poststart-and-prestop-handlers

apiVersion: v1
kind: Pod
metadata:
  name: lifecycle-demo
spec:
  containers:
  - name: lifecycle-demo-container
    image: nginx
    lifecycle:
      postStart:
        exec:
          command: ["/bin/sh", "-c", "echo Hello from the postStart handler > /usr/share/message"]

Upvotes: 4

jbrown
jbrown

Reputation: 7986

A better answer is to just make the sidecar enter an infinite sleep loop. If it never exits it'll never keep on being restarted. Resource limits can be used to ensure there's minimal impact on the cluster.

Upvotes: 4

Javier Salmeron
Javier Salmeron

Reputation: 8827

I advise you to use Kubernetes Jobs:

https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/

This kind of Job will keep running until it is completed once. In this job you could try detecting if all the required nodes are available in order to form the cluster.

Upvotes: 8

Related Questions