背景简介
Redis 在执行后台保存(RDB 快照)或 AOF 重写时,会使用 fork() 系统调用创建一个子进程。这个子进程 initially 会共享父进程的内存页。Linux 的写时复制机制意味着只有当内存被修改时,才会复制新的页面。
在最坏的情况下,这个 fork() 操作需要分配与当前 Redis 数据集大小相当的内存。如果 vm.overcommit_memory 被设置为禁用(默认值通常是 0),当内存不足时,fork() 可能会失败,导致后台保存任务失败,严重时甚至可能导致 Redis 服务停止。
报错信息
1:C 28 Oct 2025 07:45:14.679 # WARNING Memory overcommit must be enabled! Without it, a background save or replication may fail under low memory condition. Being disabled, it can also cause failures without low memory condition, see https://github.com/jemalloc/jemalloc/issues/1328. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
1:C 28 Oct 2025 07:45:14.679 * oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
1:C 28 Oct 2025 07:45:14.679 * Redis version=7.4.6, bits=64, commit=00000000, modified=0, pid=1, just started
1:C 28 Oct 2025 07:45:14.679 * Configuration loaded
1:M 28 Oct 2025 07:45:14.680 * monotonic clock: POSIX clock_gettime
1:M 28 Oct 2025 07:45:14.681 * Running mode=standalone, port=6379.
1:M 28 Oct 2025 07:45:14.681 * Server initialized
1:M 28 Oct 2025 07:45:14.687 * Creating AOF base file appendonly.aof.1.base.rdb on server start
1:M 28 Oct 2025 07:45:14.699 * Creating AOF incr file appendonly.aof.1.incr.aof on server start
1:M 28 Oct 2025 07:45:14.699 * Ready to accept connections tcp
前置信息
- Ubuntu
- Docker 部署 Redis
解决方案
- 修改
/etc/systcl.conf文件
vm.overcommit_memory = 1
设置为 1 意味着“总是允许超量分配”。这告诉内核:“尽管分配内存给我,我保证我有办法处理”。对于 Redis 来说,这是最安全的设置,可以确保其后台操作(如持久化)能够顺利进行。
- 应用配置
sudo sysctl -p
- 重启 Redis后查看log
1:C 28 Oct 2025 07:57:31.778 * oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
1:C 28 Oct 2025 07:57:31.778 * Redis version=7.4.6, bits=64, commit=00000000, modified=0, pid=1, just started
1:C 28 Oct 2025 07:57:31.778 * Configuration loaded
1:M 28 Oct 2025 07:57:31.779 * monotonic clock: POSIX clock_gettime
1:M 28 Oct 2025 07:57:31.781 * Running mode=standalone, port=6379.
1:M 28 Oct 2025 07:57:31.781 * Server initialized
1:M 28 Oct 2025 07:57:31.782 * Reading RDB base file on AOF loading...
1:M 28 Oct 2025 07:57:31.782 * Loading RDB produced by version 7.4.6
1:M 28 Oct 2025 07:57:31.782 * RDB age 737 seconds
1:M 28 Oct 2025 07:57:31.782 * RDB memory usage when created 0.90 Mb
1:M 28 Oct 2025 07:57:31.782 * RDB is base AOF
1:M 28 Oct 2025 07:57:31.782 * Done loading RDB, keys loaded: 0, keys expired: 0.
1:M 28 Oct 2025 07:57:31.782 * DB loaded from base file appendonly.aof.1.base.rdb: 0.000 seconds
1:M 28 Oct 2025 07:57:31.782 * DB loaded from append only file: 0.000 seconds
1:M 28 Oct 2025 07:57:31.782 * Opening AOF incr file appendonly.aof.1.incr.aof on server start
1:M 28 Oct 2025 07:57:31.782 * Ready to accept connections tcp
警告信息已消失
以上便是本文的全部内容,感谢您的阅读,如遇到任何问题,欢迎在评论区留言讨论。