What should I do if I want to run a shell script in pod definition file when pod restarts?

8/4/2021

We have an architecture of master, data and client in elastic search. When for some reason if data nodes are restarted, the client is failing to communicate with the data node. In order to make a connection with the data node I have run a script in that node manually. So, I want to automate it by running scripts inside a pod definition file. Is there a way?

-- Sayyapureddy Srinivas
elasticsearch
kubernetes

2 Answers

8/4/2021

This is a scenario initContainers are intended for. Details and example definition available here.

-- Rick Rainey
Source: StackOverflow

8/5/2021

For the described purpose, you can use postStart handler.

Kubernetes sends such events right after a Container is started.

To process postStart event you need to add lifecycle section in your pod specification, as below. You can find example in Define postStart and preStop handlers documentation:

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

Please keep in mind, according to handlers documentation disscussion,

Kubernetes sends the postStart event immediately after the Container is created. There is no guarantee, however, that the postStart handler is called before the Container's entrypoint is called. The postStart handler runs asynchronously relative to the Container's code, but Kubernetes' management of the container blocks until the postStart handler completes. The Container's status is not set to RUNNING until the postStart handler completes.

Check also: multiple command in postStart hook of a container

-- Andrew Skorkin
Source: StackOverflow