# 在 Kubernetes 节点上配置交换内存

LLMS index: [llms.txt](/llms.txt)

---

<!--
reviewers:
- lmktfy
title: Configuring swap memory on Kubernetes nodes
content_type: tutorial
weight: 35
min-kubernetes-server-version: "1.33"
-->

<!-- overview -->

<!--
This page provides an example of how to provision and configure swap memory on a Kubernetes node using kubeadm.
-->
本文演示了如何使用 kubeadm 在 Kubernetes 节点上制备和启用交换内存。

<!-- lessoncontent -->

## 教程目标

<!--
* Provision swap memory on a Kubernetes node using kubeadm.
* Learn to configure both encrypted and unencrypted swap.
* Learn to enable swap on boot.
-->
* 使用 kubeadm 在 Kubernetes 节点上制备交换内存。
* 学习配置加密和未加密的交换内存。
* 学习如何在系统启动时启用交换内存。

## 准备开始

<!--
You need to have a Kubernetes cluster, and the kubectl command-line tool must
be configured to communicate with your cluster. It is recommended to run this tutorial on a cluster with at least two nodes that are not acting as control plane hosts. If you do not already have a
cluster, you can create one by using
[minikube](https://minikube.sigs.k8s.io/docs/tutorials/multi_node/)
or you can use one of these Kubernetes playgrounds:
-->
<p>你必须拥有一个 Kubernetes 的集群，且必须配置 kubectl 命令行工具让其与你的集群通信。
建议运行本教程的集群至少有两个节点，且这两个节点不能作为控制平面主机。
如果你还没有集群，你可以通过 <a href="https://minikube.sigs.k8s.io/docs/tutorials/multi_node/">Minikube</a>
构建一个你自己的集群，或者你可以使用下面的 Kubernetes 练习环境之一：</p>
<!--
* [iximiuz Labs](https://labs.iximiuz.com/playgrounds?category=kubernetes&filter=all)
* [Killercoda](https://killercoda.com/playgrounds/scenario/kubernetes)
* [KodeKloud](https://kodekloud.com/public-playgrounds)
-->
<ul>
<li><a href="https://labs.iximiuz.com/playgrounds?category=kubernetes&filter=all">iximiuz Labs</a></li>
<li><a href="https://killercoda.com/playgrounds/scenario/kubernetes">Killercoda</a></li>
<li><a href="https://kodekloud.com/public-playgrounds">KodeKloud</a></li>
</ul>
 
 
 你的 Kubernetes 服务器版本必须不低于版本 1.33.
  <p>要获知版本信息，请输入  <code>kubectl version</code>.</p>


<!--
You need at least one worker node in your cluster which needs to run a Linux operating system.
It is required for this demo that the kubeadm tool be installed, following the steps outlined in the
[kubeadm installation guide](/docs/setup/production-environment/tools/kubeadm/create-cluster-kubeadm).
-->
你需要在集群中至少有一个运行 Linux 操作系统的工作节点。
本次演示需要先安装 kubeadm 工具，安装步骤请参考
[kubeadm 安装指南](/zh-cn/docs/setup/production-environment/tools/kubeadm/create-cluster-kubeadm)。

<!--
On each worker node where you will configure swap use, you need:
* `fallocate`
* `mkswap`
* `swapon`

* For encrypted swap space (recommended), you also need:
* `cryptsetup`
-->
在每个需要配置交换内存的工作节点上，你需要以下工具：

* `fallocate`
* `mkswap`
* `swapon`

对于加密的交换空间（推荐），你还需要：

* `cryptsetup`

<!-- lessoncontent -->

<!--
## Install a swap-enabled cluster with kubeadm

### Create a swap file and turn swap on

If swap is not enabled, there's a need to provision swap on the node. 
The following sections demonstrate creating 4GiB of swap, both in the encrypted and unencrypted case.
-->
## 使用 kubeadm 安装支持交换内存的集群  {#install-a-swap-enabled-cluster-with-kubeadm}

### 创建交换文件并启用交换内存  {#create-a-swap-file-and-turn-swap-on}

如果当前节点未启用交换内存，则需要先**制备**交换空间。
本节将展示如何以加密和未加密的方式创建 4GiB 的交换文件。

<!--
"Create a swap file and turn swap on"
"Setting up encrypted swap"
-->
<ul class="nav nav-tabs" id="tabs-创建交换文件并启用交换内存" role="tablist"><li class="nav-item"><a data-bs-toggle="tab" class="nav-link active" href="#tabs-%e5%88%9b%e5%bb%ba%e4%ba%a4%e6%8d%a2%e6%96%87%e4%bb%b6%e5%b9%b6%e5%90%af%e7%94%a8%e4%ba%a4%e6%8d%a2%e5%86%85%e5%ad%98-0" role="tab" aria-controls="tabs-创建交换文件并启用交换内存-0" aria-selected="true">设置加密的交换内存</a></li>
	  
		<li class="nav-item"><a data-bs-toggle="tab" class="nav-link" href="#tabs-%e5%88%9b%e5%bb%ba%e4%ba%a4%e6%8d%a2%e6%96%87%e4%bb%b6%e5%b9%b6%e5%90%af%e7%94%a8%e4%ba%a4%e6%8d%a2%e5%86%85%e5%ad%98-1" role="tab" aria-controls="tabs-创建交换文件并启用交换内存-1">设置未加密的交换内存</a></li></ul>

<div class="tab-content" id="tabs-创建交换文件并启用交换内存-content"><div class="tab-body tab-pane fadeshow active"
        id="tabs-创建交换文件并启用交换内存-0" role="tabpanel" aria-labelledby="tabs-创建交换文件并启用交换内存-0-tab" tabindex="创建交换文件并启用交换内存"><!--
An encrypted swap file can be set up as follows.
Bear in mind that this example uses the `cryptsetup` binary (which is available
on most Linux distributions).
-->
<p>你可以使用如下命令设置加密的交换文件。
请注意，此示例使用的是 <code>cryptsetup</code> 工具（在大多数 Linux 发行版中都可用）：</p>
<!--
```bash
# Allocate storage and restrict access
fallocate --length 4GiB /swapfile
chmod 600 /swapfile

# Create an encrypted device backed by the allocated storage
cryptsetup --type plain --cipher aes-xts-plain64 --key-size 256 -d /dev/urandom open /swapfile cryptswap

# Format the swap space
mkswap /dev/mapper/cryptswap

# Activate the swap space for paging
swapon /dev/mapper/cryptswap
```
-->
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="c1"># 分配存储空间并限制访问权限</span>
</span></span><span class="line"><span class="cl">fallocate --length 4GiB /swapfile
</span></span><span class="line"><span class="cl">chmod <span class="m">600</span> /swapfile
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1"># 基于已分配的存储空间创建加密设备</span>
</span></span><span class="line"><span class="cl">cryptsetup --type plain --cipher aes-xts-plain64 --key-size <span class="m">256</span> -d /dev/urandom open /swapfile cryptswap
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1"># 格式化此交换空间</span>
</span></span><span class="line"><span class="cl">mkswap /dev/mapper/cryptswap
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1"># 为换页激活交换空间</span>
</span></span><span class="line"><span class="cl">swapon /dev/mapper/cryptswap
</span></span></code></pre></div></div><div class="tab-body tab-pane fade"
        id="tabs-创建交换文件并启用交换内存-1" role="tabpanel" aria-labelledby="tabs-创建交换文件并启用交换内存-1-tab" tabindex="创建交换文件并启用交换内存"><!--
An unencrypted swap file can be set up as follows.

```bash
# Allocate storage and restrict access
fallocate --length 4GiB /swapfile
chmod 600 /swapfile

# Format the swap space
mkswap /swapfile

# Activate the swap space for paging
swapon /swapfile
```
-->
<p>未加密的交换文件可以按以下方式配置：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="c1"># 分配存储空间并限制访问权限</span>
</span></span><span class="line"><span class="cl">fallocate --length 4GiB /swapfile
</span></span><span class="line"><span class="cl">chmod <span class="m">600</span> /swapfile
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1"># 格式化此交换空间</span>
</span></span><span class="line"><span class="cl">mkswap /swapfile
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1"># 为换页激活交换空间</span>
</span></span><span class="line"><span class="cl">swapon /swapfile
</span></span></code></pre></div></div></div>


<!--
#### Verify that swap is enabled

Swap can be verified to be enabled with both `swapon -s` command or the `free` command.

Using `swapon -s`:
-->
#### 验证交换内存是否启用

你可以使用 `swapon -s` 命令或 `free` 命令来验证交换内存是否启用。

使用 `swapon -s`：

```
Filename       Type		Size		Used		Priority
/dev/dm-0      partition 	4194300		0		-2
```

使用 `free -h`：
<!--
Using `free -h`:
-->

```
               total        used        free      shared  buff/cache   available
Mem:           3.8Gi       1.3Gi       249Mi        25Mi       2.5Gi       2.5Gi
Swap:          4.0Gi          0B       4.0Gi
```

<!--
#### Enable swap on boot

After setting up swap, to start the swap file at boot time,
you typically either set up a systemd unit to activate (encrypted) swap, or you
add a line similar to `/swapfile swap swap defaults 0 0` into `/etc/fstab`.

Using systemd for swap activation allows the system to delay kubelet start until swap is available,
if that is something you want to ensure.
In a similar way, using systemd allows your server to leave swap active until kubelet
(and, typically, your container runtime) have shut down.
-->
#### 引导时启用交换内存

在设置好交换内存后，若要在系统引导时启动交换文件，通常有两种做法：
你可以设置一个 systemd 单元来激活（加密的）交换内存，或者在
`/etc/fstab` 文件中添加类似于 `/swapfile swap swap defaults 0 0` 的行。

使用 systemd 激活交换内存，可以确保在交换内存可用之前延迟启动 kubelet（如果你有这个需求）。
同样，使用 systemd 还可以让服务器在 kubelet（以及通常的容器运行时）关闭之前保持交换内存处于启用状态。

<!--
### Set up kubelet configuration

After enabling swap on the node, kubelet needs to be configured to use it.
You need to select a [swap behavior](/docs/reference/node/swap-behavior/)
for this node. You'll configure _LimitedSwap_ behavior for this tutorial.

Find and edit the kubelet configuration file, and:

- set `failSwapOn` to false
- set `memorySwap.swapBehavior` to LimitedSwap
-->
### 配置 kubelet  {#set-up-kubelet-configuration}

在节点上启用交换内存后，需要按如下方式配置 kubelet。
你需要为此节点选择一种[交换内存行为](/zh-cn/docs/reference/node/swap-behavior/)。
在本教程中，你将配置 **LimitedSwap** 行为。

找到并编辑 kubelet 配置文件，然后：

- 将 `failSwapOn` 设置为 false
- 将 `memorySwap.swapBehavior` 设置为 LimitedSwap

<!--
```yaml
 # this fragment goes into the kubelet's configuration file
 failSwapOn: false
 memorySwap:
     swapBehavior: LimitedSwap
```
-->
```yaml
# 此代码片段应添加到 kubelet 的配置文件中
failSwapOn: false
memorySwap:
    swapBehavior: LimitedSwap
```

<!--
In order for these configurations to take effect, kubelet needs to be restarted. 
Typically you do that by running:
-->
为了使这些配置生效，需重启 kubelet。
通常你需要为此运行以下命令：

```shell
systemctl restart kubelet.service
```

<!--
You should find that the kubelet is now healthy, and that you can run Pods
that use swap memory as needed.
-->
你应该会发现 kubelet 现在处于健康状态，并且你可以根据需要运行使用交换内存的 Pod。
