linuxDocker Compose部署Redis集群
时间: 2025-05-11 12:21:02 浏览: 17
### 使用 Docker Compose 在 Linux 上搭建 Redis 集群
#### 准备工作
为了成功使用 Docker Compose 搭建 Redis 集群,需要先完成一些必要的准备事项。确保目标机器上已经安装了 Docker 和 Docker Compose 工具[^1]。
#### 创建 Docker Compose 文件
创建一个新的 `docker-compose.yml` 文件来定义服务架构。下面是一个典型的用于构建 Redis 集群的配置文件:
```yaml
version: '3.7'
services:
redis-node-1:
image: redis:latest
command: ["redis-server", "--port", "6379", "--cluster-enabled", "yes", "--cluster-config-file", "nodes.conf", "--appendonly", "yes"]
ports:
- "6379:6379"
volumes:
- ./data/redis-node-1:/data
redis-node-2:
image: redis:latest
command: ["redis-server", "--port", "6380", "--cluster-enabled", "yes", "--cluster-config-file", "nodes.conf", "--appendonly", "yes"]
ports:
- "6380:6380"
volumes:
- ./data/redis-node-2:/data
redis-node-3:
image: redis:latest
command: ["redis-server", "--port", "6381", "--cluster-enabled", "yes", "--cluster-config-file", "nodes.conf", "--appendonly", "yes"]
ports:
- "6381:6381"
volumes:
- ./data/redis-node-3:/data
```
上述配置中指定了三个 Redis 节点,并启用了集群模式支持。
#### 启动容器并初始化集群
执行以下命令启动所有的 Redis 实例:
```bash
docker-compose up -d
```
当所有节点都已运行后,可以通过脚本来设置它们之间的连接关系形成完整的集群结构。这里提供一段 Python 的示例代码用来自动化这一过程:
```python
import subprocess, time
def create_cluster(hosts_ports):
cmd = ['redis-cli', '--cluster', 'create'] + hosts_ports.split() + ['--cluster-replicas', '1']
result = subprocess.run(cmd, stdout=subprocess.PIPE)
return result.stdout.decode('utf-8')
if __name__ == "__main__":
# 假设我们有六个实例分布在不同端口上
all_hosts = "localhost:6379 localhost:6380 localhost:6381"
output = create_cluster(all_hosts)
print(output)
```
此脚本会调用 `redis-cli --cluster create ...` 命令行工具去建立实际的分布式存储环境。
#### 测试与验证
最后一步是对新建成的服务做功能性的检测。尝试向任意一个节点写入数据后再读取出来确认一致性;也可以利用官方文档中的其他方法进一步检验整个系统的稳定性以及性能表现[^2]。
阅读全文
相关推荐

















