实验手册-08-滚动更新

本次实验手册我们学习一下K8S的滚动更新,滚动更新即每次更新一小部分 Pods 副本,整个更新的过程中,会始终保持有副本运行,从而保证业务的连续性。

步骤1 部署一个三副本的应用 httpd,这是不同于 nginx 的的 Web 服务器。

先创建一个配置文件,名字为 httpd-1.yaml

bash

vim httpd-1.yaml

文件内容为:

yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: httpd
spec:
  replicas: 3
  selector:
    matchLabels:
      app: web_server
  template:
    metadata:
      labels:
        app: web_server
        run: httpd
    spec:
      containers:
      - name: httpd
        image: httpd:2.2.31
        ports:
        - containerPort: 80

步骤2 通过 kubectl apply 加载该配置文件

bash

kubectl apply -f httpd-1.yaml
加载配置文件

步骤3 验证

先查看 Deployment 是不是创建成功

Deployment列表

再看看 ReplicaSet 是不是创建成功

bash

kubectl get replicaset -o wide
ReplicaSet列表

查看 Pods 是不是创建成功

bash

kubectl get pods -o wide
Pod列表

这个步骤中,K8S做了三件事:

  1. 创建 Deployment,名为 httpd
  2. 创建 ReplicaSet,名为 httpd-755694f8cd
  3. 创建三个 Pods

步骤4 我们修改一下配置文件,把 httpd 的版本进行升级

先拷贝一份配置文件

bash

cp httpd-1.yaml httpd-2.yaml

然后对新文件进行修改

bash

vim httpd-2.yaml

修改其中的第18行,把 httpd:2.2.31 改成 `httpd:2.2.32

修改后的配置文件

步骤5 我们加载一下这个新的配置文件

bash

kubectl apply -f httpd-2.yaml
加载 httpd-2.yaml

步骤6 验证

bash

kubectl get deployment -o wide
Deployment

注意,Deployment 中的镜像版本已经升级。接下来看看 ReplicaSet

bash

kubectl get replicaset -o wide
ReplicaSet

可以看出,建立了一个新的 ReplicaSet,版本号是更新后的,它拥有三个Pods(Current那一列)

同时,旧的 ReplicaSet 中已经没有 Pods 了(DESIRED、CURRENT、READY三列都是0)

步骤6 深入验证

bash

kubectl describe deployment httpd
调节过程

如果我们由于某些原因想撤销升级,可以使用回滚功能

步骤1 先删除上个任务中的资源

bash

kubectl delete -f httpd-2.yaml

步骤2 将刚才的配置文件 httpd-2.yaml 复制3份,并修改其中的版本号

text

cp httpd-2.yaml httpd-v1.yaml
cp httpd-2.yaml httpd-v2.yaml
cp httpd-2.yaml httpd-v3.yaml

修改三个新的配置文件,将其中的第18行,image: httpd:2.2.32 分别修改为 image: httpd:2.4.16 image: httpd:2.4.17image: httpd:2.4.18

步骤3 加载 v1 配置文件

bash

kubectl apply -f httpd-v1.yaml --record

注意加上最后的 --record 参数,这个参数会保存我们的操作记录

验证一下

bash

kubectl get deployment -o wide

步骤4 加载两个配置文件

bash

kubectl apply -f httpd-v2.yaml --record
kubectl apply -f httpd-v3.yaml --record

验证一下

text

kubectl get deployment -o wide

执行最后的操作后,镜像版本变成 httpd:2.4.18

步骤5 查看我们操作的历史记录

bash

kubectl rollout history deployment httpd

命令格式:kubectl <动作> <资源类型> [资源名称]

  • 动作:rollout history
  • 资源类型:deployment
  • 资源名称:httpd
命令格式

步骤6 回滚

bash

kubectl rollout undo deployment httpd --to-revision=1
回滚

验证

bash

kubectl get deployment -o wide

版本号已经回滚到 httpd:2.4.16