环境准备
- Docker:提供隔离容器环境,可运行应用程序。
- Docker compose:运行多个容器服务的管理工具,通过编写 YAML 配置文件,可以实现一键启动多个应用服务。
运行 Redis 服务
0. 创建并进入目录
mkdir redis-docker # 可以随意命名
cd redis-docker
也可以直接克隆 Repo,已经写好 compose 文件,直接跳到第2步。
git clone https://github.com/aaron0769/docker-redis.git
tree docker-redis
docker-redis
├── LICENSE
├── README.md
├── conf
│ └── redis.conf
└── docker-compose.yml
cd docker-redis
1. 编写 compose 文件 docker-compose.yml
version: '3'
services:
redis:
image: redis
ports:
- "6379:6379"
volumes:
- ./data:/data
- ./conf/redis.conf:/etc/redis.conf
networks:
localnet:
aliases:
- my-redis-server
command: ["redis-server", "/etc/redis.conf"]
networks:
localnet:
关于 compose 文件想了解更多,可以参考以下文档:
https://docs.docker.com/compose/gettingstarted/
2. 启动
# 在 docker-redis 目录下
docker-compose up
3. 测试
方法一:使用 redis-cli 命令行工具
docker run --network redis_localnet -it --rm redis redis-cli -h $my-redis-server
方法二:使用 redis-py 客户端
/usr/bin/env python3
import redis
conn = redis.StrictRedis(host='127.0.0.1', port=6379)
conn.set('A', 1)
result = conn.get('A')
print(result)
4. 下线 Redis 服务
docker-compose down
5. 修改配置
vim conf/redis.conf
docker-compose stop && docker-compose up
6. 查看备份文件
data
├── appendonly.aof
└── dump.rdb
7. 查看 Redis 日志
$docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
b6665e1c7d66 redis "docker-entrypoint.s…" About a minute ago Up About a minute 0.0.0.0:6379->6379/tcp redis_redis_1
#$docker logs b6665e1c7d66
$docker logs redis_redis_1 # 效果同上一行
1:C 04 Aug 14:41:28.012 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
1:C 04 Aug 14:41:28.012 # Redis version=4.0.11, bits=64, commit=00000000, modified=0, pid=1, just started
1:C 04 Aug 14:41:28.012 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
1:M 04 Aug 14:41:28.015 * Running mode=standalone, port=6379.
1:M 04 Aug 14:41:28.015 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
1:M 04 Aug 14:41:28.015 # Server initialized
1:M 04 Aug 14:41:28.015 # WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled.
1:M 04 Aug 14:41:28.020 * DB loaded from disk: 0.004 seconds
1:M 04 Aug 14:41:28.020 * Ready to accept connections