8ec3a4abf74b ubuntu "bash -c 'touch /hal…" About a minute ago Up About a minute (unhealthy) healt
Kubernetes предоставляет (kubernetes.io/docs/tasks/configure-POD-container/configure-liveness-readiness-probes/) три инструмента, которые проверяют состояние контейнера из вне. Они имеют больше значение, так они служат не только для информирования, но и для управления жизненным циклом приложения, накатом и откатом обновления. Их неправильная настройка может, и часто такое бывает, приводят к неработоспособности приложения. Так, к если liveness проба буте срабатывать до начала работы приложения – Kubernetes будет убивать контейнер, не дав ему подняться. Рассмотрим её более подробно. Проба liveness служит для определения работоспособности приложения и в случае, если приложение сломалось и не отвечает на пробу liveness – Kubernetes перезагружает контейнер. В качестве примера возьмём shell-пробу, из-за простоты демонстрации работы, но на практике её следует использовать только в крайних случаях, например, если контейнер запускается не как долгоживущий сервер, а как JOB, выполняющий свою работу и завершающий своё существование, достигнув результата. Для проверок серверов лучше использовать HTTP-пробы, которые уже имеют встроенный выделенный проксировщик и не требуют наличия в контейнере curl и не зависящие от внешних настроек kube-proxy. При использовании баз данных нужно использовать TCP-пробу, так как HTTP—протокол они обычно не поддерживают. Создадим долгоживущий контейнер в www.katacoda.com/courses/kubernetes/playground:
controlplane $ cat << EOF > liveness.yaml
apiVersion: v1
kind: Pod
metadata:
name: liveness
spec:
containers:
– name: healtcheck
image: alpine:3.5
args:
– /bin/sh
– -c
– touch /tmp/healthy; sleep 10; rm -rf /tmp/healthy; sleep 60
livenessProbe:
exec:
command:
– cat
– /tmp/healthy
initialDelaySeconds: 15
periodSeconds: 5
EOF
controlplane $ kubectl create -f liveness.yaml
pod/liveness created
controlplane $ kubectl get pods
NAME READY STATUS RESTARTS AGE
liveness 1/1 Running 2 2m11s
controlplane $ kubectl describe pod/liveness | tail -n 10
Type Reason Age From Message
–– – – – –
Normal Scheduled 2m37s default-scheduler Successfully assigned default/liveness to node01
Normal Pulling 2m33s kubelet, node01 Pulling image "alpine:3.5"
Normal Pulled 2m30s kubelet, node01 Successfully pulled image "alpine:3.5"
Normal Created 33s (x3 over 2m30s) kubelet, node01 Created container healtcheck
Normal Started 33s (x3 over 2m30s) kubelet, node01 Started container healtcheck
Normal Pulled 33s (x2 over 93s) kubelet, node01 Container image "alpine:3.5" already present on machine
Warning Unhealthy 3s (x9 over 2m13s) kubelet, node01 Liveness probe failed: cat: can't open '/tmp/healthy': No such file or directory
Normal Killing 3s (x3 over 2m3s) kubelet, node01 Container healtcheck failed liveness probe, will be restarted
Мы видим, что контейнер постоянно перезапускается.
controlplane $ cat << EOF > liveness.yaml
apiVersion: v1
kind: Pod
metadata:
name: liveness
spec:
containers:
– name: healtcheck
image: alpine:3.5
args:
– /bin/sh
– -c
– touch /tmp/healthy; sleep 30; rm -rf /tmp/healthy; sleep 60
livenessProbe:
exec:
command:
– cat
– /tmp/healthy
initialDelaySeconds: 15
periodSeconds: 5
EOF
controlplane $ kubectl create -f liveness.yaml
pod/liveness created
controlplane $ kubectl get pods
NAME READY STATUS RESTARTS AGE
liveness 1/1 Running 2 2m53s
controlplane $ kubectl describe pod/liveness | tail -n 15
SecretName: default-token-9v5mb
Optional: false
QoS Class: BestEffort
Node-Selectors: < none>
Tolerations: node.kubernetes.io/not-ready:NoExecute for 300s
node.kubernetes.io/unreachable:NoExecute for 300s
Events:
Type Reason Age From Message
–– – – – –
Normal Scheduled 3m44s default-scheduler Successfully assigned default/liveness to node01
Normal Pulled 68s (x3 over 3m35s) kubelet, node01 Container image "alpine:3.5" already present on machine
Normal Created 68s (x3 over 3m35s) kubelet, node01 Created container healtcheck
Normal Started 68s (x3 over 3m34s) kubelet, node01 Started container healtcheck
Warning Unhealthy 23s (x9 over 3m3s) kubelet, node01 Liveness probe failed: cat: can't open '/tmp/healthy': No such file or directory
Normal Killing 23s (x3 over 2m53s) kubelet, node01 Container healtcheck failed liveness probe, will be restarted
Также мы видим и на событиях кластера, что когда cat /tmp/health терпит неудачу – контейнере пересоздаётся:
controlplane $ kubectl get events
controlplane $ kubectl get events | grep pod/liveness
13m Normal Scheduled pod/liveness Successfully assigned default/liveness to node01
13m Normal Pulling pod/liveness Pulling image "alpine:3.5"
13m Normal Pulled pod/liveness Successfully pulled image "alpine:3.5"
10m Normal Created pod/liveness Created container healtcheck
10m Normal Started pod/liveness Started container healtcheck
10m Warning Unhealthy pod/liveness Liveness probe failed: cat: can't open '/tmp/healthy': No such file or directory
10m Normal Killing pod/liveness Container healtcheck failed liveness probe, will be restarted
10m Normal Pulled pod/liveness Container image "alpine:3.5" already present on machine
8m32s Normal Scheduled pod/liveness Successfully assigned default/liveness to node01
4m41s Normal Pulled pod/liveness Container image "alpine:3.5" already present on machine
4m41s Normal Created pod/liveness Created container healtcheck
4m41s Normal Started pod/liveness Started container healtcheck
2m51s Warning Unhealthy pod/liveness Liveness probe failed: cat: can't open '/tmp/healthy': No such file or directory
5m11s Normal Killing pod/liveness Container healtcheck failed liveness probe, will be restarted
Рассмотрим RadyNess пробу. Доступность этой пробы свидетельствует, что приложение готово к принятию запросов и можно на него сервис может переключать трафик:
controlplane $ cat << EOF > readiness.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: readiness
spec:
replicas: 2
selector:
matchLabels:
app: readiness
template:
metadata:
Читать дальше