Настройка безотказного K8s
WhetherНезависимо you’veот beenтого, usingпользуетесь Kubernetesли forвы ak8s while,недолго, orили you’reвы stillвсе testingеще itпроверяете out,его, it’sэто moreговорит, thanчто likelyвы thatуже you’veимели comeдело acrossс Kubernetesним eventsранее. before.Но Butчто whatже exactlyтакое areнастройка theyбезотказного andk8s is there a way to manage a Kubernetes Cluster State for high availability?кластера?
WhatЧто areтакое Kubernetesсобытия Events?k8s?
HaveПриходилось youли dealtрешать withпроблемы anyk8s debuggingпри issuesего whenиспользовании? usingЭто Kubernetes?может Itбыть canдовольно beсложно, incrediblyно frustrating,понимание butсоздания understandingсобытий eventи creationсостояний andможет stateсильно changeпомочь. canK8s reallyсобытия help.представляют Kubernetesиз eventsсебя provideто, insightчто intoслучается whatвнутри isкластера. happeningСобытие insideэто theтип cluster.ресурса Eventсоздаваемый isавтоматически, aкогда resourceпроисходит typeизменения inсостояния Kubernetesкластера. andКак itвы isможете automaticallyувидеть, createdсобытие dueочень toважный stateресуср changesпри whichрешении occurпроблем. inПрочитайте theпо cluster. So as you can see, events are a super valuable resource when dealing with debugging issues. Read on to learn more about the flow ofповоду state/event managementуправления andи relatedтаймеров timersпо andподробнее, howэто thisвам canпоможет helpв you.работе.
FlowПоток ofуправления State Managementсостоянием
IfЕсли youвы understandпонимаете theчто flowтакое ofпоток stateуправления management,состоянием, it’sлегко easyпонять toпочему understandнекоторые howсостояния someпадают, statesи fail,как andможно howэто weпредотвратить, canдавайте preventкапнем this, so let’s dig in:глубже:
The Kubelet inв eachкаждой clusterноде nodeкластера updates theобновляет API serverсервевр basedосновываясь onна theчастоте frequencyукаазнной configuredв in the node-status-update-
frequencyfrequenceparameter.параметре. TheЗначение defaultпо valueумолчанию is10 10s.секунд. ThenЗатем, fromпереодически, time to time, the master’s controller controller-manager checksпроверяет theсостояние nodeноды status from theчерез API Server.сервер. TheЧастота frequencyнастроенна isв configured in the node-monitor-
periodperoidparameterпараметре andи theпо defaultумолчанию valueсоставляет is5 5s.секунд.
IfЕсли the master's controller controller-manager noticesвидит, aчто nodeнода isне unhealthyздорова viaв theтечении node-monitor-grace-period
(по-умолчанию (Default40 is 40s)секунд), thenто itон marksпомечает theеё nodeкак asunhealty
unhealthyчерез via the control controller-manager.
ThenЗатем the controller controller-manager waitsожидаает for pod-eviction-
(timeout, timeoutdefault isпо-умолчанию 5 mins)минут) andи updates theговорит API serverсерверу toубрать removeподы theустановив podдля byних settingсостояние terminate
.
Kube proxy state.receivesполучает podуведомление terminationо notificationудалении fromноды theот API Server.сервера.
Kube proxy updatesудаляет theнедоступный endpoints by removing inaccessible pods.под.
WhatЧто happensслучается toс theкластером, clusterкогда whenнода nodesне failможет isэтого then,сделать, basedосновываясь onна defaultвременных timing.ограничениях. InВ thisпримере aboveвыше, exampleэто it will takeзаймент 5 minsминут andи 40 seconds секунд(node-monitor-grace-period
+ pod-eviction-
) timeout)timeouttoдля removeудаления inaccessibleнедоступного podsпода andи getвозвращения backв toрежим aготовности. steadyЭто state.не Thisпроблема isесли notdeployment
aимеет problemнесколько ifподов(значение replica
больше чем 1) и поды на здоровой ноде могут обрабатывать все запросы без проблем. Если deployment
hasимеет multipleодин podsпод (moreили thanздоровый 1под replica)не andможет theобрабатывать podsзапросы, on the healthy nodes can handle all transactions without any failures. If deployment has one pod or healthy pods cannot handle the transactions, thenтогда 5 minsминут andи 40 secondsсекунд isэто notне anприемлемое acceptableвремя downнедоступности time,сервиса, soпоэтому theлучшее bestрешение solutionнастроить isпеременные configuringв theкластере timingдля variablesускорения inреакции theна clusterпроблемы. toКак reactэто fasterсделать, forспросите failures.вы? HowДавайте doпройдемся you do that, you ask? Well, let’s go through it together:вместе:
Изменения конфигурации для улучшения безотказности кластера.
ConfigurationРешение changesточно toработает improve the high availability of the cluster
The following steps were tested inдля Kubernetes v1.18.3
1. ReduceСокращаем node-status-update-frequency
node-status-update-frequency
is- aпараметр kubeletkubelet, configurationон andимеет theзначение default value isпо-умолчанию 10 seconds.секунд.
StepsШаги toдля overrideтого, defaultчтотбы valueзаменить значение по-умолчанию
a)
- Изменяем
theпараметр kubletconfigurationsвоinвсехall nodesнодах(masterandи workers)byчерезmodifying theфайл /var/lib/kubelet/kubeadm-flags.env
vi /var/lib/kubelet/kubeadm-flags.env
b)
- Добавляем “--node-status-update-frequency=5s”
optionпараметрatвtheконецendследующейorлинии
KUBELET_KUBEADM_ARGS="--cgroup-driver=systemd --network-plugin=cni --pod-infra-container-image=k8s.gcr.io/pause:3.2 --node-status-update-frequency=5s"
-
c)СохранаяемSave your file.файл. -
d)РестартимRestartkubelete.the
systemctl restart kubelet
e)
- Повторяем
stepsшаги(a)1-4toна(d)всехinнодах.
2. ReduceСокращаем node-monitor-period andи node-monitor-grace-period
node-monitor-period
andи node-monitor-grace-period
areнастройки control controleler-manager configurationsb andи theirих defaultзначения values areпо-умолчанию 5 secondsсекунд andи 40 secondsсекунд respectively.соотвественно.
StepsШаги toдля overrideтого defaultчтобы valueих изменить
a)
- Настроим kube-controller-manager
inвmasterмастерnodes.нодах.
vi /etc/kubernetes/manifests/kube-controller-manager.yaml
b)
- Добавим
theследующиеfollowingдваtwoпараметраparameters to the command section inв kube-controller-manager.yamlfileфайл
- --node-monitor-period=3s
- --node-monitor-grace-period=20s
AfterПосле addingдобавления aboveдвух twoпараметров, parameters,конфигурация yourдолжна commandвыглядеть sectionпримерно should look like this:так:
spec:
containers:
- command:
- kube-controller-manager
. . . [There are more parameters here]
- --use-service-account-credentials=true
- --node-monitor-period=3s
- --node-monitor-grace-period=20s
image: k8s.gcr.io/kube-controller-manager:v1.18.4
imagePullPolicy: IfNotPresent
...
c)
- Перезапускаем
theдокер
systemctl restart docker
d)
- Повторяем
theшагиsteps1-3(a)наtoвсех(c)мастерinнонах
3. ReduceСокращаем pod-eviction-timeout
pod-eviction-timeout
canможно beсократить reducedустановив byдополнительный settingфлаг newдля flagsAPI on the API-Server.сервера.
StepsШаги toдля overrideизменения default valueпараметра
a)
- Создаем
aновыйnew file calledфайлkubeadm-apiserver-update.yamlinв /etc/kubernetes/manifestsfolderпапкиinмастерmasterноды
cd /etc/kubernetes/manifests/
vi kubeadm-apiserver-update.yaml
b)
- Добавляем
theследующееfollowingсодержаниеcontent to theв kubeadm-apiserver-update.yaml
apiVersion: kubeadm.k8s.io/v1beta2
kind: ClusterConfiguration
kubernetesVersion: v1.18.3
apiServer:
extraArgs:
enable-admission-plugins: DefaultTolerationSeconds
default-not-ready-toleration-seconds: "20"
default-unreachable-toleration-seconds: "20"
MakeУбеждаемся,sure the aboveчто kubernetesVersionmatchesсовпадаетwithсyourвашей версией Kubernetesversion
-
c) Save the fileСохраняем -
d)ВыполняемRunследующуюtheкомандуfollowingдляcommandпримененияtoнастроекapply
kubeadm init phase control-plane apiserver --config=kubeadm-apiserver-update.yaml
e)
- Проверяем,
thatчтоtheизмененияchangeкоторыеhasбылиbeen applied by checking theв kube-apiserver.yamlforпримеенены дляdefault-not-ready-toleration-seconds
andиdefault-unreachable-toleration-seconds
cat /etc/kubernetes/manifests/kube-apiserver.yaml
f)
- Повторяем
theшагиsteps1-5(a)дляtoвсех(e)мастерinнод.
TheШаги aboveвыше stepsменяеют change the pod-eviction-timeout
acrossдля theвсего cluster,кластера, butно thereесть isеще anotherодин wayспособ toизменить changepod-eviction-timeout
. theЭто podможно evictionсделать timeout.добавив Youtolerations
canво doвсе thisdeployment
, byчто addingпозволит tolerationsприменить toконфиг eachтолько deployment,на soопределенныйdeployment
. thisДля willтакой affectнастройки onlypod-eviction-timeout
, theдобавьте relevantследующие deployment.строки Toв configureописание deployment-based pod eviction time, add the following tolerations to each deployment:deployment
:
tolerations:
- key: "node.kubernetes.io/unreachable"
operator: "Exists"
effect: "NoExecute"
tolerationSeconds: 20
- key: "node.kubernetes.io/not-ready"
operator: "Exists"
effect: "NoExecute"
tolerationSeconds: 20
IfЕслиyouвыareработаетеworkingсwithуправляемымaсервисомmanagedKubernetes,Kubernetesтакимservice, such asкак Amazon EKSorили AKS,youтоwillуnotвасbeнеableбудетtoвозможностиupdateобновитьpodpod-eviction-timeout
evictionвtimeoutкластере.acrossНеобходимоtheиспользоватьcluster.tolerations
Youдляwill need to add the tolerations to yourdeployment
.in each situation.
AndВот that'sи it,всё, you'veвы successfullyуспешно managedобработали Kubernetesсобытия events. Well done! hackajob has a wealth of roles where skills like this will come in handy. Interested? Find the right opportunities here.K8s.
Like what you've read or want more like this? Let us know! Email us here or DM us: Twitter, LinkedIn, Facebook, we'd love to hear from you.