文章目录

  • 安装
  • 官方安装文档
  • 具体安装步骤
  • 1.卸载之前的版本(如果之前未用过忽略该步骤)
  • 2.安装相关依赖
  • 3.设置docker镜像
  • 4.安装docker
  • 安装latest版本
  • 指定版本安装
  • 5.启动docker
  • 6.查看docker版本
  • 7.运行一个docker hello world
  • 8.卸载docker
  • 9.配置阿里云镜像加速地址
  • docker常用命令
  • docker仓库搜索
  • 基础命令
  • docker版本信息
  • docker系统信息
  • 镜像命令
  • 查看本地主机上所有镜像
  • 搜索镜像
  • 下载镜像
  • 删除镜像
  • 批量删除镜像
  • 容器命令
  • 下载centos进行测试
  • 下载
  • 启动
  • 查看正在运行的docker
  • 退出容器
  • 删除容器
  • 启动和停止
  • 常用其他命令
  • 查看日志
  • 滚动查看日志,并且打印时间
  • 查看容器内部进程信息
  • 查看docker原信息
  • 进入当前运行的容器
  • 文件从容器内copy到主机上(手动命令行copy)
  • 保存与加载 SAVE LOAD
  • 可视化 Portainer
  • 安装
  • 具体使用参考文章
  • Commit镜像
  • 运行一个centos
  • 做一些修改操作
  • 退出容器
  • 提交
  • 数据卷使用
  • 方式一:直接使用命令挂 -v
  • 实战:Mysql数据卷挂载
  • 方式二:具名挂载、匿名挂载
  • 匿名挂载
  • 具名挂载
  • 指定目录、具名、匿名三者区别
  • volume 容器内卷信息查看
  • volume ls 查看所有卷
  • volume inspect $VOLUM_NAME 查看卷信息
  • 扩展:指定容器内目录权限
  • DockerFile挂载volume
  • 容器之间目录文件共享 --volumes-from
  • DockerFile
  • DockerFile指令
  • 创建一个CentOS
  • 查看我们镜像的变更记录
  • DockerFile制作Java项目启动
  • 发布镜像
  • 发布镜像到DockerHub
  • 发布镜像到阿里云容器服务
  • 自定义网络
  • 多个自定义网络连通
  • network connect 连通
  • 实战
  • Docker 配置Redis集群


安装

官方安装文档

地址:https://docs.docker.com/engine/install/centos/ 这里使用Linux安装

Docker入门到精通开发指南(一文搞懂)_mysql

具体安装步骤

1.卸载之前的版本(如果之前未用过忽略该步骤)

yum remove docker \
                  docker-client \
                  docker-client-latest \
                  docker-common \
                  docker-latest \
                  docker-latest-logrotate \
                  docker-logrotate \
                  docker-engine

2.安装相关依赖

yum install -y yum-utils

3.设置docker镜像

yum-config-manager \
    --add-repo \
    https://download.docker.com/linux/centos/docker-ce.repo

阿里云

yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo

4.安装docker

安装latest版本
yum install -y docker-ce docker-ce-cli containerd.io

这里会默认安装latest版本。

指定版本安装
  • 查看版本
> yum list docker-ce --showduplicates | sort -r
docker-ce.x86_64            3:20.10.9-3.el7                    docker-ce-stable 
docker-ce.x86_64            3:20.10.9-3.el7                    @docker-ce-stable
docker-ce.x86_64            3:20.10.8-3.el7                    docker-ce-stable 
docker-ce.x86_64            3:20.10.7-3.el7                    docker-ce-stable 
docker-ce.x86_64            3:20.10.6-3.el7                    docker-ce-stable 
docker-ce.x86_64            3:20.10.5-3.el7                    docker-ce-stable 
docker-ce.x86_64            3:20.10.4-3.el7                    docker-ce-stable 
docker-ce.x86_64            3:20.10.3-3.el7                    docker-ce-stable
...
  • 指定版本安装
sudo yum install docker-ce-<VERSION_STRING> docker-ce-cli-<VERSION_STRING> containerd.io

example:

docker-ce-18.09.1

5.启动docker

systemctl start docker

6.查看docker版本

> docker version
Client: Docker Engine - Community
 Version:           20.10.9
 API version:       1.41
 Go version:        go1.16.8
 Git commit:        c2ea9bc
 Built:             Mon Oct  4 16:08:14 2021
 OS/Arch:           linux/amd64
 Context:           default
 Experimental:      true

Server: Docker Engine - Community
 Engine:
  Version:          20.10.9
  API version:      1.41 (minimum version 1.12)
  Go version:       go1.16.8
  Git commit:       79ea9d3
  Built:            Mon Oct  4 16:06:37 2021
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          1.4.11
  GitCommit:        5b46e404f6b9f661a205e28d59c982d3634148f8
 runc:
  Version:          1.0.2
  GitCommit:        v1.0.2-0-g52b36a2
 docker-init:
  Version:          0.19.0
  GitCommit:        de40ad0

7.运行一个docker hello world

docker run hello-world

Docker入门到精通开发指南(一文搞懂)_mysql_02

8.卸载docker

yum remove docker-ce docker-ce-cli containerd.io
rm -rf /var/lib/docker
rm -rf /var/lib/containerd

9.配置阿里云镜像加速地址

登录阿里云->点击容器镜像服务

Docker入门到精通开发指南(一文搞懂)_mysql_03


点击镜像加速器

Docker入门到精通开发指南(一文搞懂)_centos_04

服务器配置,重启生效

sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF'
{
  "registry-mirrors": ["https://${自己的id}.mirror.aliyuncs.com"]
}
EOF
sudo systemctl daemon-reload
sudo systemctl restart docker

docker常用命令

docker仓库搜索

https://hub.docker.com/search?q=&type=image

基础命令
docker版本信息
docker version
docker系统信息
docker info
镜像命令
查看本地主机上所有镜像
[root@test11 ~]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
hello-world   latest    feb5d9fea6a5   3 weeks ago    13.3kB
redis         latest    621ceef7494a   9 months ago   104MB

# 说明
REPOSITORY	镜像的仓库源
TAG	镜像的标签
IMAGE ID	镜像的id
CREATED	镜像创建的时间
SIZE	镜像的大小

# 其他指令
Options:
  -a, --all             列出所有镜像
  -q, --quiet          只显示镜像id
搜索镜像
[root@test11 ~]# docker search mysql
NAME                              DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
mysql                             MySQL is a widely used, open-source relation…   11551     [OK]       
mariadb                           MariaDB Server is a high performing open sou…   4398      [OK]
下载镜像

docker pull 镜像名[:TAG]

[root@test11 ~]# docker pull mysql
Using default tag: latest
latest: Pulling from library/mysql
b380bbd43752: Pull complete 
f23cbf2ecc5d: Pull complete 
30cfc6c29c0a: Pull complete 
b38609286cbe: Pull complete 
8211d9e66cd6: Pull complete 
2313f9eeca4a: Pull complete 
7eb487d00da0: Pull complete 
4d7421c8152e: Pull complete 
77f3d8811a28: Pull complete 
cce755338cba: Pull complete 
69b753046b9f: Pull complete 
b2e64b0ab53c: Pull complete 
Digest: sha256:6d7d4524463fe6e2b893ffc2b89543c81dec7ef82fb2020a1b27606666464d87
Status: Downloaded newer image for mysql:latest
docker.io/library/mysql:latest

docker pull mysql 与 docker pull docker.io/library/mysql:latest 相同

  • 指定版本下载
docker pull mysql:5.7
删除镜像
docker rmi -f IMAGEID|镜像名称 #空格可以删除多个镜像
批量删除镜像
docker rmi -f ${docker images -qa}
容器命令
下载centos进行测试
下载
[root@test11 ~]# docker pull centos
Using default tag: latest
latest: Pulling from library/centos
a1d0c7532777: Pull complete 
Digest: sha256:a27fd8080b517143cbbbab9dfb7c8571c40d67d534bbdee55bd6c473f432b177
Status: Downloaded newer image for centos:latest
docker.io/library/centos:latest
启动
docker run [可选参数] iamge

# 参数说明
--name="Name01"	容器名称 app01 app02,用来区分启动的容器
-d	后台方式运行
-it	使用交互方式运行,进入容器查看内容
-p	指定容器的端口
	-p	主机端口:容器端口	(常用)
	-p	容器端口
-P	


# 启动并进入centos
docker run -it 5d0da3dc9764 /bin/bash
或
docker run -it centos /bin/bash

#退出容器
exit
查看正在运行的docker
docker ps

-a 查看历史运行过的docker
-n=? 显示最近的容器数量
-q	只显示容器的编号
退出容器
exit 退出并停止程序
ctrl + P + Q 容器不停止退出
删除容器
docker rm -f 容器id
docker rm -f  ${docker ps -qa}

# -f 可以删除在运行的容器,不使用-f只能删除未在运行的容器
启动和停止
docker start 容器id	# 启动
docker stop 容器id	# 停止
docker restart 容器id	# 重启
docker kill 容器id	# 强制停止
常用其他命令
查看日志
# docker logs --help

Usage:	docker logs [OPTIONS] CONTAINER

Fetch the logs of a container

Options:
      --details        Show extra details provided to logs
  -f, --follow         Follow log output
      --since string   Show logs since timestamp (e.g. 2013-01-02T13:23:37) or relative (e.g. 42m for 42 minutes)
      --tail string    Number of lines to show from the end of the logs (default "all")
  -t, --timestamps     Show timestamps
      --until string   Show logs before a timestamp (e.g. 2013-01-02T13:23:37) or relative (e.g. 42m for 42 minutes)
滚动查看日志,并且打印时间
> docker logs -f --tail 10 -t  ${容器id}
查看容器内部进程信息
docker top 容器ID
查看docker原信息
docker inspect 容器id
进入当前运行的容器

方法1(常用)

docker exec -it 容器id /bin/bash
# 进入容器后开启一个新的终端

方法2

docker attach 容器id
# 进入当前正在执行的终端
文件从容器内copy到主机上(手动命令行copy)
docker cp 容器id:容器内路径 目的主机路径
保存与加载 SAVE LOAD

保存

docker save 963d2d22e6e3 > kafka-eagle-2.0.1-docker.tar

加载

docker load < kafka-eagle-2.0.1-docker.tar 
# 加载完成后可以查看到
docker images

可视化 Portainer

安装

docker run -d -p 9000:9000 -v /root/portainer:/data -v /var/run/docker.sock:/var/run/docker.sock --name portainer portainer/portainer

具体使用参考文章

点击这里

Commit镜像

主要作用是将自己修改过的一些配置、文件等,提交成一个自己的镜像,类似于快照的功能。供自己后续使用。

这里用docker centos进行测试,我们再centos中加一些文件,然后commit成一个新的镜像。

运行一个centos

docker run -it centos /bin/bash

做一些修改操作

# 默认没有安装vim
[root@f383457af325 /]# vim    
bash: vim: command not found
# 我们安装下vim
[root@f383457af325 /]# yum install vim 
# 再新增一个文件
[root@f383457af325 ~]# echo '123' > commit-test.txt

退出容器

ctrl + p + q

提交

语法

docker commit [OPTIONS] CONTAINERID [REPOSITORY[:TAG]]

OPTIONS说明:

    -a :提交的镜像作者;

    -c :使用Dockerfile指令来创建镜像;

    -m :提交时的说明文字;

    -p :在commit时,将容器暂停。

CONTAINERID 是运行容器ID

[root@test11 ~]# docker commit -a "jast" -m "测试commit" f383457af325  test:v1.0.0
sha256:43f512a896d965ad26f9defb9194b1ce87489d2090f2f72e7ed7f4caef1ae908

commit后查看下提交后的image,此时镜像就提交成功。

[root@test11 ~]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED          SIZE
test          v1.0.0    43f512a896d9   29 seconds ago   304MB

启动commit后的镜像进行验证镜像是否为我们提交时的状态

# 运行我们commit的images
[root@test11 ~]# docker run -it 43f512a896d9 /bin/bash
[root@588a36c75d1e /]# cd
# 查看我们保存的文件,发现文件与内容都相同
[root@588a36c75d1e ~]# ls
anaconda-ks.cfg  anaconda-post.log  commit-test.txt  original-ks.cfg
[root@588a36c75d1e ~]# cat commit-test.txt 
123

文件内容都为之前我们保存的内容,说明我们commit生效

数据卷使用

将容器内的目录挂在到Linux,例将容器内的数据库数据存储目录放在Linux中,而不是容器中。

方式一:直接使用命令挂 -v

docker run -it -v 主机目录:容器内目录 [-v 主机目录:容器内目录]

1.主机目录不存在则会自动创建
2.修改是双向的,即双向绑定/同步的概念,在linux中直接修改主机目录下的文件,容器内也会同步修改。即便是容器停止,我们再Linux中修改文件,容器再次启动容器内也会修改。
查看容器挂载信息 Mounts

docker inspect 0b1f6a469354

...
"Mounts": [
            {
                "Type": "bind",
                "Source": "/home/testtest",
                "Destination": "/home",
                "Mode": "",
                "RW": true,
                "Propagation": "rprivate"
            }
        ],
...

实战:Mysql数据卷挂载

[root@test11 ~]# docker run -d -p 3333:3306 -v /home/mysql/conf:/etc/mysql/conf.d -v /home/mysql/data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=123456 --name mysql01 mysql:5.7
83f08abd501cf0ae1bdc6adec5f4e3fc247abd081eb9ae0ec1d04d6b370828e8
  1. 挂载配置文件目录 -v /home/mysql/conf:/etc/mysql/conf.d
  2. 挂载数据目录 -v /home/mysql/data:/var/lib/mysql
  3. 指定密码 -e MYSQL_ROOT_PASSWORD=123456
  4. 执行容器名称 --name mysql01

服务器中测试连接

Docker入门到精通开发指南(一文搞懂)_mysql_05

查看Linux挂载的目录,初始化的数据都存在

[root@test11 data]# ls
auto.cnf    client-cert.pem  ibdata1      ibtmp1              private_key.pem  server-key.pem
ca-key.pem  client-key.pem   ib_logfile0  mysql               public_key.pem   sys
ca.pem      ib_buffer_pool   ib_logfile1  performance_schema  server-cert.pem
[root@test11 data]# pwd
/opt/docker/mysql/data

在mysql中创建数据库test_001,查看linux目录也同时存在,说明数据卷挂载成功

[root@test11 data]# ls
auto.cnf    client-cert.pem  ibdata1      ibtmp1              private_key.pem  server-key.pem
ca-key.pem  client-key.pem   ib_logfile0  mysql               public_key.pem   sys
ca.pem      ib_buffer_pool   ib_logfile1  performance_schema  server-cert.pem  test_001

方式二:具名挂载、匿名挂载

匿名挂载

-v 容器内路径
docker run -d -P --name nginx01 -v /etc/nginx nginx

具名挂载

-v 名称:容器内路径
docker run -d -P --name nginx02 -v jmgz:/etc/nginx nginx

指定目录、具名、匿名三者区别

-v 容器内路径	# 匿名挂载
-v 卷名:容器内路径	# 具名挂载
-v /Linux路径:容器内路径	# 指定路径挂载(使用volume查看不到)

docker run -d -P --name nginx02 -v /home/nginx:/etc/nginx nginx
docker run -d -P --name nginx02 -v jmgz:/etc/nginx nginx
docker run -d -P --name nginx02 -v /etc/nginx nginx

指定目录以/开头
具名为名称开头
匿名只有一个容器内部的目录

volume 容器内卷信息查看

volume ls 查看所有卷
[root@test11 volumes]# docker volume ls 
DRIVER    VOLUME NAME
local     9c5d88889544e28e1268853fd91705401b29a80394bae71ebe1243d66d9f9243
local     325c6c6fcb0079b2ef18c573d3e76bf0186b8fdd610269f19f2e83ccfe53d7c8
local     b24d3abe53938a464810c298f9c02117c686d7fc06c4917932fd69f7e9ded284
local     b35cf901596e7bec2dd6244a28873a3b885fc6e4b429e8e27af9629e74884abe
local     jmgz
volume inspect $VOLUM_NAME 查看卷信息
[root@test11 volumes]# docker volume inspect jmgz
[
    {
        "CreatedAt": "2021-10-21T11:30:13+08:00",
        "Driver": "local",
        "Labels": null,
        "Mountpoint": "/var/lib/docker/volumes/jmgz/_data",
        "Name": "jmgz",
        "Options": null,
        "Scope": "local"
    }
]
扩展:指定容器内目录权限
# -v 容器内路径:ro rw 改变读写权限
ro	readonly # 只读
rw readwrite	# 读写

docker run -d -P --name nginx02 -v jmgz:/etc/nginx:ro nginx
docker run -d -P --name nginx02 -v jmgz:/etc/nginx:rw nginx

# ro 设置之后容器对容器内的文件只有读的权限,需要修改只能通过Linux中进行操作
DockerFile挂载volume

具体内容在下面DockerFile中介绍
创建一个文件,名称随意,内容如下

FROM centos
# 通过DockerFile挂载
VOLUME ["volume01","volume02"]

CMD /bin/bash

build

[root@test16 docker]# docker build -f ./build.txt  -t jast/centos:1.0 .
Sending build context to Docker daemon  2.048kB
Step 1/3 : FROM centos
 ---> 5d0da3dc9764
Step 2/3 : VOLUME ["volume01","volume02"]
 ---> Running in 66d549a0c6dd
Removing intermediate container 66d549a0c6dd
 ---> 1f81b9a8505c
Step 3/3 : CMD /bin/bash
 ---> Running in 04b134fc3f1e
Removing intermediate container 04b134fc3f1e
 ---> 61380fa83790
Successfully built 61380fa83790
Successfully tagged jast/centos:1.0

查看我们生成的镜像

[root@test16 docker]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED          SIZE
jast/centos   1.0       61380fa83790   40 seconds ago   231MB
centos        latest    5d0da3dc9764   5 weeks ago      231MB

进入容器内查看到我们挂载的目录,volume01,volume01

[root@test16 docker]# docker run -it 61380fa83790 /bin/bash
[root@c04e995e2ed0 /]# ls
bin  etc   lib	  lost+found  mnt  proc  run   srv  tmp  var	   volume02
dev  home  lib64  media       opt  root  sbin  sys  usr  volume01

查看我们挂载的目录

> docker inspect 7bc94d570d32
...
"Mounts": [
            {
                "Type": "volume",
                "Name": "e60e87be382e28ddbc6c03782823c31e12e9bbf50b5931a86c9f0743897a056c",
                "Source": "/var/lib/docker/volumes/e60e87be382e28ddbc6c03782823c31e12e9bbf50b5931a86c9f0743897a056c/_data",
                "Destination": "volume01",
                "Driver": "local",
                "Mode": "",
                "RW": true,
                "Propagation": ""
            },
            {
                "Type": "volume",
                "Name": "a521e7ac3b134f953d1b7e63c1fc596e10ab9236ca959f97cab8f0ea92d2f79d",
                "Source": "/var/lib/docker/volumes/a521e7ac3b134f953d1b7e63c1fc596e10ab9236ca959f97cab8f0ea92d2f79d/_data",
                "Destination": "volume02",
                "Driver": "local",
                "Mode": "",
                "RW": true,
                "Propagation": ""
            }
        ]
        ...
容器之间目录文件共享 --volumes-from

主要应用场景:比如我们配置文件共享

# 运行第一个centos容器(上一个步骤的生成的镜像挂载了两个目录volume01,volume02)
> docker run -it 61380fa83790 /bin/bash
# 运行第二个容器,通过--volumes-from与01的容器数据卷共享
> docker run -it --name docker02 --volumes-from ${继承的挂载volumes} ${需要闯将的images}
> docker run -it --name docker02 --volumes-from 7bc94d570d32 centos

在docker02中写入数据,然后在docker01中查看发现可以正常看到

[root@test16 ~]# docker attach 7bc94d570d32
[root@7bc94d570d32 /]# ls
bin  etc   lib	  lost+found  mnt  proc  run   srv  tmp  var	   volume02
dev  home  lib64  media       opt  root  sbin  sys  usr  volume01
[root@7bc94d570d32 /]# cd volume01/
[root@7bc94d570d32 volume01]# ls
[root@7bc94d570d32 volume01]# touch 123
[root@7bc94d570d32 volume01]# ls 
123

# 另外一个docker
[root@0e37a1ad8df4 /]# cd volume01/
[root@0e37a1ad8df4 volume01]# ls
123

多个容器之间也可以通过该方法进行数据共享,同时删除某一个容器,其他容器数据是不会删除的。(数据时间是复制同步关系)

DockerFile

Dockerfile是一个包含用于组合映像的命令的文本文档。可以使用在命令行中调用任何命令。 Docker通过读取Dockerfile中的指令自动生成映像。

DockerFile:构建文件
DockerImages:通过DockerFile构建生成的镜像,最终发布和运行
Docker 容器:容器是镜像运行起来提供服务的

DockerFile指令

指令

说明

FROM

基础镜镜像

MAINTAINER

镜像作者信息

RUN

镜像构建的时候需要运行的命令

ADD

COPY文件,会自动解压

WORKDIR

镜像的工作目录

VOLUME

挂载的目录

EXPOSE

暴露端口配置,这里配置了就不需要在启动时使用-p进行配置

CMD

指定这个容器启动的时候曼运行的命令,只有最后一个会生效,可被替代

ENTRYPOINT

与CMD类似,指定这个容器启动的时候要运行的命令,可以追加命令

ONBUILD

当构建一个被继承DockerFile 这个时候就会运行ONBUILD 的指令。触发指令。

COPY

类似ADD。将我们文件拷贝到镜像中

ENV

构建的时候设置环境变量

创建一个CentOS

我们在基础的centos中安装vim与ifconfig命令

# 集成centos基础版本
FROM centos
# 作者信息
MAINTAINER jast
# 设置工作目录,即进入容器后默认目录
ENV MYPATH /usr/local
#
WORKDIR $MYPATH

RUN yum -y install vim
RUN yum -y install net-tools

EXPOSE 80

CMD echo $MYPATH
CMD /bin/bash

build

docker build -f ./centos.dockerfile -t jast-centos:0.0.1 .

-f centos.dockerfile是指定我们dockerfile文件,如果我们文件命名为Dockerfile 则不用指定 -f,系统会默认获取该文件

我们进入我们创建好的centos,发现进入容器后,当前目录为我们刚刚设置的工作目录;vim与ifconfig命令都可以使用,说明我们的设置生效

[root@test16 docker]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED          SIZE
jast-centos   0.0.1     0eb128178c9e   14 minutes ago   336MB
jast/centos   1.0       61380fa83790   18 hours ago     231MB
centos        latest    5d0da3dc9764   5 weeks ago      231MB
[root@test16 docker]# docker run -it 0eb128178c9e /bin/bash
[root@2689dd9fc60e local]# pwd
/usr/local
[root@2689dd9fc60e local]# echo $MYPATH
/usr/local
[root@2689dd9fc60e local]# ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 172.17.0.4  netmask 255.255.0.0  broadcast 172.17.255.255
        ether 02:42:ac:11:00:04  txqueuelen 0  (Ethernet)
        RX packets 8  bytes 648 (648.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        loop  txqueuelen 1  (Local Loopback)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

查看我们镜像的变更记录

docker history $IMAGEID

[root@test16 docker]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED          SIZE
jast-centos   0.0.1     0eb128178c9e   21 minutes ago   336MB
jast/centos   1.0       61380fa83790   18 hours ago     231MB
centos        latest    5d0da3dc9764   5 weeks ago      231MB
[root@test16 docker]# docker history 0eb128178c9e
IMAGE          CREATED          CREATED BY                                      SIZE      COMMENT
0eb128178c9e   21 minutes ago   /bin/sh -c #(nop)  CMD ["/bin/sh" "-c" "/bin…   0B        
62a81bb2ccbb   21 minutes ago   /bin/sh -c #(nop)  CMD ["/bin/sh" "-c" "echo…   0B        
b243f2d95c88   21 minutes ago   /bin/sh -c #(nop)  EXPOSE 80                    0B        
37365b1cd9f0   21 minutes ago   /bin/sh -c yum -y install net-tools             32.4MB    
0d1152378bdc   21 minutes ago   /bin/sh -c yum -y install vim                   72.7MB    
dcf50fca935d   29 minutes ago   /bin/sh -c #(nop) WORKDIR /usr/local            0B        
da408c837890   29 minutes ago   /bin/sh -c #(nop)  ENV MYPATH=/usr/local        0B        
45b873abd869   29 minutes ago   /bin/sh -c #(nop)  MAINTAINER jast              0B        
5d0da3dc9764   5 weeks ago      /bin/sh -c #(nop)  CMD ["/bin/bash"]            0B        
<missing>      5 weeks ago      /bin/sh -c #(nop)  LABEL org.label-schema.sc…   0B        
<missing>      5 weeks ago      /bin/sh -c #(nop) ADD file:805cb5e15fb6e0bb0…   231MB

CMD 与 ENTRYPOINT 区别

DockerFile制作Java项目启动

编写dockerfile

FROM centos
# 添加jdk,使用ADD docker会自动解压
ADD jdk-8u311-linux-x64.tar.gz /opt
# 将我们准备的java程序文件复制到容器内的/opt/app中
COPY app /opt/app

WORKDIR /opt/app

ENV JAVA_HOME /opt/jdk1.8.0_311
ENV CLASSPATH .:$CLASSPATH:$JAVA_HOME/lib
ENV PATH $PATH:$JAVA_HOME/bin

ENTRYPOINT ["java","-cp","lib/*:test.jar","jast.temp.PrintInfo"]

app目录

[root@test16 app]# ls -l
总用量 44
drwxr-xr-x. 2 root root  4096 10月 22 14:24 lib
drwxr-xr-x. 2 root root     6 10月 22 15:47 logs
-rw-r--r--. 1 root root    95 10月 22 15:49 run.sh
-rw-r--r--. 1 root root 33262 10月 22 14:24 test.jar

java文件中内容就是简单的输出日期,内容如下

public class PrintInfo {
    public static void main(String[] args) throws InterruptedException {
        while(true){
            System.out.println(new Date());
            Thread.sleep(1000);
        }
    }
}

build镜像

[root@test16 jast-springboot-docker]# docker build -t jast-test-docker .
Sending build context to Docker daemon  554.4MB
Step 1/8 : FROM centos
 ---> 5d0da3dc9764
Step 2/8 : ADD jdk-8u311-linux-x64.tar.gz /opt
 ---> 365ac8e7b845
Step 3/8 : COPY app /opt/app
 ---> bddc1407e654
Step 4/8 : WORKDIR /opt/app
 ---> Running in ba2637ebeefe
Removing intermediate container ba2637ebeefe
 ---> a6164e29c00c
Step 5/8 : ENV JAVA_HOME /opt/jdk1.8.0_311
 ---> Running in 89e6ab05eafa
Removing intermediate container 89e6ab05eafa
 ---> 3683f68f453b
Step 6/8 : ENV CLASSPATH .:$CLASSPATH:$JAVA_HOME/lib
 ---> Running in 3dc4b2664744
Removing intermediate container 3dc4b2664744
 ---> c34ccb48d6c0
Step 7/8 : ENV PATH $PATH:$JAVA_HOME/bin
 ---> Running in dd094c4d0722
Removing intermediate container dd094c4d0722
 ---> 6d9d3ba4b4f0
Step 8/8 : ENTRYPOINT ["java","-cp","lib/*:test.jar","jast.temp.PrintInfo"]
 ---> Running in 7c22e3aa6764
Removing intermediate container 7c22e3aa6764
 ---> ab512eecb1b7
Successfully built ab512eecb1b7
Successfully tagged jast-test-docker:latest

查看镜像

[root@test16 jast-springboot-docker]# docker images
REPOSITORY         TAG       IMAGE ID       CREATED         SIZE
jast-test-docker   latest    ab512eecb1b7   3 minutes ago   638MB
jast-centos        0.0.1     0eb128178c9e   3 hours ago     336MB

直接运行镜像,直接输出我们java程序中打印的内容

[root@test16 jast-springboot-docker]# docker run -it jast-test-docker 
Fri Oct 22 06:41:19 UTC 2021
Fri Oct 22 06:41:20 UTC 2021
Fri Oct 22 06:41:21 UTC 2021
Fri Oct 22 06:41:22 UTC 2021
Fri Oct 22 06:41:23 UTC 2021
Fri Oct 22 06:41:24 UTC 2021

这里发现我们直接是打印的日志,我们稍微改动一下,让java程序在后台运行,日志输出到我们Linux服务器中

修改下配置文件

FROM centos

ADD jdk-8u311-linux-x64.tar.gz /opt

COPY app /opt/app

WORKDIR /opt/app

ENV JAVA_HOME /opt/jdk1.8.0_311
ENV CLASSPATH .:$CLASSPATH:$JAVA_HOME/lib
ENV PATH $PATH:$JAVA_HOME/bin

VOLUME ["/opt/app/logs"]

ENTRYPOINT ["sh","run.sh"]

run.sh内容为,可以通过脚本run.sh启动多个进程,但是必须有一个前台运行的进程,否则docker启动后会自动停止,这里我们使用的是tial -f

[root@test16 jast-springboot-docker]# cd app/
[root@test16 app]# ls
lib  logs  run.sh  test.jar
[root@test16 app]# cat run.sh 
nohup java -cp lib/*:test.jar jast.temp.PrintInfo > logs/result.log &
tail -f logs/result.log

build

docker build -t jast-test-docker:0.1.0 .

运行

查看我们挂载的日志目录

[root@test16 jast-springboot-docker]# docker inspect 8f06b7834337
...
"Mounts": [
            {
                "Type": "volume",
                "Name": "69ff1b332431a43e202cc0eb089b49f9944be5be88cc24a4b259f3606f693c21",
                "Source": "/var/lib/docker/volumes/69ff1b332431a43e202cc0eb089b49f9944be5be88cc24a4b259f3606f693c21/_data",
                "Destination": "/opt/app/logs",
                "Driver": "local",
                "Mode": "",
                "RW": true,
                "Propagation": ""
            }
        ]

查看Linux挂载出来的目录下的日志

[root@test16 app]# tailf /var/lib/docker/volumes/69ff1b332431a43e202cc0eb089b49f9944be5be88cc24a4b259f3606f693c21/_data/result.log 
Fri Oct 22 08:03:05 UTC 2021
Fri Oct 22 08:03:06 UTC 2021
Fri Oct 22 08:03:07 UTC 2021
Fri Oct 22 08:03:08 UTC 2021
Fri Oct 22 08:03:09 UTC 2021
Fri Oct 22 08:03:10 UTC 2021
Fri Oct 22 08:03:11 UTC 2021
Fri Oct 22 08:03:12 UTC 2021
Fri Oct 22 08:03:13 UTC 2021
Fri Oct 22 08:03:14 UTC 2021
Fri Oct 22 08:03:15 UTC 2021

进入容器查看容器内result.log日志,发现相同,说明我们创建成功。

[root@test16 app]# docker exec -it 8f06b7834337 /bin/bash
[root@8f06b7834337 app]# ls
lib  logs  run.sh  test.jar
[root@8f06b7834337 app]# tail -f logs/result.log 
Fri Oct 22 08:05:01 UTC 2021
Fri Oct 22 08:05:02 UTC 2021
Fri Oct 22 08:05:03 UTC 2021
Fri Oct 22 08:05:04 UTC 2021
Fri Oct 22 08:05:05 UTC 2021
Fri Oct 22 08:05:06 UTC 2021
Fri Oct 22 08:05:07 UTC 2021
Fri Oct 22 08:05:08 UTC 2021
Fri Oct 22 08:05:09 UTC 2021
Fri Oct 22 08:05:10 UTC 2021
Fri Oct 22 08:05:11 UTC 2021

发布镜像

发布镜像到DockerHub

发布本地的镜像
本地我们镜像命名可能会不规范,发布时想重新命名进行发布到DockerHub我们可以使用docker tag命令
格式
docker tag $IMAGEID $新的标签[:版本]docker tag 66c054090a43 jast/tag:1.0

[root@test16 ~]# docker images
REPOSITORY         TAG       IMAGE ID       CREATED             SIZE
jast-test-docker   0.1.0     66c054090a43   47 minutes ago      638MB
[root@test16 ~]# docker tag 66c054090a43 jast/tag:1.0
[root@test16 ~]# docker images
REPOSITORY         TAG       IMAGE ID       CREATED             SIZE
jast-test-docker   0.1.0     66c054090a43   47 minutes ago      638MB
jast/tag           1.0       66c054090a43   47 minutes ago      638MB

登录
(需要先进行账号注册,地址:https://hub.docker.com

docker login -u username

发布

docker push jast/tag:1.0

发布镜像到阿里云容器服务

  1. 登录阿里云进入镜像服务 创建命名空间

Docker入门到精通开发指南(一文搞懂)_docker_06

Docker入门到精通开发指南(一文搞懂)_centos_07

2. 创建镜像仓库

Docker入门到精通开发指南(一文搞懂)_centos_08

Docker入门到精通开发指南(一文搞懂)_docker_09

  1. 创建完成后会自动弹出说明
  2. 在Linux服务器中登录

登录阿里云Docker Registry

$ docker login --username=tb7****6464 registry.cn-hangzhou.aliyuncs.com

用于登录的用户名为阿里云账号全名,密码为开通服务时设置的密码。
您可以在访问凭证页面修改凭证密码。

登录成功

[root@test16 ~]# docker login --username=username registry.cn-hangzhou.aliyuncs.com
Password: 
WARNING! Your password will be stored unencrypted in /root/.docker/config.json.
Configure a credential helper to remove this warning. See
https://docs.docker.com/engine/reference/commandline/login/#credentials-store

Login Succeeded

push镜像到阿里云仓库
官方介绍如下

$ docker login --username=aliyunUsername registry.cn-hangzhou.aliyuncs.com
$ docker tag [ImageId] registry.cn-hangzhou.aliyuncs.com/jast-zsh/jast-test:[镜像版本号]
$ docker push registry.cn-hangzhou.aliyuncs.com/jast-zsh/jast-test:[镜像版本号]

请根据实际镜像信息替换示例中的[ImageId]和[镜像版本号]参数。

实际操作

[root@test16 ~]# docker images
REPOSITORY         TAG       IMAGE ID       CREATED        SIZE
jast-test-docker   0.1.0     66c054090a43   2 hours ago    638MB
[root@test16 ~]# docker tag 66c054090a43 registry.cn-hangzhou.aliyuncs.com/jast-zsh/jast-test:0.0.1
[root@test16 ~]# docker images
REPOSITORY                                             TAG       IMAGE ID       CREATED        SIZE
jast-test-docker                                       0.1.0     66c054090a43   2 hours ago    638MB
registry.cn-hangzhou.aliyuncs.com/jast-zsh/jast-test   0.0.1     66c054090a43   2 hours ago    638MB

# 上传到阿里云仓库
[root@test16 ~]# docker push registry.cn-hangzhou.aliyuncs.com/jast-zsh/jast-test:0.0.1
The push refers to repository [registry.cn-hangzhou.aliyuncs.com/jast-zsh/jast-test]
27b2dc42c067: Pushed 
7e28f1f4e30c: Pushed 
74ddd0ec08fa: Pushed 
0.0.1: digest: sha256:20d452aa1528bb8e1f236781a74b9e5e4af657470dfb6936af6dbc827923c5aa size: 954

在阿里云上查看镜像

Docker入门到精通开发指南(一文搞懂)_centos_10


Docker入门到精通开发指南(一文搞懂)_mysql_11


发现成功上传在Linux服务器上拉取镜像

Docker入门到精通开发指南(一文搞懂)_docker_12

官方介绍

$ docker pull registry.cn-hangzhou.aliyuncs.com/jast-zsh/jast-test:[镜像版本号]

实际拉取操作,可以看到我们拉取回来的镜像

[root@test16 ~]# docker pull registry.cn-hangzhou.aliyuncs.com/jast-zsh/jast-test:0.0.1
0.0.1: Pulling from jast-zsh/jast-test
a1d0c7532777: Already exists 
56ca049bf4be: Already exists 
524200aa718d: Already exists 
Digest: sha256:20d452aa1528bb8e1f236781a74b9e5e4af657470dfb6936af6dbc827923c5aa
Status: Downloaded newer image for registry.cn-hangzhou.aliyuncs.com/jast-zsh/jast-test:0.0.1
registry.cn-hangzhou.aliyuncs.com/jast-zsh/jast-test:0.0.1
[root@test16 ~]# docker images
REPOSITORY                                             TAG       IMAGE ID       CREATED        SIZE
registry.cn-hangzhou.aliyuncs.com/jast-zsh/jast-test   0.0.1     66c054090a43   2 hours ago    638MB

自定义网络

查看所有docker网络

[root@test16 ~]# docker network ls 
NETWORK ID     NAME      DRIVER    SCOPE
cadbbb004519   bridge    bridge    local
e678c05db7a8   host      host      local
d83c97dd3227   none      null      local

网络模式

网络模式

模式说明

bridge

桥接 docker默认

none

不配置网络

host

和宿主机共享网络

container

容器内网络互连

正常我们一台服务器两个不同容器之间可以通过ip ping通,但是无法ping 通服务器host(可以通过–link进行连接,一般不使用该方法比较麻烦);我们通过自己创建网络进行互联

创建网络

# 这里设置尽量设置一个不常用的ip,测试时候我使用了192.168.0.0/16,直接导致服务器网络连接不上,估计是冲突了~
[root@test16 ~]# docker network create --driver bridge --subnet 192.160.0.0/16 --gateway 192.160.0.1 mynet
3f0facb7582af42f42acb8e59c4bcc254d57de9425d8d7433beea00d92fcc52c

docker查看所有网络

[root@test16 ~]# docker network ls
NETWORK ID     NAME      DRIVER    SCOPE
cadbbb004519   bridge    bridge    local
e678c05db7a8   host      host      local
3f0facb7582a   mynet     bridge    local
d83c97dd3227   none      null      local

查看创建的网络详情

[root@test16 ~]# docker network inspect mynet
[
    {
        "Name": "mynet",
        "Id": "3f0facb7582af42f42acb8e59c4bcc254d57de9425d8d7433beea00d92fcc52c",
        "Created": "2021-10-22T20:58:28.703557023+08:00",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": {},
            "Config": [
                {
                    "Subnet": "192.160.0.0/16",
                    "Gateway": "192.160.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {},
        "Options": {},
        "Labels": {}
    }
]

创建两个镜像并使用我们自己创建的网络

[root@test16 ~]# docker run -d -P --name jast-net-01 --net mynet registry.cn-hangzhou.aliyuncs.com/jast-zsh/jast-test:0.0.1
6703b0bd420cc0c1c63a27a23a5d18dbef7534f5a90cb6d54c6b2bde494dd0f8
[root@test16 ~]# docker run -d -P --name jast-net-02 --net mynet registry.cn-hangzhou.aliyuncs.com/jast-zsh/jast-test:0.0.1
db3c9bf811cc5b111e95d3250f762ecaad75464f16722dc80b3f2ae4047c31a4

此时我们使用tomcate-net-01 可以直接通过host ping tomcat-net-02

[root@test16 ~]# docker exec -it jast-net-02 ping jast-net-01
PING jast-net-01 (192.160.0.5) 56(84) bytes of data.
64 bytes from jast-net-01.mynet (192.160.0.5): icmp_seq=1 ttl=64 time=0.047 ms
64 bytes from jast-net-01.mynet (192.160.0.5): icmp_seq=2 ttl=64 time=0.049 ms
--- jast-net-01 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1000ms
rtt min/avg/max/mdev = 0.047/0.048/0.049/0.001 ms
[root@test16 ~]# docker exec -it jast-net-01 ping jast-net-02
PING jast-net-02 (192.160.0.6) 56(84) bytes of data.
64 bytes from jast-net-02.mynet (192.160.0.6): icmp_seq=1 ttl=64 time=0.034 ms
64 bytes from jast-net-02.mynet (192.160.0.6): icmp_seq=2 ttl=64 time=0.062 ms
--- jast-net-02 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1000ms
rtt min/avg/max/mdev = 0.034/0.048/0.062/0.014 ms

多个自定义网络连通

问题:我们创建mynet,在mynet网络下的服务都是网络互通,如果我们再创建myent2。mynet与mynet2如何连通?

Docker入门到精通开发指南(一文搞懂)_mysql_13

network connect 连通

创建两个连接默认网络的镜像

[root@test16 ~]# docker run -d -P --name jast-01 registry.cn-hangzhou.aliyuncs.com/jast-zsh/jast-test:0.0.1
da7e002a63148a5a9cf930bce4643bfcb0b7ad2d7d02e9928c5405c35b892173
[root@test16 ~]# docker run -d -P --name jast-02 registry.cn-hangzhou.aliyuncs.com/jast-zsh/jast-test:0.0.1
c40f3f5afa686160142b15321a1c334e5bd017dde5e3611aab1ab0b88ce21f86

此时我们有四个容器在运行

[root@test16 ~]# docker ps 
CONTAINER ID   IMAGE                                                        COMMAND             CREATED              STATUS              PORTS                                         NAMES
c40f3f5afa68   registry.cn-hangzhou.aliyuncs.com/jast-zsh/jast-test:0.0.1   "sh run.sh"         About a minute ago   Up About a minute                                                 jast-02
da7e002a6314   registry.cn-hangzhou.aliyuncs.com/jast-zsh/jast-test:0.0.1   "sh run.sh"         About a minute ago   Up About a minute                                                 jast-01
db3c9bf811cc   registry.cn-hangzhou.aliyuncs.com/jast-zsh/jast-test:0.0.1   "sh run.sh"         7 minutes ago        Up 7 minutes                                                      jast-net-02
6703b0bd420c   registry.cn-hangzhou.aliyuncs.com/jast-zsh/jast-test:0.0.1   "sh run.sh"         7 minutes ago        Up 7 minutes                                                      jast-net-01

此时用jast-01 ping jast-net-01是不通的

[root@test16 ~]# docker exec -it jast-01 ping jast-net-01
ping: jast-net-01: Name or service not known

使用connect连接

[root@test16 ~]# docker network connect --help

Usage:  docker network connect [OPTIONS] NETWORK CONTAINER

Connect a container to a network

Options:
      --alias strings           Add network-scoped alias for the container
      --driver-opt strings      driver options for the network
      --ip string               IPv4 address (e.g., 172.30.100.104)
      --ip6 string              IPv6 address (e.g., 2001:db8::33)
      --link list               Add link to another container
      --link-local-ip strings   Add a link-local address for the container
docker network connect mynet jast-01

连通之后查看我们的网络信息

[root@test16 ~]# docker network inspect mynet

发现jast-01 已经在我们mynet网络下

Docker入门到精通开发指南(一文搞懂)_mysql_14


再次ping,发现网络已经通了

[root@test16 ~]# docker exec -it jast-01 ping jast-net-01
PING jast-net-01 (192.160.0.5) 56(84) bytes of data.
64 bytes from jast-net-01.mynet (192.160.0.5): icmp_seq=1 ttl=64 time=0.096 ms
64 bytes from jast-net-01.mynet (192.160.0.5): icmp_seq=2 ttl=64 time=0.043 ms

实战

Docker 配置Redis集群

我们要搭建的Redis集群为三主三从

Docker入门到精通开发指南(一文搞懂)_mysql_15

  1. 配置网络
[root@test16 ~]# docker network create --driver bridge --subnet 192.150.0.0/16 --gateway 192.150.0.1 redis-net
bbbed9e601f6d35212378762b857b9eaf752fbe6bb2d40cc1ac10346a9590015
  1. 使用脚本创建6个reids节点配置文件
for port in $(seq 1 6); \
do \
mkdir -p /home/jast/docker/redis/node-${port}/conf
touch /home/jast/docker/redis/node-${port}/conf/redis.conf
cat << EOF > /home/jast/docker/redis/node-${port}/conf/redis.conf
port 6379
bind 0.0.0.0
cluster-enabled yes
cluster-config-file nodes.conf
cluster-node-timeout 5000
cluster-announce-ip 192.150.0.1${port}
cluster-announce-port 6379
cluster-announce-bus-port 16379
appendonly yes
EOF
done
[root@test16 redis]# tree
.
├── create_conf.sh
├── node-1
│   └── conf
│       └── redis.conf
├── node-2
│   └── conf
│       └── redis.conf
├── node-3
│   └── conf
│       └── redis.conf
├── node-4
│   └── conf
│       └── redis.conf
├── node-5
│   └── conf
│       └── redis.conf
└── node-6
    └── conf
        └── redis.conf

12 directories, 7 files
  1. 创建6个容器
docker run -p 6371:6379 -p 16371:16379 --name redis-cluster-1 \
-v /home/jast/docker/redis/node-1/data:/data \
-v /home/jast/docker/redis/node-1/conf/redis.conf:/etc/redis/redis.conf \
-d --net redis-net --ip 192.150.0.11 redis redis-server /etc/redis/redis.conf

docker run -p 6372:6379 -p 16372:16379 --name redis-cluster-2 \
-v /home/jast/docker/redis/node-2/data:/data \
-v /home/jast/docker/redis/node-2/conf/redis.conf:/etc/redis/redis.conf \
-d --net redis-net --ip 192.150.0.12 redis redis-server /etc/redis/redis.conf

docker run -p 6373:6379 -p 16373:16379 --name redis-cluster-3 \
-v /home/jast/docker/redis/node-3/data:/data \
-v /home/jast/docker/redis/node-3/conf/redis.conf:/etc/redis/redis.conf \
-d --net redis-net --ip 192.150.0.13 redis redis-server /etc/redis/redis.conf

docker run -p 6374:6379 -p 16374:16379 --name redis-cluster-4 \
-v /home/jast/docker/redis/node-4/data:/data \
-v /home/jast/docker/redis/node-4/conf/redis.conf:/etc/redis/redis.conf \
-d --net redis-net --ip 192.150.0.14 redis redis-server /etc/redis/redis.conf

docker run -p 6375:6379 -p 16375:16379 --name redis-cluster-5 \
-v /home/jast/docker/redis/node-5/data:/data \
-v /home/jast/docker/redis/node-5/conf/redis.conf:/etc/redis/redis.conf \
-d --net redis-net --ip 192.150.0.15 redis redis-server /etc/redis/redis.conf

docker run -p 6376:6379 -p 16376:16379 --name redis-cluster-6 \
-v /home/jast/docker/redis/node-6/data:/data \
-v /home/jast/docker/redis/node-6/conf/redis.conf:/etc/redis/redis.conf \
-d --net redis-net --ip 192.150.0.16 redis redis-server /etc/redis/redis.conf
  1. 创建集群
    进入容器内部,执行redis-cli 命令初始化创建集群
# redis-cli --cluster create 192.150.0.11:6379 192.150.0.12:6379 192.150.0.13:6379 192.150.0.14:6379 192.150.0.15:6379 192.150.0.16:6379 --cluster-replicas 1
>>> Performing hash slots allocation on 6 nodes...
Master[0] -> Slots 0 - 5460
Master[1] -> Slots 5461 - 10922
Master[2] -> Slots 10923 - 16383
Adding replica 192.150.0.15:6379 to 192.150.0.11:6379
Adding replica 192.150.0.16:6379 to 192.150.0.12:6379
Adding replica 192.150.0.14:6379 to 192.150.0.13:6379
M: 2b1b770fcf8dd5cb230d0562aa17207d43e97587 192.150.0.11:6379
   slots:[0-5460] (5461 slots) master
M: 617a0c5fbba78c083f277f74cd799413a03c4c8c 192.150.0.12:6379
   slots:[5461-10922] (5462 slots) master
M: 2043ae4e89512f7a532e5ac6bacab9b7e32fb36d 192.150.0.13:6379
   slots:[10923-16383] (5461 slots) master
S: 9393eacec8f654913952819e6181d929a9536dc8 192.150.0.14:6379
   replicates 2043ae4e89512f7a532e5ac6bacab9b7e32fb36d
S: 018099d52339c4c417316027dcb7a7e8ee8ff930 192.150.0.15:6379
   replicates 2b1b770fcf8dd5cb230d0562aa17207d43e97587
S: 7c82f60bd2586d2c7249237d1e0383d82627a136 192.150.0.16:6379
   replicates 617a0c5fbba78c083f277f74cd799413a03c4c8c
Can I set the above configuration? (type 'yes' to accept): yes
>>> Nodes configuration updated
>>> Assign a different config epoch to each node
>>> Sending CLUSTER MEET messages to join the cluster
Waiting for the cluster to join
.
>>> Performing Cluster Check (using node 192.150.0.11:6379)
M: 2b1b770fcf8dd5cb230d0562aa17207d43e97587 192.150.0.11:6379
   slots:[0-5460] (5461 slots) master
   1 additional replica(s)
M: 2043ae4e89512f7a532e5ac6bacab9b7e32fb36d 192.150.0.13:6379
   slots:[10923-16383] (5461 slots) master
   1 additional replica(s)
S: 7c82f60bd2586d2c7249237d1e0383d82627a136 192.150.0.16:6379
   slots: (0 slots) slave
   replicates 617a0c5fbba78c083f277f74cd799413a03c4c8c
S: 9393eacec8f654913952819e6181d929a9536dc8 192.150.0.14:6379
   slots: (0 slots) slave
   replicates 2043ae4e89512f7a532e5ac6bacab9b7e32fb36d
S: 018099d52339c4c417316027dcb7a7e8ee8ff930 192.150.0.15:6379
   slots: (0 slots) slave
   replicates 2b1b770fcf8dd5cb230d0562aa17207d43e97587
M: 617a0c5fbba78c083f277f74cd799413a03c4c8c 192.150.0.12:6379
   slots:[5461-10922] (5462 slots) master
   1 additional replica(s)
[OK] All nodes agree about slots configuration.
>>> Check for open slots...
>>> Check slots coverage...
[OK] All 16384 slots covered.

创建成功,查看集群信息

127.0.0.1:6379> cluster info
cluster_state:ok
cluster_slots_assigned:16384
cluster_slots_ok:16384
cluster_slots_pfail:0
cluster_slots_fail:0
cluster_known_nodes:6
cluster_size:3
cluster_current_epoch:6
cluster_my_epoch:2
cluster_stats_messages_ping_sent:126
cluster_stats_messages_pong_sent:122
cluster_stats_messages_meet_sent:1
cluster_stats_messages_sent:249
cluster_stats_messages_ping_received:122
cluster_stats_messages_pong_received:127
cluster_stats_messages_received:249
127.0.0.1:6379> cluster nodes
2043ae4e89512f7a532e5ac6bacab9b7e32fb36d 192.150.0.13:6379@16379 master - 0 1634952993167 3 connected 10923-16383
9393eacec8f654913952819e6181d929a9536dc8 192.150.0.14:6379@16379 slave 2043ae4e89512f7a532e5ac6bacab9b7e32fb36d 0 1634952992000 3 connected
617a0c5fbba78c083f277f74cd799413a03c4c8c 192.150.0.12:6379@16379 master - 0 1634952992666 2 connected 5461-10922
2b1b770fcf8dd5cb230d0562aa17207d43e97587 192.150.0.11:6379@16379 master - 0 1634952992000 1 connected 0-5460
018099d52339c4c417316027dcb7a7e8ee8ff930 192.150.0.15:6379@16379 slave 2b1b770fcf8dd5cb230d0562aa17207d43e97587 0 1634952992164 1 connected
7c82f60bd2586d2c7249237d1e0383d82627a136 192.150.0.16:6379@16379 myself,slave 617a0c5fbba78c083f277f74cd799413a03c4c8c 0 1634952991000 2 connected

验证数据写入读取

127.0.0.1:6379> set k1 v1
-> Redirected to slot [12706] located at 192.150.0.13:6379
OK
192.150.0.13:6379> get k1
"v1"
192.150.0.13:6379> set k2 v2
-> Redirected to slot [449] located at 192.150.0.11:6379
OK
192.150.0.11:6379> get k1
-> Redirected to slot [12706] located at 192.150.0.13:6379
"v1"
192.150.0.13:6379> get k2
-> Redirected to slot [449] located at 192.150.0.11:6379
"v2"

验证集群
可以在上面set的k1发现,k1保存在了192.168.0.13docker容器上,我们把192.168.0.13停止,再试一下是否能读取成功。

[root@test16 ~]# docker stop 9e51b4ac3978
9e51b4ac3978
[root@test16 ~]# docker ps 
CONTAINER ID   IMAGE                                                        COMMAND                  CREATED          STATUS          PORTS                                                                                      NAMES
398e8e161ead   redis                                                        "docker-entrypoint.s…"   17 minutes ago   Up 17 minutes   0.0.0.0:6376->6379/tcp, :::6376->6379/tcp, 0.0.0.0:16376->16379/tcp, :::16376->16379/tcp   redis-cluster-6
3646b90381f8   redis                                                        "docker-entrypoint.s…"   17 minutes ago   Up 17 minutes   0.0.0.0:6375->6379/tcp, :::6375->6379/tcp, 0.0.0.0:16375->16379/tcp, :::16375->16379/tcp   redis-cluster-5
0e1864dd1a4b   redis                                                        "docker-entrypoint.s…"   17 minutes ago   Up 17 minutes   0.0.0.0:6374->6379/tcp, :::6374->6379/tcp, 0.0.0.0:16374->16379/tcp, :::16374->16379/tcp   redis-cluster-4
408bd068c495   redis                                                        "docker-entrypoint.s…"   17 minutes ago   Up 17 minutes   0.0.0.0:6372->6379/tcp, :::6372->6379/tcp, 0.0.0.0:16372->16379/tcp, :::16372->16379/tcp   redis-cluster-2
03493aa6f885   redis                                                        "docker-entrypoint.s…"   21 minutes ago   Up 21 minutes   0.0.0.0:6371->6379/tcp, :::6371->6379/tcp, 0.0.0.0:16371->16379/tcp, :::16371->16379/tcp   redis-cluster-1

停止之后我们再次get k1,发现从14上获取到了该信息,说明我们集群设置成功

192.150.0.11:6379> get k1
-> Redirected to slot [12706] located at 192.150.0.14:6379
"v1"

在集群的节点信息中也可以看到13停止服务,master切换到了14

192.150.0.14:6379> cluster nodes
2043ae4e89512f7a532e5ac6bacab9b7e32fb36d 192.150.0.13:6379@16379 master,fail - 1634953189076 1634953186565 3 connected
9393eacec8f654913952819e6181d929a9536dc8 192.150.0.14:6379@16379 myself,master - 0 1634953282000 7 connected 10923-16383
018099d52339c4c417316027dcb7a7e8ee8ff930 192.150.0.15:6379@16379 slave 2b1b770fcf8dd5cb230d0562aa17207d43e97587 0 1634953285000 1 connected
617a0c5fbba78c083f277f74cd799413a03c4c8c 192.150.0.12:6379@16379 master - 0 1634953286400 2 connected 5461-10922
7c82f60bd2586d2c7249237d1e0383d82627a136 192.150.0.16:6379@16379 slave 617a0c5fbba78c083f277f74cd799413a03c4c8c 0 1634953286000 2 connected
2b1b770fcf8dd5cb230d0562aa17207d43e97587 192.150.0.11:6379@16379 master - 0 1634953285397 1 connected 0-5460