Linux Swap Configuration Skill
You are a Linux swap configuration assistant. When a user needs to create, resize, or tune swap on a Linux system, use this skill.
Typical scenarios:
- - Server has no swap, user wants to add one
- User wants to resize existing swap
- User wants to tune swappiness
- Swap is lost after reboot (not persisted in fstab)
Workflow
- 1. First check the current swap status to understand the starting point
- Then execute the appropriate operation section based on the user's request
- Always verify the result after any change
1. Check Current Swap Status
Before any operation, check the current state:
CODEBLOCK0
2. Create Swap File
First根据 RAM 大小确定 swap 容量:
| RAM | Swap 大小 |
|---|
| <= 2 GB | 2x RAM |
| > 2 GB -- 8 GB |
与 RAM 相等 |
| > 8 GB -- 64 GB | >= 4 GB |
例如:RAM 为 2 GB 时创建 4G swap,RAM 为 4 GB 时创建 4G swap,RAM 为 16 GB 时创建 4G swap。
两种创建方式,优先用 fallocate(快);ext3 或不支持 fallocate 的文件系统用 dd:
CODEBLOCK1
3. Persist Swap Across Reboots
Without this step, swap will be lost after reboot.
CODEBLOCK2
Verify the entry:
CODEBLOCK3
4. Set Swappiness
INLINECODE3 controls how aggressively the kernel uses swap (0-100, default 60). Value of 20 is recommended for most servers.
CODEBLOCK4
5. Resize Swap
按 Section 2 的规则表确定新容量,然后先禁用再重建:
CODEBLOCK5
The fstab entry does not need to change if the file path stays the same.
Linux Swap 配置技能
你是一名 Linux swap 配置助手。当用户需要在 Linux 系统上创建、调整大小或调优 swap 时,请使用此技能。
典型场景:
- - 服务器没有 swap,用户想要添加一个
- 用户想要调整现有 swap 的大小
- 用户想要调优 swappiness 值
- 重启后 swap 丢失(未在 fstab 中持久化)
工作流程
- 1. 首先检查当前 swap 状态,了解起始情况
- 然后根据用户请求执行相应的操作部分
- 任何更改后务必验证结果
1. 检查当前 Swap 状态
在执行任何操作之前,先检查当前状态:
bash
显示活动的 swap 设备
swapon --show
显示包括 swap 在内的内存信息
free -h
检查 fstab 中的 swap 持久化配置
grep -v ^# /etc/fstab | grep swap
当前 swappiness 值
sysctl vm.swappiness
2. 创建 Swap 文件
首先根据 RAM 大小确定 swap 容量:
| RAM | Swap 大小 |
|---|
| <= 2 GB | 2x RAM |
| > 2 GB -- 8 GB |
与 RAM 相等 |
| > 8 GB -- 64 GB | >= 4 GB |
例如:RAM 为 2 GB 时创建 4G swap,RAM 为 4 GB 时创建 4G swap,RAM 为 16 GB 时创建 4G swap。
两种创建方式,优先用 fallocate(快);ext3 或不支持 fallocate 的文件系统用 dd:
bash
根据上表确定 SIZE,例如 4G
方法 1: fallocate(推荐)
sudo fallocate -l
/swapfile
方法 2: dd(备用方案)
例如 4G = 4096M
sudo dd if=/dev/zero of=/swapfile bs=1M count=INMB>
设置权限 — swap 文件必须为 0600
sudo chmod 600 /swapfile
格式化为 swap
sudo mkswap /swapfile
启用
sudo swapon /swapfile
验证
swapon --show
free -h
3. 持久化 Swap 以支持重启
如果不执行此步骤,重启后 swap 将会丢失。
bash
添加到 /etc/fstab
echo /swapfile none swap sw 0 0 | sudo tee -a /etc/fstab
验证条目:
bash
grep swap /etc/fstab
4. 设置 Swappiness
vm.swappiness 控制内核使用 swap 的积极程度(0-100,默认 60)。对于大多数服务器,建议值为 20。
bash
立即生效
sudo sysctl -w vm.swappiness=20
重启后持久化
echo vm.swappiness=20 | sudo tee -a /etc/sysctl.conf
sudo sysctl -p
5. 调整 Swap 大小
按第 2 节的规则表确定新容量,然后先禁用再重建:
bash
禁用当前 swap
sudo swapoff /swapfile
使用新大小重新创建
sudo fallocate -l /swapfile
或:sudo dd if=/dev/zero of=/swapfile bs=1M count=INMB>
重新格式化并启用
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
验证
swapon --show
free -h
如果文件路径保持不变,则无需更改 fstab 条目。