How to delete another pod when based on lifeCycle of one pod
Solution 1:
Disclaimer - as mentioned in the comments, you should avoid this solution (microservices should be independent) until you really have no other choice.
You can setup both postStart
and preStop
handlers (for installing kubectl
binary and for deleting the pods from deployment), but first you need to create a proper Service Account for the pod and Role(Bindings) with permissions to delete pods:
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: role-for-hook
subjects:
- kind: ServiceAccount
name: service-account-for-hook
namespace: default
roleRef:
kind: ClusterRole
name: delete-pods-role
apiGroup: rbac.authorization.k8s.io
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: service-account-for-hook
---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: delete-pods-role
labels:
# Add these permissions to the "view" default role.
rbac.authorization.k8s.io/aggregate-to-view: "true"
rules:
- apiGroups: ["*"]
resources: ["pods"]
verbs: ["delete","list"]
Then, you can use newly created Service Account + postStart
and preStop
handlers in pod / deployment definition - example for NGINX image. I assumed, that the label for the pods from the Service1
is app=service1
apiVersion: apps/v1
kind: Deployment
metadata:
name: service2-deployment
spec:
selector:
matchLabels:
app: service2
replicas: 2
template:
metadata:
labels:
app: service2
spec:
serviceAccountName: service-account-for-hook
containers:
- name: service2
image: nginx:latest
lifecycle:
postStart:
exec:
command: ["/bin/sh", "-c", "apt update && apt install curl && curl -L https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl -o /usr/local/bin/kubectl && chmod +x /usr/local/bin/kubectl"]
preStop:
exec:
command: ["/bin/sh", "-c", "kubectl delete pods -l app=service1"]
ports:
- containerPort: 80
Then, if the pod from Service2
is restarted, the pods from Service1
are also restarted.
Commands used in the command:
could be different for you, it depends which base image you are using for your application.