个人技术空间

Linux 开启 zRam 内存压缩

系统环境:Ubuntu:24.04

zRam可以将内存压缩存储,能在有限的物理内存中存放更多的数据。
和 swap 不同的是,zRam 的数据还是存放在内存中,比在 swap 文件中的数据读写速度更高,缺点是会消耗一定的 CPU。

对于小内存的机器,开启 zRam 和 swap 都是能缓解内存紧张。

安装zram工具

apt install zram-tools

编辑配置文件

root@linux:~# cat /etc/default/zramswap
# Compression algorithm selection
# speed: lz4 > zstd > lzo
# compression: zstd > lzo > lz4
# This is not inclusive of all that is available in latest kernels
# See /sys/block/zram0/comp_algorithm (when zram module is loaded) to see
# what is currently set and available for your kernel[1]
# [1]  https://github.com/torvalds/linux/blob/master/Documentation/blockdev/zram.txt#L86
ALGO=zstd

# Specifies the amount of RAM that should be used for zram
# based on a percentage the total amount of available memory
# This takes precedence and overrides SIZE below
PERCENT=50

# Specifies a static amount of RAM that should be used for
# the ZRAM devices, this is in MiB
#SIZE=256

# Specifies the priority for the swap devices, see swapon(2)
# for more details. Higher number = higher priority
# This should probably be higher than hdd/ssd swaps.
PRIORITY=100

参数说明

重启服务生效

systemctl restart zramswap

查看 zram 的使用情况

root@linux:~# swapon --show
NAME       TYPE        SIZE   USED PRIO
/swap.img  file        1.9G     0B   -2
/dev/zram0 partition 983.8M 549.1M  100
root@linux:~# zramctl
NAME       ALGORITHM DISKSIZE   DATA  COMPR  TOTAL STREAMS MOUNTPOINT
/dev/zram0 zstd        983.8M 548.8M 122.1M 126.6M       2 [SWAP]

zramctl 的输出可以看到,Data 数据大小 548.8M,ToTal 实际占用 126.6M,作用还是很明显的。

另外,可以调整内核参数,几乎所有非活跃进程进入压缩状态。极致节省物理内存,但 CPU 负载会升高。

root@linux:~# sysctl vm.swappiness
vm.swappiness = 150

vm.swappiness 的值可以设置为 100-200 之间。

CreateBy:2026-02-22,UpdateBy:2026-02-22
版权声明:署名-非商业性使用-禁止演绎 3.0 未本地化版本 (CC BY-NC-ND 3.0)
留言板开发中,站长邮箱:admin@aliencn.net。欢迎交流。