Если вы видите что-то необычное, просто сообщите мне. Skip to main content

Настройка безотказного 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-frequencyfrequence parameter.параметре. 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-periodperoid parameterпараметре 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, timeout(default isпо-умолчанию 5 mins)минут) andи updates theговорит API serverсерверу toубрать removeподы theустановив podдля byних settingсостояние terminate state.. Kube proxy 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)timeout) toдля 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)

    Change
  1. Изменяем theпараметр kublet configurationsво inвсех all nodes нодах(master andи workers) byчерез modifying theфайл /var/lib/kubelet/kubeadm-flags.env
  2. file

vi /var/lib/kubelet/kubeadm-flags.env

b)

    Add the
  1. Добавляем “--node-status-update-frequency=5s” optionпараметр atв theконец endследующей orлинии
  2. anywhere on this line.

KUBELET_KUBEADM_ARGS="--cgroup-driver=systemd --network-plugin=cni --pod-infra-container-image=k8s.gcr.io/pause:3.2 --node-status-update-frequency=5s"
  1. c)Сохранаяем Save your file.файл.

  2. d)Рестартим Restartkubelete.

    the
  3. kubelet.

systemctl restart kubelet

e)

    Repeat
  1. Повторяем stepsшаги (a)1-4 toна (d)всех inнодах.
  2. all nodes.

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)

    Change the
  1. Настроим kube-controller-manager inв masterмастер nodes.

    нодах.
vi /etc/kubernetes/manifests/kube-controller-manager.yaml

b)

    Add
  1. Добавим theследующие followingдва twoпараметра parameters to the command section inв kube-controller-manager.yaml file

    файл
- --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)

    Restart
  1. Перезапускаем theдокер
  2. docker

systemctl restart docker

d)

    Repeat
  1. Повторяем theшаги steps1-3 (a)на toвсех (c)мастер inнонах
  2. all master nodes.

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)

    Create
  1. Создаем aновый new file called файлkubeadm-apiserver-update.yaml inв /etc/kubernetes/manifests folderпапки inмастер masterноды
  2. nodes

cd /etc/kubernetes/manifests/
vi kubeadm-apiserver-update.yaml

b)

    Add
  1. Добавляем 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что kubernetesVersion matchesсовпадает withс yourвашей версией Kubernetes version

  1. c) Save the fileСохраняем

  2. d)Выполняем Runследующую theкоманду followingдля commandприменения toнастроек

    apply
  3. the changes

kubeadm init phase control-plane apiserver --config=kubeadm-apiserver-update.yaml

e)

    Verify
  1. Проверяем, thatчто theизменения changeкоторые hasбыли been applied by checking theв kube-apiserver.yaml forпримеенены для default-not-ready-toleration-seconds andи default-unreachable-toleration-seconds

cat /etc/kubernetes/manifests/kube-apiserver.yaml

f)

    Repeat
  1. Повторяем theшаги steps1-5 (a)для toвсех (e)мастер inнод.
  2. all master nodes.

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 EKS orили 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 your deployment 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.