温馨提示×

centos如何搭建redis

小樊
33
2026-07-08 07:34:11
栏目: 云计算

CentOS 上搭建 Redis,常见有三种方式:yum 安装(最简单)源码编译安装(最常用、可控)Docker 安装。下面我按 生产环境最推荐的方式(源码安装) 详细说明,并补充 yum 方式。


一、环境准备(通用)

# 更新系统
yum update -y

# 安装依赖
yum install -y gcc make wget tcl

二、方式一:源码编译安装 Redis(推荐 ✅)

1️⃣ 下载 Redis 源码

cd /usr/local/src
wget https://download.redis.io/redis-stable.tar.gz
tar -zxvf redis-stable.tar.gz
cd redis-stable

2️⃣ 编译安装

make
make install

安装完成后,Redis 可执行文件会在:

/usr/local/bin/redis-server
/usr/local/bin/redis-cli

3️⃣ 配置 Redis

创建配置目录

mkdir -p /etc/redis
cp redis.conf /etc/redis/6379.conf

编辑配置文件

vim /etc/redis/6379.conf

常用修改项:

# 后台运行
daemonize yes

# 监听地址(生产建议内网IP)
bind 0.0.0.0

# 端口
port 6379

# 密码(强烈建议)
requirepass yourpassword

# 持久化
appendonly yes

# 日志文件
logfile "/var/log/redis.log"

4️⃣ 创建 systemd 服务(CentOS 7+)

vim /etc/systemd/system/redis.service

内容如下:

[Unit]
Description=Redis Server
After=network.target

[Service]
ExecStart=/usr/local/bin/redis-server /etc/redis/6379.conf
ExecStop=/usr/local/bin/redis-cli shutdown
Restart=always
User=root

[Install]
WantedBy=multi-user.target

5️⃣ 启动并设置开机自启

systemctl daemon-reload
systemctl start redis
systemctl enable redis
systemctl status redis

6️⃣ 测试 Redis

redis-cli
AUTH yourpassword
ping
# 返回 PONG 表示成功

三、方式二:yum 安装(简单但不一定是最新版本)

1️⃣ 安装 Redis

yum install -y epel-release
yum install -y redis

2️⃣ 启动 Redis

systemctl start redis
systemctl enable redis

配置文件路径:

/etc/redis.conf

四、防火墙放行(如需要)

firewall-cmd --add-port=6379/tcp --permanent
firewall-cmd --reload

生产环境不建议直接暴露 6379 到公网


五、常见问题排查

1️⃣ Redis 启动失败

journalctl -u redis -xe

2️⃣ 内存不足

vim /etc/redis/6379.conf
maxmemory 512mb
maxmemory-policy allkeys-lru

六、生产环境建议 ✅

✅ 关闭公网访问
✅ 设置密码
✅ 开启 AOF 持久化
✅ 限制最大内存
✅ 使用 systemd 管理
✅ 定期备份 RDB / AOF


如果你需要:

  • Redis 主从复制
  • Redis 哨兵(Sentinel)
  • Redis Cluster
  • 与 Java / PHP / Python 连接示例

告诉我你的 CentOS 版本(6/7/8)使用场景,我可以给你更精确方案。

0