确保你的电脑已经安装docker并正常启动

Step1:搜索redis: docker search redis

Step2:拉取官方镜像:docker pull docker.io/redis

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Using default tag: latest
latest: Pulling from library/redis
27833a3ba0a5: Pulling fs layer
cde8019a4b43: Pulling fs layer
97a473b37fb2: Pulling fs layer
c6fe0dfbb7e3: Waiting
39c8f5ba1240: Waiting
cfbdd870cf75: Waiting
latest: Pulling from library/redis
27833a3ba0a5: Pull complete
cde8019a4b43: Pull complete
97a473b37fb2: Pull complete
c6fe0dfbb7e3: Pull complete
39c8f5ba1240: Pull complete
cfbdd870cf75: Pull complete
Digest: sha256:000339fb57e0ddf2d48d72f3341e47a8ca3b1beae9bdcb25a96323095b72a79b
Status: Downloaded newer image for redis:latest

Step3:下载完成后,使用docker images查看是否拉去成功:

1
2
3
4
5
REPOSITORY                       TAG                 IMAGE ID            CREATED             SIZE
redis latest a55fbf438dfd 8 days ago 95MB
nginx latest 881bd08c0b08 4 weeks ago 109MB
hello-world latest fce289e99eb9 3 months ago 1.84kB
alexeiled/docker-oracle-xe-11g latest f7304758169d 2 years ago 2.39GB

Step4:运行容器

1
docker run -p 6379:6379 -v $PWD/data:/data -d redis:latest redis-server --appendonly yes

命令说明:
docker run:启动命令

-p 6379:6379 : 将容器的6379端口映射到主机的6379端口

-v $PWD/data:/data : 将主机中当前目录下的data挂载到容器的/data
- d : 后台运行
redis-server --appendonly yes : 在容器执行redis-server启动命令,并打开redis持久化配置

Step5:使用docker ps命令查看容器是否启动:

1
2
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                    NAMES
13c589ece0eb redis:latest "docker-entrypoint.s…" 8 seconds ago Up 6 seconds 0.0.0.0:6379->6379/tcp serene_golick

Step6:连接、查看容器:

使用redis镜像执行docker exec -it 13c589ece0eb redis-cli命令连接到刚启动的容器,主机IP为127.0.0.1:6379

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
127.0.0.1:6379> info
# Server
redis_version:5.0.4
redis_git_sha1:00000000
redis_git_dirty:0
redis_build_id:c6d7e1572d62bb79
redis_mode:standalone
os:Linux 4.9.125-linuxkit x86_64
arch_bits:64
multiplexing_api:epoll
atomicvar_api:atomic-builtin
gcc_version:6.3.0
process_id:1
run_id:6143b8551da60441636d50e0fed7aeb93ee363cc
tcp_port:6379
uptime_in_seconds:73
uptime_in_days:0
hz:10
configured_hz:10
lru_clock:10846166
executable:/data/redis-server
config_file:

Step7: 使用redis:

添加数据, key 为 username value 为zhangsan

1
2
127.0.0.1:6379> set username zhangsan
OK

欢迎关注微信公众号【Java猿记】,回复【面试】可领取面试资料。