擴展應用
通過修改 Deployment 中副本的數量(replicas),可以動態擴展或收縮應用:
這些自動擴展的容器會自動加入到 service 中,而收縮回收的容器也會自動從 service 中刪除。
Copy $ kubectl scale --replicas=3 deployment/nginx-app
$ kubectl get deploy
NAME DESIRED CURRENT UP-TO-DATE AVAILABLE AGE
nginx-app 3 3 3 3 10m
滾動升級
滾動升級(Rolling Update)通過逐個容器替代升級的方式來實現無中斷的服務升級:
Copy kubectl rolling-update frontend-v1 frontend-v2 --image=image:v2
在滾動升級的過程中,如果發現了失敗或者配置錯誤,還可以隨時回滾:
Copy kubectl rolling-update frontend-v1 frontend-v2 --rollback
需要注意的是,kubectl rolling-update
只針對 ReplicationController。對於更新策略是 RollingUpdate 的 Deployment(Deployment 可以在 spec 中設置更新策略爲 RollingUpdate,默認就是 RollingUpdate),更新應用後會自動滾動升級:
Copy spec:
replicas: 3
selector:
matchLabels:
run: nginx-app
strategy:
rollingUpdate:
maxSurge: 1
maxUnavailable: 1
type: RollingUpdate
而更新應用的話,就可以直接用 kubectl set
命令:
Copy kubectl set image deployment/nginx-app nginx-app=nginx:1.9.1
滾動升級的過程可以用 rollout
命令查看:
Copy $ kubectl rollout status deployment/nginx-app
Waiting for rollout to finish: 2 out of 3 new replicas have been updated...
Waiting for rollout to finish: 2 of 3 updated replicas are available...
Waiting for rollout to finish: 2 of 3 updated replicas are available...
Waiting for rollout to finish: 2 of 3 updated replicas are available...
Waiting for rollout to finish: 2 of 3 updated replicas are available...
Waiting for rollout to finish: 2 of 3 updated replicas are available...
deployment "nginx-app" successfully rolled out
Deployment 也支持回滾:
Copy $ kubectl rollout history deployment/nginx-app
deployments "nginx-app"
REVISION CHANGE-CAUSE
1 <none>
2 <none>
$ kubectl rollout undo deployment/nginx-app
deployment "nginx-app" rolled back
資源限制
Kubernetes 通過 cgroups 提供容器資源管理的功能,可以限制每個容器的 CPU 和內存使用,比如對於剛纔創建的 deployment,可以通過下面的命令限制 nginx 容器最多隻用 50% 的 CPU 和 128MB 的內存:
Copy $ kubectl set resources deployment nginx-app -c=nginx --limits=cpu=500m,memory=128Mi
deployment "nginx" resource requirements updated
這等同於在每個 Pod 中設置 resources limits:
Copy apiVersion: v1
kind: Pod
metadata:
labels:
app: nginx
name: nginx
spec:
containers:
- image: nginx
name: nginx
resources:
limits:
cpu: "500m"
memory: "128Mi"
健康檢查
Kubernetes 作爲一個面向應用的集群管理工具,需要確保容器在部署後確實處在正常的運行狀態。Kubernetes 提供了兩種探針(Probe,支持 exec、tcpSocket 和 http 方式)來探測容器的狀態:
LivenessProbe:探測應用是否處於健康狀態,如果不健康則刪除並重新創建容器
ReadinessProbe:探測應用是否啓動完成並且處於正常服務狀態,如果不正常則不會接收來自 Kubernetes Service 的流量
對於已經部署的 deployment,可以通過 kubectl edit deployment/nginx-app
來更新 manifest,增加健康檢查部分:
Copy apiVersion: extensions/v1beta1
kind: Deployment
metadata:
labels:
app: nginx
name: nginx-default
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- image: nginx
imagePullPolicy: Always
name: http
resources: {}
terminationMessagePath: /dev/termination-log
terminationMessagePolicy: File
resources:
limits:
cpu: "500m"
memory: "128Mi"
livenessProbe:
httpGet:
path: /
port: 80
initialDelaySeconds: 15
timeoutSeconds: 1
readinessProbe:
httpGet:
path: /
port: 80
initialDelaySeconds: 5
timeoutSeconds: 1