- Added comprehensive course structure with 11 modules - Included theoretical content, practical examples, and tasks - Multi-language code examples (Java, Rust, Node.js, Python) - Detailed analysis of architectural approaches and trade-offs - Complete caching strategies documentation - Architecture examples from real-world systems (Twitter, Netflix, Uber) - Structured navigation and learning path - Ready for educational use
12 KiB
12 KiB
Kubernetes
Навигация
Что такое Kubernetes
Kubernetes (K8s) — система оркестрации контейнеров для автоматизации развертывания, масштабирования и управления приложениями.
Архитектура Kubernetes
┌─────────────────────────────────────────────────────────┐
│ Control Plane │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────────┐ │
│ │ API Server │ │ Scheduler │ │ Controller Mgr │ │
│ └─────────────┘ └─────────────┘ └─────────────────┘ │
│ ┌─────────────┐ ┌─────────────┐ │
│ │ etcd │ │ Cloud Ctlr │ │
│ └─────────────┘ └─────────────┘ │
└─────────────────────────────────────────────────────────┘
│
┌─────────────────────────────────────────────────────────┐
│ Worker Nodes │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────────┐ │
│ │ kubelet │ │ kube-proxy │ │ Container Runtime│ │
│ └─────────────┘ └─────────────┘ └─────────────────┘ │
└─────────────────────────────────────────────────────────┘
Основные компоненты
Плоскость управления:
- API Server — центральный компонент управления
- etcd — хранилище конфигурации
- Scheduler — планировщик подов
- Controller Manager — контроллеры системы
Рабочие узлы:
- kubelet — агент на каждом узле
- kube-proxy — сетевой прокси
- Container Runtime — Docker, containerd, CRI-O
Объекты Kubernetes
1. Pod
Pod — наименьшая единица развертывания в Kubernetes.
apiVersion: v1
kind: Pod
metadata:
name: user-service-pod
labels:
app: user-service
version: v1.0.0
annotations:
prometheus.io/scrape: "true"
prometheus.io/port: "8080"
prometheus.io/path: "/actuator/prometheus"
spec:
containers:
- name: user-service
image: user-service:latest
ports:
- containerPort: 8080
name: http
protocol: TCP
env:
- name: SPRING_PROFILES_ACTIVE
value: "kubernetes"
- name: SPRING_DATASOURCE_URL
valueFrom:
secretKeyRef:
name: user-db-secret
key: url
resources:
requests:
memory: "256Mi"
cpu: "250m"
limits:
memory: "512Mi"
cpu: "500m"
livenessProbe:
httpGet:
path: /actuator/health/liveness
port: 8080
initialDelaySeconds: 30
periodSeconds: 10
timeoutSeconds: 5
failureThreshold: 3
readinessProbe:
httpGet:
path: /actuator/health/readiness
port: 8080
initialDelaySeconds: 5
periodSeconds: 5
timeoutSeconds: 3
failureThreshold: 3
volumeMounts:
- name: config-volume
mountPath: /app/config
readOnly: true
volumes:
- name: config-volume
configMap:
name: user-service-config
restartPolicy: Always
terminationGracePeriodSeconds: 30
2. Deployment
Deployment — управляет репликами подов.
apiVersion: apps/v1
kind: Deployment
metadata:
name: user-service-deployment
labels:
app: user-service
version: v1.0.0
spec:
replicas: 3
strategy:
type: RollingUpdate
rollingUpdate:
maxUnavailable: 1
maxSurge: 1
selector:
matchLabels:
app: user-service
template:
metadata:
labels:
app: user-service
version: v1.0.0
annotations:
prometheus.io/scrape: "true"
prometheus.io/port: "8080"
prometheus.io/path: "/actuator/prometheus"
spec:
containers:
- name: user-service
image: user-service:v1.0.0
imagePullPolicy: IfNotPresent
ports:
- containerPort: 8080
name: http
protocol: TCP
env:
- name: SPRING_PROFILES_ACTIVE
value: "kubernetes"
- name: POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: POD_NAMESPACE
valueFrom:
fieldRef:
fieldPath: metadata.namespace
resources:
requests:
memory: "256Mi"
cpu: "250m"
limits:
memory: "512Mi"
cpu: "500m"
livenessProbe:
httpGet:
path: /actuator/health/liveness
port: 8080
initialDelaySeconds: 30
periodSeconds: 10
timeoutSeconds: 5
failureThreshold: 3
readinessProbe:
httpGet:
path: /actuator/health/readiness
port: 8080
initialDelaySeconds: 5
periodSeconds: 5
timeoutSeconds: 3
failureThreshold: 3
volumeMounts:
- name: config-volume
mountPath: /app/config
readOnly: true
- name: logs-volume
mountPath: /app/logs
volumes:
- name: config-volume
configMap:
name: user-service-config
- name: logs-volume
emptyDir: {}
restartPolicy: Always
terminationGracePeriodSeconds: 30
dnsPolicy: ClusterFirst
securityContext:
runAsNonRoot: true
runAsUser: 1000
fsGroup: 2000
3. Service
Service — обеспечивает сетевой доступ к подам.
apiVersion: v1
kind: Service
metadata:
name: user-service
labels:
app: user-service
annotations:
prometheus.io/scrape: "true"
prometheus.io/port: "8080"
prometheus.io/path: "/actuator/prometheus"
spec:
selector:
app: user-service
ports:
- name: http
protocol: TCP
port: 80
targetPort: 8080
- name: metrics
protocol: TCP
port: 9090
targetPort: 9090
type: ClusterIP
sessionAffinity: None
4. Ingress
Ingress — управляет внешним доступом к сервисам.
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: microservices-ingress
annotations:
kubernetes.io/ingress.class: "nginx"
nginx.ingress.kubernetes.io/rewrite-target: /
nginx.ingress.kubernetes.io/ssl-redirect: "true"
nginx.ingress.kubernetes.io/force-ssl-redirect: "true"
cert-manager.io/cluster-issuer: "letsencrypt-prod"
spec:
tls:
- hosts:
- api.example.com
secretName: api-tls-secret
rules:
- host: api.example.com
http:
paths:
- path: /api/users
pathType: Prefix
backend:
service:
name: user-service
port:
number: 80
- path: /api/orders
pathType: Prefix
backend:
service:
name: order-service
port:
number: 80
- path: /api/payments
pathType: Prefix
backend:
service:
name: payment-service
port:
number: 80
5. ConfigMap
ConfigMap — хранит конфигурационные данные.
apiVersion: v1
kind: ConfigMap
metadata:
name: user-service-config
labels:
app: user-service
data:
application.yml: |
server:
port: 8080
spring:
application:
name: user-service
datasource:
driver-class-name: org.postgresql.Driver
hikari:
maximum-pool-size: 10
minimum-idle: 5
connection-timeout: 20000
idle-timeout: 300000
max-lifetime: 1200000
jpa:
hibernate:
ddl-auto: validate
show-sql: false
properties:
hibernate:
dialect: org.hibernate.dialect.PostgreSQLDialect
format_sql: true
rabbitmq:
host: rabbitmq-service
port: 5672
username: admin
password: admin
management:
endpoints:
web:
exposure:
include: health,info,prometheus,metrics
endpoint:
health:
show-details: always
metrics:
export:
prometheus:
enabled: true
6. Secret
Secret — хранит чувствительные данные.
apiVersion: v1
kind: Secret
metadata:
name: user-db-secret
labels:
app: user-service
type: Opaque
data:
url: cG9zdGdyZXNxbDovL3VzZXItZGItc2VydmljZToyNTQzMi91c2VyZGI= # base64 encoded
username: dXNlcg== # base64 encoded
password: cGFzc3dvcmQ= # base64 encoded
7. HorizontalPodAutoscaler
HPA — автоматическое масштабирование подов.
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: user-service-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: user-service-deployment
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: 80
behavior:
scaleDown:
stabilizationWindowSeconds: 300
policies:
- type: Percent
value: 10
periodSeconds: 60
scaleUp:
stabilizationWindowSeconds: 60
policies:
- type: Percent
value: 50
periodSeconds: 60
Команды Kubernetes
Основные команды:
# Применение манифеста
kubectl apply -f deployment.yaml
# Просмотр подов
kubectl get pods
# Просмотр сервисов
kubectl get services
# Просмотр деплойментов
kubectl get deployments
# Описание ресурса
kubectl describe pod <pod-name>
# Логи пода
kubectl logs <pod-name>
# Подключение к поду
kubectl exec -it <pod-name> -- /bin/bash
# Масштабирование деплоймента
kubectl scale deployment my-deployment --replicas=5
Сетевая модель Kubernetes
1. Cluster Networking
- Каждый под имеет уникальный IP
- Поды могут общаться друг с другом
- Сервисы обеспечивают стабильные IP
2. Service Types
- ClusterIP — внутренний IP кластера
- NodePort — доступ через порт узла
- LoadBalancer — внешний балансировщик нагрузки
- ExternalName — внешний DNS
Хранилище в Kubernetes
1. Volumes
apiVersion: v1
kind: Pod
spec:
containers:
- name: my-container
image: nginx
volumeMounts:
- name: my-volume
mountPath: /data
volumes:
- name: my-volume
persistentVolumeClaim:
claimName: my-pvc
2. PersistentVolume
apiVersion: v1
kind: PersistentVolume
metadata:
name: my-pv
spec:
capacity:
storage: 10Gi
accessModes:
- ReadWriteOnce
persistentVolumeReclaimPolicy: Retain
storageClassName: fast-ssd
3. PersistentVolumeClaim
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: my-pvc
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 10Gi
storageClassName: fast-ssd