1. 创建配置文件
创建redis.conf配置文件,添加aof以及rdb配置信息,具体如下:
# 密码自行替换
requirepass aNrLBR840p6ymwTYmA
tcp-backlog 511
appendonly yes
appendfsync everysec
save 900 1
save 300 10
save 60 10000
2. 创建docker-compose
docker-compose.yml配置信息如下所示(添加了数据持久化配置):
version: "3.8"
services:
redis:
container_name: redis
hostname: redis
image: redis:7.4.1-alpine
command: redis-server /usr/local/etc/redis/redis.conf
volumes:
- ./data:/data
- ./redis.conf:/usr/local/etc/redis/redis.conf
ports:
- "6379:6379"
3. 修正# WARNING Memory overcommit must be enabled!问题
参照前序章节配置,启动redis容器,会出现如下提示:
1:C 22 Jan 2025 08:43:05.587 # 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.
对于此问题,可以参照《How to remove Redis warning on Docker: Memory overcommit must be enabled》一文解决,缺点是docker logs无法观察到日志。
3.1 编写启动脚本
init.sh脚本如下:
# WARNING overcommit_memory is set to 0! Background save may fail under low memory condition.
# 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.
# The overcommit_memory has 3 options.
# 0, the system kernel check if there is enough memory to be allocated to the process or not,
# if not enough, it will return errors to the process.
# 1, the system kernel is allowed to allocate the whole memory to the process
# no matter what the status of memory is.
# 2, the system kernel is allowed to allocate a memory whose size could be bigger than
# the sum of the size of physical memory and the size of exchange workspace to the process.
sysctl vm.overcommit_memory=1
# Start redis server
redis-server /usr/local/etc/redis/redis.conf --bind 0.0.0.0
3.2 Dockerfile
FROM redis:7.4.1-alpine
WORKDIR /redis
COPY redis.conf /usr/local/etc/redis/redis.conf
COPY init.sh ./
RUN chmod +x init.sh
3.3 docker-compose
version: '3.8'
services:
cache:
# Adjust the build context to your needs targetting the created Dockerfile
build:
context: .
dockerfile: Dockerfile
#image: redis:7.2-alpine
restart: always
ports:
- 6379:6379
# Run the init script
command: sh -c "./init.sh"
# Run as privileged to allow the container to change the vm.overcommit_memory setting
privileged: true
volumes:
- ./data:/data