> For the complete documentation index, see [llms.txt](https://bohans.gitbook.io/devops/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://bohans.gitbook.io/devops/kubernetes/ji-chu-zhi-shi/pod/ephemeral-containers-lin-shi-rong-qi.md).

# Ephemeral Containers（临时容器）

{% hint style="info" %}

#### <mark style="color:blue;">**临时容器与其他容器的不同之处在于，临时容器是被临时添加到 Pod 上，用于在线调试应用的，它永远不会自动重启，因此不适用于构建应用程序**</mark>。

{% endhint %}

{% hint style="warning" %}

#### <mark style="color:orange;">**因为临时容器是为了调试程序而设计的，所以在添加临时容器时，最好使用一个包含所有常用工具的镜像进行创建。**</mark>

{% endhint %}

当**业务容器崩溃**或**容器镜像不包含调试工具而导致 kubectl exec 不可用**时，临时容器对于交互式故障排查和在线 Debug 很有用。尤其是在使用像**不包含任何 shell 和其他工具的 distroless 镜像**作为基础镜像时，虽然可以减少攻击面和漏洞，但是对于问题的排查会变得尤为棘手，此时临时容器就可以发挥很大的作用，带来诸多便利性。

{% hint style="success" %}

* 临时容器的声明和普通容器类似，但是**临时容器没有端口配置**，因此不能使用像 ports、livenessProbe、readinessProbe、resources 这样的字段。**临时容器只是用来调试程序的，它的状态不会影响正常容器**，所以它并不需要这些字段配置。
* **临时容器使用 API 中一种特殊的 ephemeralcontainers 处理器进行创建**，而不是直接添加到 pod.spec 字段，因此**无法使用 kubectl edit 来添加一个临时容器。**
* 与常规容器一样，**将临时容器添加到 Pod 后，将不能更改或删除临时容器**，但是当添加了临时容器的 **Pod 重启后，临时容器就会被销毁**。
  {% endhint %}

## 使用临时容器来调试的例子 <a href="#ephemeral-container-example" id="ephemeral-container-example"></a>

首先，像示例一样创建一个 pod：

{% code overflow="wrap" %}

```properties
$ kubectl run ephemeral-demo \
--image=registry.cn-hangzhou.aliyuncs.com/google_containers/pause:3.1 --restart=Never
pod/ephemeral-demo created
```

{% endcode %}

如果尝试使用 kubectl exec 来创建一个 shell，将会看到一个错误，因为这个容器镜像中没有 shell：

<pre class="language-properties" data-overflow="wrap"><code class="lang-properties"><strong>$ kubectl exec -it ephemeral-demo -- sh
</strong>error: Internal error occurred: error executing command in container: failed to exec in container: failed to start exec "1993bffac1b845330114c8a71d16ee918b4586fbd7ad36bd5e6a844b4bdcdc0d": OCI runtime exec failed: exec failed: unable to start container process: exec: "sh": executable file not found in $PATH: unknown
</code></pre>

使用 <mark style="color:blue;">**kubectl debug**</mark> 添加调试容器。如果指定 <mark style="color:blue;">**-i**</mark> 或者 <mark style="color:blue;">**--interactive**</mark> 参数，<mark style="color:blue;">**kubectl**</mark> 将自动挂接到临时容器的控制台：

{% code overflow="wrap" %}

```properties
$ kubectl debug -it ephemeral-demo --image=centos:6 --target=ephemeral-demo
Targeting container "ephemeral-demo". If you don't see processes from this container it may be because the container runtime doesn't 
support this feature.
Defaulting debug container name to debugger-mmn8j.
If you don't see a command prompt, try pressing enter.
[root@ephemeral-demo /]# ps -ef
UID         PID   PPID  C STIME TTY          TIME CMD
root          1      0  0 03:10 ?        00:00:00 /pause
root         18      0  0 03:12 pts/0    00:00:00 /bin/bash
root         31     18  0 03:12 pts/0    00:00:00 ps -ef
```

{% endcode %}
