docker - 安装配置 Redis 6.x
- 拉取镜像
1 | docker pull redis:6.2.7 |
- 创建挂载目录
1 | mkdir ./redis |
- 拉取官方配置文件
Redis configuration | Docs 这个提供了所有的配置文件,我这里选择 6.2 版本,如下
1 | curl -fsSL https://raw.githubusercontent.com/redis/redis/6.2/redis.conf \ |
- 修改配置文件
通过命令 vi ./redis/redis.conf
编辑配置文件,修改如下信息
1 | # 允许远程访问 |
【提示】为什么我这里要设置密码?
因为 redis.conf 配置文件中有一个配置是 protected-mode 默认是 yes,即处于保护模式,此时要求我们:如果没有 bind 具体的 IP,则必须设置密码,如果不设置密码,则有如下报错
1
2
3 root@eb2215e39db8:/data# redis-cli -h 172.17.0.3
172.17.0.3:6379> get a
(error) DENIED Redis is running in protected mode because protected mode is enabled, no bind address was specified, no authentication password is requested to clients. In this mode connections are only accepted from the loopback interface. If you want to connect from external computers to Redis you may adopt one of the following solutions: 1) Just disable protected mode sending the command 'CONFIG SET protected-mode no' from the loopback interface by connecting to Redis from the same host the server is running, however MAKE SURE Redis is not publicly accessible from internet if you do so. Use CONFIG REWRITE to make this change permanent. 2) Alternatively you can just disable the protected mode by editing the Redis configuration file, and setting the protected mode option to 'no', and then restarting the server. 3) If you started the server manually just for testing, restart it with the '--protected-mode no' option. 4) Setup a bind address or an authentication password. NOTE: You only need to do one of the above things in order for the server to start accepting connections from the outside.此时有三种解决方案
关闭保护模式
- 【1】注释 bind,无需设置密码:不推荐
开启保护模式
【2】不注释 bind,无需设置密码:此时只能本地访问(此时即使通过 docker 将端口映射出来,其实也是不能外部使用的,因为 docker 映射的网卡其实是 eth0,不包括回环地址)【也就是说根本不能用,不推荐】
【3】注释 bind,设置密码:推荐,即安全,又达到我们的目的
另外,为了验证没有配置文件时,redis 的默认配置是什么样的,我通过如下命令启动了一个 redis 容器【此时可以通过外部直接访问,相当于上述解决方案中的1】
1 docker run --rm -p 6379:6379 redis:6.2.7![]()
- 启动容器
1 | docker run --name redis \ |
【提示】对应的 docker-compose.yml 文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 networks:
net:
name: redis_net
volumes:
redis_data:
name: redis_data
services:
redis:
image: redis:6.2.7
container_name: redis
restart: unless-stopped
networks:
- net
ports:
- 6379:6379
environment:
- TZ=Asia/Shanghai
- LANG=C.UTF-8
volumes:
- redis_data:/data
- ./redis/redis.conf:/etc/redis/redis.conf
command: redis-server /etc/redis/redis.conf
- 连接测试
我这里使用的图形化客户端是 RedisDesktopManager,如下配置连接信息