在CentOS上實現K8s自動擴縮容,通常使用Horizontal Pod Autoscaler(HPA)和Cluster Autoscaler,具體操作如下:
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
spec:
replicas: 2
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:latest
resources:
requests:
cpu: "100m"
memory: "200Mi"
limits:
cpu: "500m"
memory: "1Gi"
kubectl autoscale deployment nginx-deployment --cpu-percent=50 --min=2 --max=10
或使用YAML文件:
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: nginx-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: nginx-deployment
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 50
kubectl apply -f https://github.com/kubernetes/autoscaler/releases/download/cluster-autoscaler/v1.21.0/cluster-autoscaler.yaml
kubectl get hpa
kubectl top nodes和kubectl top pods命令監控資源使用情況,或通過Prometheus等工具進行更詳細的監控。