Развёртывание Kong в Kubernetes: Ingress, KongPlugin, KongConsumer
Kong Ingress Controller автоматизирует конфигурацию Kong на основе Kubernetes ресурсов, обеспечивая декларативное управление API Gateway.
Проблема: Ручная конфигурация Kong через Admin API не масштабируется в Kubernetes среде.
Решение: Kong Ingress Controller — Kubernetes Controller, который автоматически конфигурирует Kong при изменении ресурсов.
┌─────────────────────────────────────────────────────────────┐
│ Kong Ingress Controller Architecture │
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│ Kubernetes Cluster │
│ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ Ingress │ │ Service │ │ Secret │ │
│ │ Resource │ │ Resource │ │ Resource │ │
│ └────┬─────┘ └────┬─────┘ └────┬─────┘ │
│ │ │ │ │
│ └─────────────┼─────────────┘ │
│ │ │
│ ┌──────▼──────┐ │
│ │ Kong │ │
│ │ Ingress │ │
│ │ Controller│ │
│ └──────┬──────┘ │
│ │ │
│ │ Admin API │
│ ▼ │
│ ┌──────────────┐ │
│ │ Kong Gateway│ │
│ │ (Data Plane)│ │
│ └──────────────┘ │
└─────────────────────────────────────────────────────────────┘
Компоненты:
Проблема: Нужно развернуть Kong в Kubernetes с автоматическим управлением конфигурацией.
Решение: Helm chart для Kong Ingress Controller.
# Добавляем репозиторий
helm repo add kong https://charts.konghq.com
helm repo update
# Создаём namespace
kubectl create namespace kong
# Установка Kong Ingress Controller
helm install kong kong/kong \
--namespace kong \
--set ingressController.enabled=true \
--set ingressController.ingressClass=kong \
--set proxy.http.enabled=true \
--set proxy.http.servicePort=8000 \
--set proxy.type=LoadBalancer \
--set admin.enabled=true \
--set admin.type=ClusterIP# Проверка подов
kubectl get pods -n kong
# NAME READY STATUS
# kong-kong-xxxxxxxxx-xxxxx 2/2 Running
# kong-kong-ingress-controller-xxxxxxxxx-xxxxx 1/1 Running
# Проверка сервиса
kubectl get svc -n kong
# NAME TYPE CLUSTER-IP EXTERNAL-IP
# kong-proxy LoadBalancer 10.0.0.100 203.0.113.10
# kong-admin ClusterIP 10.0.0.101 <none>Проблема: Не хочется зависеть от PostgreSQL для конфигурации.
Решение: DB-less режим с конфигурацией через CRD.
helm install kong kong/kong \
--namespace kong \
--set ingressController.enabled=true \
--set ingressController.ingressClass=kong \
--set env.database=off \
--set proxy.http.enabled=true \
--set proxy.type=LoadBalancerПроблема: Нужно направить внешний трафик на сервис в Kubernetes.
Решение: Kubernetes Ingress ресурс с аннотацией Kong.
# users-service.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: users-service
spec:
replicas: 2
selector:
matchLabels:
app: users-service
template:
metadata:
labels:
app: users-service
spec:
containers:
- name: users-service
image: users-service:latest
ports:
- containerPort: 8080
---
apiVersion: v1
kind: Service
metadata:
name: users-service
labels:
app: users-service
spec:
ports:
- port: 80
targetPort: 8080
protocol: TCP
selector:
app: users-servicekubectl apply -f users-service.yaml# users-ingress.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: users-ingress
annotations:
kubernetes.io/ingress.class: kong
spec:
rules:
- host: api.example.com
http:
paths:
- path: /users
pathType: Prefix
backend:
service:
name: users-service
port:
number: 80kubectl apply -f users-ingress.yamlРезультат:
http://203.0.113.10/users → users-service:80http://203.0.113.10/users/123 → users-service:80# Получение внешнего IP
export KONG_PROXY_IP=$(kubectl get svc -n kong kong-proxy -o jsonpath='{.status.loadBalancer.ingress[0].ip}')
# Тестирование
curl -H "Host: api.example.com" http://$KONG_PROXY_IP/usersПроблема: Нужно применить плагины Kong (rate limiting, auth) к сервисам.
Решение: KongPlugin CRD и аннотации.
# rate-limit-plugin.yaml
apiVersion: configuration.konghq.com/v1
kind: KongPlugin
metadata:
name: rate-limiting
namespace: default
config:
minute: 100
policy: local
plugin: rate-limitingkubectl apply -f rate-limit-plugin.yamlСпособ 1: Аннотация на Service
apiVersion: v1
kind: Service
metadata:
name: users-service
annotations:
konghq.com/plugins: rate-limiting
spec:
ports:
- port: 80
targetPort: 8080
selector:
app: users-serviceСпособ 2: Аннотация на Ingress
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: users-ingress
annotations:
kubernetes.io/ingress.class: kong
konghq.com/plugins: rate-limiting
spec:
rules:
- host: api.example.com
http:
paths:
- path: /users
pathType: Prefix
backend:
service:
name: users-service
port:
number: 80# jwt-plugin.yaml
apiVersion: configuration.konghq.com/v1
kind: KongPlugin
metadata:
name: jwt-auth
namespace: default
config:
key_claim_name: iss
claims_to_verify:
- exp
plugin: jwtkubectl apply -f jwt-plugin.yamlapiVersion: v1
kind: Service
metadata:
name: users-service
annotations:
konghq.com/plugins: rate-limiting,jwt-auth,cors
spec:
# ...Проблема: Нужно определить потребителей API с credentials и индивидуальными лимитами.
Решение: KongConsumer CRD.
# consumer.yaml
apiVersion: configuration.konghq.com/v1
kind: KongConsumer
metadata:
name: mobile-app
namespace: default
username: mobile-app
credentials:
- mobile-app-jwt
- mobile-app-key-auth# jwt-credentials.yaml
apiVersion: v1
kind: Secret
metadata:
name: mobile-app-jwt
namespace: default
type: Opaque
stringData:
key: mobile-app-key
algorithm: HS256
secret: my-super-secret-key# key-auth-credentials.yaml
apiVersion: v1
kind: Secret
metadata:
name: mobile-app-key-auth
namespace: default
type: Opaque
stringData:
key: secret-key-123kubectl apply -f jwt-credentials.yaml
kubectl apply -f key-auth-credentials.yaml
kubectl apply -f consumer.yaml# premium-rate-limit.yaml
apiVersion: configuration.konghq.com/v1
kind: KongPlugin
metadata:
name: premium-rate-limiting
namespace: default
config:
hour: 10000
policy: redis
plugin: rate-limiting
consumerRef: premium-userПроблема: Нужно настроить параметры upstream (алгоритм балансировки, health checks).
Решение: KongIngress CRD (устаревает в пользу KongUpstream).
# custom-upstream.yaml
apiVersion: configuration.konghq.com/v1
kind: KongIngress
metadata:
name: custom-upstream
namespace: default
proxy:
connect_timeout: 5000
read_timeout: 60000
write_timeout: 60000
retries: 3
upstream:
algorithm: round-robin
slots: 10000
healthchecks:
active:
healthy:
interval: 5
successes: 2
unhealthy:
interval: 5
tcp_failures: 3
http_failures: 3
type: http
http_path: /health
timeout: 1kubectl apply -f custom-upstream.yamlПрименение к Service:
apiVersion: v1
kind: Service
metadata:
name: users-service
annotations:
konghq.com/override: custom-upstream
spec:
# ...Проблема: Нужно проксировать TCP/UDP трафик через Kong.
Решение: TCPIngress и UDPIngress CRD.
# tcp-ingress.yaml
apiVersion: configuration.konghq.com/v1beta1
kind: TCPIngress
metadata:
name: postgres-tcp
namespace: default
spec:
rules:
- port: 5432
backend:
serviceName: postgres-service
servicePort: 5432kubectl apply -f tcp-ingress.yaml# udp-ingress.yaml
apiVersion: configuration.konghq.com/v1beta1
kind: UDPIngress
metadata:
name: dns-udp
namespace: default
spec:
rules:
- port: 53
backend:
serviceName: coredns
servicePort: 53Проблема: Нужно включить HTTPS для API.
Решение: TLS Secret и Ingress с TLS.
kubectl create secret tls api-tls-secret \
--cert=tls.crt \
--key=tls.key \
--namespace=defaultapiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: users-ingress
annotations:
kubernetes.io/ingress.class: kong
spec:
tls:
- hosts:
- api.example.com
secretName: api-tls-secret
rules:
- host: api.example.com
http:
paths:
- path: /users
pathType: Prefix
backend:
service:
name: users-service
port:
number: 80Проблема: Нужно развернуть новую версию сервиса с постепенным накатом.
Решение: Несколько Ingress с weights через KongIngress.
# users-v1.yaml
apiVersion: v1
kind: Service
metadata:
name: users-service-v1
annotations:
konghq.com/plugins: canary-v1
spec:
selector:
app: users-service
version: v1
ports:
- port: 80
targetPort: 8080
---
# users-v2.yaml
apiVersion: v1
kind: Service
metadata:
name: users-service-v2
annotations:
konghq.com/plugins: canary-v2
spec:
selector:
app: users-service
version: v2
ports:
- port: 80
targetPort: 8080# canary-route.yaml
apiVersion: configuration.konghq.com/v1
kind: KongIngress
metadata:
name: canary-route
spec:
route:
weights:
- weight: 90
service: users-service-v1
- weight: 10
service: users-service-v2namespaces/
kong/ # Kong Ingress Controller
default/ # Приложения
staging/ # Staging окружение
production/ # Production окружение
Проблема: Нужно версионировать конфигурацию Kong.
Решение: Хранить все YAML манифесты в git.
# kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- users-service.yaml
- users-ingress.yaml
- rate-limit-plugin.yaml
- jwt-plugin.yaml
- consumer.yaml
configMapGenerator:
- name: kong-config
files:
- kong.yml# Проверка статуса синхронизации
kubectl get ingress -o custom-columns=NAME:.metadata.name,SYNCED:.status.loadBalancer.ingress
# Логи Kong Ingress Controller
kubectl logs -n kong -l app=kong-ingress-controller
# Проверка конфигурации Kong
kubectl port-forward -n kong svc/kong-admin 8001:80
curl http://localhost:8001/routesВопросы ещё не добавлены
Вопросы для этой подтемы ещё не добавлены.