# 回滚 Deployment

当更新的版本不稳定或配置不合理时，可以对其进行回滚操作。

假设我们又进行了几次更新（此处以更新镜像版本触发更新，更改配置效果类似）：

```properties
kubectl set image deploy nginx-deploy nginx=dotbalo/canary:v1 --record
kubectl set image deploy nginx-deploy nginx=dotbalo/canary:v2 --record
```

> **如果上述命令不加 --record，当查看更新历史时将看不到命令信息，CAUSE-CHANGE 列将显示为< none>**

### 查看更新历史

使用 **kubectl rollout history** 查看更新历史：

{% code overflow="wrap" %}
```properties
$ kubectl rollout history deploy nginx-deploy
deployment.apps/nginx-deploy 
REVISION  CHANGE-CAUSE
3         <none>
4         <none>
5         kubectl.exe set image deploy nginx-deploy nginx=nginx:1.25.3 --record=true
6         kubectl.exe set image deployment nginx-deploy nginx=dotbalo/canary:v1 --record=true
7         kubectl.exe set image deploy nginx-deploy nginx=dotbalo/canary:v2 --record=true
```
{% endcode %}

### 查看更新的详细信息

查看 Deployment 某次更新的详细信息，使用 **--revision** 指定某次更新的版本号：

{% code overflow="wrap" lineNumbers="true" %}
```properties
$ kubectl rollout history deploy nginx-deploy --revision=5
deployment.apps/nginx-deploy with revision #5
Pod Template:
  Labels:       app=nginx
        pod-template-hash=68c574c9f
  Annotations:  kubernetes.io/change-cause: kubectl.exe set image deploy nginx-deploy nginx=nginx:1.25.3 --record=true
  Containers:
   nginx:
    Image:      nginx:1.25.3
    Port:       80/TCP
    Host Port:  0/TCP
    Limits:
      cpu:      500m
      memory:   128Mi
    Environment:        <none>
    Mounts:     <none>
  Volumes:      <none>
```
{% endcode %}

### 回滚

如果只需要回滚到上一个稳定版本，使用 **kubectl rollout undo** 即可：

```properties
$ kubectl rollout undo deploy nginx-deploy
deployment.apps/nginx-deploy rolled back
```

再次查看更新历史，发现 REVISION 8 回到了 canary:v1：

{% code overflow="wrap" %}
```properties
$ kubectl rollout history deploy nginx-deploy
deployment.apps/nginx-deploy 
REVISION  CHANGE-CAUSE
3         <none>
4         <none>
5         kubectl.exe set image deploy nginx-deploy nginx=nginx:1.25.3 --record=true
7         kubectl.exe set image deploy nginx-deploy nginx=dotbalo/canary:v2 --record=true
8         kubectl.exe set image deployment nginx-deploy nginx=dotbalo/canary:v1 --record=true
```
{% endcode %}

如果要回滚到**指定版本**，使用 **--to-revision** 参数：

```properties
$ kubectl rollout undo deploy nginx-deploy --to-revision=5
deployment.apps/nginx-deploy rolled back
```

{% code overflow="wrap" %}
```properties
$ kubectl rollout history deploy nginx-deploy
deployment.apps/nginx-deploy 
REVISION  CHANGE-CAUSE
3         <none>
4         <none>
7         kubectl.exe set image deploy nginx-deploy nginx=dotbalo/canary:v2 --record=true
8         kubectl.exe set image deployment nginx-deploy nginx=dotbalo/canary:v1 --record=true
9         kubectl.exe set image deploy nginx-deploy nginx=nginx:1.25.3 --record=true
```
{% endcode %}
