Duration: 4 hours

Level: Intermediate

Environment: Simulated On-Premises Kubernetes

Role: DevOps Engineer / Site Reliability Engineer

Tools: Docker, Kind, Kubernetes, Linux, NGINX, curl

1. Production Incident Scenario

Вы работаете DevOps/SRE Engineer в компании, которая поддерживает production application, запущенное в Kubernetes Cluster.

Архитектура компании:

  • 1 Control Plane
  • 3 Worker Nodes
  • 3 Application Replicas
  • Kubernetes Service
  • Container Runtime — containerd
  • Kubernetes Node Agent — Kubelet

Приложение должно оставаться доступным для клиентов даже при отказе одного Worker Node.

В течение рабочего дня monitoring system обнаруживает проблему и отправляет alert команде Operations.

Incident Ticket — INC-001

Field Description
Incident ID INC-001
Environment Production Simulation
Alert Kubernetes Worker Node NotReady
Affected Component Worker Node
Customer Impact Unknown
Root Cause Unknown
Assigned Team DevOps / SRE
Status Open
Priority Pending impact assessment

Incident Description:

One of the three Kubernetes worker nodes stopped responding to the Kubernetes Control Plane. The monitoring system generated a NodeNotReady alert. The root cause and customer impact are currently unknown.

Your responsibility:

Investigate the incident, identify the affected components, determine customer impact, collect evidence, identify the root cause, restore the system and verify recovery.

2. DevOps/SRE Engineer Responsibilities

В реальной компании DevOps/SRE Engineer отвечает не только за deployment приложения.

Responsibility Description
Deployment Доставка приложения в нужное окружение
Availability Обеспечение доступности приложения
Reliability Обеспечение стабильной работы системы
Security Защита инфраструктуры и коммуникации
Observability Понимание состояния системы
Troubleshooting Поиск и устранение проблем
Incident Response Реагирование на инциденты
Automation Автоматизация повторяющихся процессов
Change Management Безопасное выполнение изменений
Prevention Предотвращение повторных инцидентов

Сегодня основное внимание уделяется Troubleshooting, Availability, Reliability и Incident Response.

3. What Is Troubleshooting?

Troubleshooting is a systematic process of identifying, investigating, isolating and resolving problems based on evidence.

Troubleshooting — это систематический процесс выявления, расследования, локализации и устранения проблемы на основании доказательств.

Troubleshooting не означает выполнение случайных команд.

Каждая команда должна иметь конкретную цель и отвечать на конкретный вопрос.

Troubleshooting Workflow

  1. Understand the system — понять архитектуру.
  2. Identify the symptoms — определить симптомы.
  3. Assess customer impact — определить влияние на клиентов.
  4. Collect evidence — собрать доказательства.
  5. Form a hypothesis — выдвинуть предположение.
  6. Test the hypothesis — проверить предположение.
  7. Isolate the problem — локализовать проблему.
  8. Mitigate and resolve — уменьшить влияние и устранить проблему.
  9. Verify recovery — проверить восстановление.
  10. Prevent recurrence — предотвратить повторение.

Important: Do not restart, delete or modify production resources without understanding the problem and potential impact.

4. Laboratory Architecture

 Kubernetes Control Plane ┌────────────────────────┐ │ API Server │ │ Scheduler │ │ Controller Manager │ │ etcd │ └───────────┬────────────┘ │ Node Management / Heartbeat │ ┌─────────────────┼─────────────────┐ │ │ │ ┌─────▼──────┐ ┌─────▼──────┐ ┌─────▼──────┐ │ Worker 1 │ │ Worker 2 │ │ Worker 3 │ │ │ │ │ │ │ │ Kubelet │ │ Kubelet │ │ Kubelet │ │ containerd │ │ containerd │ │ containerd │ │ NGINX Pod │ │ NGINX Pod │ │ NGINX Pod │ └────────────┘ └────────────┘ └────────────┘ 

Application Communication

Client │ ▼ NodePort Service │ ├──────► Application Pod 1 ├──────► Application Pod 2 └──────► Application Pod 3 

Control Plane управляет Kubernetes Cluster, но пользовательский HTTP traffic не должен проходить через API Server для обычной коммуникации с приложением.

Why Kind?

Kind stands for Kubernetes in Docker.

Kind позволяет создавать Kubernetes Clusters, используя Docker containers в качестве Kubernetes Nodes.

В нашей лабораторной работе каждый Node будет отдельным Docker container, внутри которого работают Linux, kubelet и containerd.

Это симуляция on-premises infrastructure. Все Nodes физически находятся на одном компьютере, поэтому это не настоящая production High Availability architecture.

PHASE 1 — Environment Preparation

Step 1. Verify Required Tools

Выполните:

docker version 
kind version 
kubectl version --client 
docker info 

Why are we doing this?

Перед созданием infrastructure инженер должен убедиться, что необходимые инструменты установлены и доступны.

Мы проверяем:

  • Docker Engine
  • Kind
  • Kubernetes CLI
  • Docker connectivity
  • Available computing resources

Если Docker не запущен, Kind не сможет создать Kubernetes Cluster.

Step 2. Check Available Resources

docker info --format 'CPUs={{.NCPU}} MemoryBytes={{.MemTotal}}' 
docker stats --no-stream 
kind get clusters 
docker ps 

Why are we doing this?

Создание Kubernetes Cluster требует CPU, Memory и Disk Space.

Если на компьютере уже существуют другие Kubernetes Clusters, Docker containers или applications, может возникнуть resource pressure.

Это называется Capacity Planning.

Не удаляйте существующие clusters без разрешения преподавателя.

Step 3. Verify Kubernetes Context

kubectl config current-context 
kubectl config get-contexts 

What is Kubernetes Context?

Context определяет, с каким Kubernetes Cluster, пользователем и namespace работает kubectl.

Один инженер может иметь доступ к нескольким environments:

Development Staging Production Local Kubernetes 

Why is this important?

Если инженер случайно выполнит destructive command в production вместо local environment, это может привести к production outage.

Во время всей лабораторной работы мы будем явно указывать:

--context kind-node-incident 

Это уменьшает риск выполнения команд в неправильном Kubernetes Cluster.

PHASE 2 — Infrastructure Provisioning

Step 4. Create Working Directory

mkdir -p ~/jumptotech-node-incident 
cd ~/jumptotech-node-incident 
mkdir -p evidence 
pwd 

Why are we doing this?

Мы создаём отдельную рабочую директорию для:

  • Infrastructure configuration
  • Kubernetes manifests
  • Incident evidence
  • Troubleshooting results
  • Incident documentation

В реальной компании конфигурации обычно хранятся в Git repository, а результаты расследования — в incident management system.

Step 5. Create Kubernetes Cluster Configuration

Создайте файл:

cat > kind-config.yaml <<'EOF' kind: Cluster apiVersion: kind.x-k8s.io/v1alpha4 nodes: - role: control-plane - role: worker - role: worker - role: worker EOF 

Проверьте содержимое:

cat kind-config.yaml 

Configuration Explanation

Field Meaning
kind Тип конфигурационного объекта
apiVersion Версия Kind configuration API
nodes Список Kubernetes Nodes
control-plane Node, управляющий кластером
worker Node для запуска workloads

Why are we doing this?

Мы используем declarative configuration.

Вместо ручного создания каждого сервера мы описываем desired state нашей infrastructure.

Step 6. Provision Kubernetes Cluster

kind create cluster \ --name node-incident \ --config kind-config.yaml \ --wait 5m 

Expected Output:

Creating cluster "node-incident" ... ✓ Ensuring node image ✓ Preparing nodes ✓ Writing configuration ✓ Starting control-plane ✓ Installing CNI ✓ Installing StorageClass ✓ Joining worker nodes Set kubectl context to "kind-node-incident" 

Фактический вывод может отличаться в зависимости от версии Kind.

What happens behind the scenes?

Kind выполняет следующие действия:

  1. Подготавливает Kubernetes Node image.
  2. Создаёт Docker containers.
  3. Инициализирует Kubernetes Control Plane.
  4. Настраивает networking.
  5. Подключает Worker Nodes к Control Plane.
  6. Настраивает kubeconfig.

Step 7. Verify Kubernetes Nodes

kubectl --context kind-node-incident get nodes -o wide 

Expected Output:

NAME STATUS ROLES node-incident-control-plane Ready control-plane node-incident-worker Ready <none> node-incident-worker2 Ready <none> node-incident-worker3 Ready <none> 

What should we understand?

У нас четыре Kubernetes Nodes:

  • 1 Control Plane
  • 3 Worker Nodes

Worker Nodes могут отображать ROLES как <none>. Это не означает, что Node неисправен.

Interview Question

Are Kubernetes Nodes namespaced resources?

No. Nodes are cluster-scoped resources.

Поэтому команда:

kubectl get nodes 

не требует указания namespace.

Pods, Deployments и Services, в отличие от Nodes, являются namespaced resources.

Step 8. Verify Underlying Infrastructure

docker ps --filter name=node-incident 

Expected Result:

node-incident-control-plane node-incident-worker node-incident-worker2 node-incident-worker3 

Why are we doing this?

Kubernetes показывает логическое состояние Nodes.

Docker показывает состояние инфраструктуры, на которой в нашей лабораторной работе работают Kubernetes Nodes.

В реальном production это могли бы быть:

  • Physical Servers
  • VMware Virtual Machines
  • AWS EC2 Instances
  • Azure Virtual Machines
  • Google Compute Engine Instances

Инженер должен уметь расследовать проблему не только на Kubernetes level, но и на infrastructure level.

PHASE 3 — Understand Worker Node Components

Step 9. Access Worker Node

docker exec -it node-incident-worker3 bash 

Внутри Worker Node выполните:

hostname 
whoami 
uname -a 
cat /etc/os-release 

Why are we doing this?

Мы подключаемся непосредственно к операционной системе Worker Node.

В реальном on-premises environment для этого может использоваться SSH или management console.

В Kind используется docker exec.

Step 10. Check Kubelet

Внутри Worker Node:

systemctl status kubelet --no-pager 
systemctl is-active kubelet 

Expected Output:

active 

What is Kubelet?

Kubelet is a Kubernetes agent running on each node.

Kubelet выполняет следующие функции:

  • Communicates with Kubernetes API Server.
  • Receives assigned Pod specifications.
  • Manages Pod lifecycle through the container runtime.
  • Executes health probes.
  • Reports Node and Pod status.
  • Renews Node Lease.
API Server │ ▼ Kubelet │ ▼ Container Runtime │ ▼ Application Containers 

Why are we checking kubelet?

Если kubelet перестаёт работать, Control Plane может потерять актуальную информацию о состоянии Node.

Step 11. Check Container Runtime

systemctl status containerd --no-pager 
systemctl is-active containerd 

Expected Output:

active 

Дополнительно:

crictl ps 

What is containerd?

containerd — это container runtime, который управляет жизненным циклом containers.

Kubelet взаимодействует с container runtime через CRI — Container Runtime Interface.

Interview Question:

What is the difference between kubelet and containerd?

Answer:

Kubelet manages Kubernetes workloads on a node. Containerd manages the actual containers.

Это разные компоненты. Один компонент может работать, когда другой недоступен.

Step 12. Check Linux System Health

free -h 
df -h 
uptime 
ip addr 
ip route 
ps aux | grep '[k]ubelet' 
Command Purpose
free -h Проверка памяти
df -h Проверка дискового пространства
uptime Проверка uptime и load average
ip addr Проверка network interfaces
ip route Проверка routing table
ps aux Проверка процессов

Why are we doing this?

Kubernetes работает поверх операционной системы.

Если существуют проблемы на Linux level, они могут влиять на Kubernetes и application workloads.

В Kind некоторые показатели отражают общие ресурсы Docker VM, а не отдельного физического сервера.

Step 13. Check Kubelet Logs

journalctl -u kubelet -n 30 --no-pager 

What is journalctl?

journalctl позволяет просматривать systemd journal, включая logs системных сервисов.

Why are logs important?

Logs помогают определить:

  • Когда возникла проблема.
  • Какие ошибки произошли.
  • Какой компонент сообщил об ошибке.
  • Были ли проблемы с network, certificates или container runtime.

Выйдите из Worker Node:

exit 

PHASE 4 — Application Deployment

Step 14. Create Production Namespace

kubectl --context kind-node-incident \ create namespace production 
kubectl --context kind-node-incident get namespaces 

Why are we doing this?

Namespaces позволяют логически разделять Kubernetes resources.

В этой лабораторной работе namespace production симулирует production environment.

Это не настоящий production cluster.

Step 15. Create Application Deployment

Создайте файл deployment.yaml:

cat > deployment.yaml <<'EOF' apiVersion: apps/v1 kind: Deployment metadata: name: web-app namespace: production spec: replicas: 3 selector: matchLabels: app: web-app template: metadata: labels: app: web-app spec: affinity: podAntiAffinity: requiredDuringSchedulingIgnoredDuringExecution: - labelSelector: matchLabels: app: web-app topologyKey: kubernetes.io/hostname containers: - name: nginx image: nginx:alpine ports: - containerPort: 80 resources: requests: cpu: 50m memory: 64Mi limits: cpu: 200m memory: 128Mi readinessProbe: httpGet: path: / port: 80 initialDelaySeconds: 3 periodSeconds: 5 livenessProbe: httpGet: path: / port: 80 initialDelaySeconds: 5 periodSeconds: 10 EOF 

Deployment Configuration Explanation

Replicas

replicas: 3 

Мы хотим поддерживать три экземпляра приложения.

Resource Requests

requests: cpu: 50m memory: 64Mi 

Requests используются Scheduler при принятии решения о размещении Pod.

Resource Limits

limits: cpu: 200m memory: 128Mi 

Limits ограничивают использование ресурсов container.

CPU limit может приводить к CPU throttling. Превышение memory limit может приводить к OOM termination.

Readiness Probe

Readiness Probe определяет, готов ли Pod принимать traffic.

Liveness Probe

Liveness Probe проверяет, необходимо ли перезапустить container из-за нарушения его работоспособности.

Pod Anti-Affinity

podAntiAffinity: requiredDuringSchedulingIgnoredDuringExecution: 

Эта конфигурация запрещает Scheduler размещать несколько соответствующих Pods приложения на одном Node.

topologyKey: kubernetes.io/hostname 

Распределение выполняется по hostname Kubernetes Nodes.

Why do we need Pod Anti-Affinity?

Without distribution:

Worker 1: Pod 1, Pod 2, Pod 3 Worker 2: Empty Worker 3: Empty 

Если Worker 1 перестанет работать, все три реплики будут затронуты.

With distribution:

Worker 1: Pod 1 Worker 2: Pod 2 Worker 3: Pod 3 

Если Worker 3 перестанет работать, две другие реплики могут продолжить обслуживать клиентов.

Important: Having multiple replicas does not automatically guarantee High Availability.

Step 16. Deploy Application

kubectl --context kind-node-incident \ apply -f deployment.yaml 
kubectl --context kind-node-incident \ rollout status deployment/web-app \ -n production --timeout=180s 
kubectl --context kind-node-incident \ get deployments -n production 
kubectl --context kind-node-incident \ get pods -n production -o wide 

Expected Output:

NAME READY STATUS NODE web-app-xxx-a 1/1 Running node-incident-worker web-app-xxx-b 1/1 Running node-incident-worker2 web-app-xxx-c 1/1 Running node-incident-worker3 

Pod names will be different.

Verification Requirement:

Убедитесь, что все три Pods:

  • Running
  • Ready
  • Distributed across three different Worker Nodes

Не переходите к следующему шагу, пока application deployment не завершён успешно.

Step 17. Create Kubernetes Service

cat > service.yaml <<'EOF' apiVersion: v1 kind: Service metadata: name: web-service namespace: production spec: type: NodePort selector: app: web-app ports: - port: 80 targetPort: 80 nodePort: 30080 EOF 
kubectl --context kind-node-incident \ apply -f service.yaml 
kubectl --context kind-node-incident \ get services -n production 

What is Kubernetes Service?

Service предоставляет стабильную сетевую точку доступа к группе Pods.

Pods могут пересоздаваться, получать новые IP addresses и перемещаться между Nodes.

Service позволяет клиенту обращаться к приложению без необходимости знать IP каждого Pod.

Field Purpose
port: 80 Service port
targetPort: 80 Application container port
nodePort: 30080 Port exposed on Kubernetes Nodes
selector Определяет соответствующие Pods

Step 18. Verify Service Endpoints

kubectl --context kind-node-incident \ get endpointslices -n production 
kubectl --context kind-node-incident \ get endpointslices -n production \ -l kubernetes.io/service-name=web-service \ -o yaml 

Найдите:

conditions: ready: true 

Why are we doing this?

Наличие Service не гарантирует, что у него существуют доступные application endpoints.

EndpointSlices позволяют проверить, какие Pods связаны с Service и какие из них готовы принимать traffic.

Step 19. Verify HTTP Communication

Получите IP первого Worker Node:

HEALTHY_IP=$(docker inspect \ -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' \ node-incident-worker) 
echo "$HEALTHY_IP" 

Отправьте HTTP request из Control Plane container:

docker exec node-incident-control-plane \ curl -i --max-time 5 \ "http://${HEALTHY_IP}:30080/" 

Expected Output:

HTTP/1.1 200 OK Server: nginx Content-Type: text/html 

Why are we doing this?

Running Pods не являются достаточным доказательством того, что application доступен.

Мы должны проверить реальную коммуникацию между клиентом и приложением.

В этом тесте Control Plane container используется только как test client. Пользовательский запрос не