根据以下学习视频,个人整理的笔记

https://www.bilibili.com/video/BV1og4y1q7M4?spm_id_from=333.999.0.0&vd_source=7a8946d22777450e46486d5fd60d8d4d

https://www.bilibili.com/video/BV1kv411q7Qc?spm_id_from=333.999.0.0

Docker概述

Docker为什么出现?

一款产品:开发、上线(两套环境部署)

开发------运维

环境配置是十分麻烦的,每一个机器都要部署环境!费时费力!

发布一个项目(jar包+环境(Redis、MySQL、JDK、等等)),项目能不能都带上环境安装打包?

之前在服务器配置一个应用的环境,配置超级麻烦,不能够跨平台。

传统:开发人员发jar包,运维人员来部署环境

现在:开发人员打包部署上线,一套流程做完!

Docker给以上的问题,提出了解决方案!

Docker的思想就来自于集装箱:打包装箱,每个箱子是互相隔离的。Docker通过隔离机制,可以将服务器利用到极致!!!

在这里插入图片描述

java —> jar、环境 —> 带上环境打包项目(镜像) —> Docker仓库 —> 运维人员从仓库中下载我们发布的镜像 —> 直接运行即可

本质:所有的技术都是因为出现了一些问题,我们需要去解决,才去学习

Docker的历史

2010年,几个搞IT的年轻人,就在美国成立了一家公司,名字叫dotCloud。主要是做一些pass的云计算服务!Linux虚拟机相关的容器技术!他们将自己的技术(容器技术)命名为Docker!

Docker刚刚诞生的时候,没有引起行业的注意!dotCloud这家公司就活不下去了!2013年,将Docker开源!越来越多的人开始发现Docker的优点。所以就火了!开源后,Docker每一个月都会更新一个版本。

2014年4月,Docker1.0发布!

Docker为什么这么火呢?因为Docker十分的轻巧,在容器技术出来之前,我们都是使用虚拟机技术(笨重)。

虚拟机(笨重)是属于虚拟化技术,Docker容器技术(轻巧)也是一种虚拟化技术!

虚拟机:下载一个原生镜像(相当于一个完整的电脑),几个G,十分的笨重,启动很慢

Docker:下载一个镜像(只包含最核心的环境),几百兆,十分的小巧,启动很快

到现在,所有开发人员都必须要会Docker!

Docker是基于Go语言开发的,开源项目

Docker官网:www.docker.com

Docker文档地址:https://docs.docker.com

Docker仓库地址:https://hub.docker.com

Docker能干嘛?

传统的虚拟机的方式

在这里插入图片描述

虚拟机技术的缺点:

1、资源占用十分多

2、冗余步骤多

3、启动很慢

容器化技术

在这里插入图片描述

容器化技术不是模拟一个完整的操作系统

比较Docker和虚拟机技术的不同

  • 传统虚拟机,虚拟出一套操作系统,运行一个完整的操作系统,然后在这个系统上安装和运行软件
  • Docker容器内的应用是直接运行在宿主机的内核上,容器是没有自己的内核的,没有虚拟操作系统,所以就十分轻便!而且每个容器间是互相隔离的,每个容器内都有一个属于自己的文件系统,互不影响

DevOps(开发、运维)

  • 传统方式:一堆帮助文档,安装程序

  • Docker:打包镜像,发布测试,一键运行。在容器化之后,我们的开发和测试环境是高度一致的

    • 保证应用更快速地交付和部署
    • 更便捷的升级和扩缩容
    • 更简单的系统运维
    • 更高效的计算资源利用

Docker的基本组成

在这里插入图片描述

镜像(image):

Docker镜像就好比是一个模板,可以通过这个模板来创建容器服务,最终服务运行或者项目运行就是在容器中的

容器(container):

Docker利用容器技术,独立运行一个或者一组应用,容器是通过镜像来创建的

仓库(repository):

Docker仓库就是存放镜像的地方

仓库分为公有仓库和私有仓库

DockerHub默认是国外的,阿里云也有容器服务(需要配置镜像加速!)

Docker安装

先使用Xshell连接阿里云服务器,查看系统相关环境

# 系统内核是 3.10 以上的
[root@iZwz9cj1ytrolpgw50tiksZ /]# uname -r
3.10.0-1062.18.1.el7.x86_64
# 系统版本
[root@iZwz9cj1ytrolpgw50tiksZ /]# cat /etc/os-release 
NAME="CentOS Linux"
VERSION="7 (Core)"
ID="centos"
ID_LIKE="rhel fedora"
VERSION_ID="7"
PRETTY_NAME="CentOS Linux 7 (Core)"
ANSI_COLOR="0;31"
CPE_NAME="cpe:/o:centos:centos:7"
HOME_URL="https://www.centos.org/"
BUG_REPORT_URL="https://bugs.centos.org/"

CENTOS_MANTISBT_PROJECT="CentOS-7"
CENTOS_MANTISBT_PROJECT_VERSION="7"
REDHAT_SUPPORT_PRODUCT="centos"
REDHAT_SUPPORT_PRODUCT_VERSION="7"

安装Docker

# 1、先卸载旧的版本
 yum remove docker \
                  docker-client \
                  docker-client-latest \
                  docker-common \
                  docker-latest \
                  docker-latest-logrotate \
                  docker-logrotate \
                  docker-engine

在这里插入图片描述

# 如果没有安装gcc的环境还需要先安装
# yum -y install gcc 
# yum -y install gcc-c++
###################################
# 2、安装需要的安装包
 yum install -y yum-utils
# 3、Docker仓库默认是国外的,速度十分慢,我们自己设置国内的镜像仓库,推荐使用阿里云镜像
 yum-config-manager \
    --add-repo \
    http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
# 4、更新软件包索引
 yum makecache fast
# 5、安装最新版的Docker引擎相关的内容
 yum install docker-ce docker-ce-cli containerd.io docker-compose-plugin
# 6、启动Docker
 systemctl start docker
# 7、查看Docker的版本信息
 docker version
# 8、测试
 docker run hello-world
# 9、查看一下 hello-world 镜像
 docker images

在这里插入图片描述

卸载Docker

# 1、卸载依赖
 yum remove docker-ce docker-ce-cli containerd.io docker-compose-plugin
# 2、删除资源
 rm -rf /var/lib/docker
 rm -rf /var/lib/containerd
 
 
 
/var/lib/docker # 这是Docker的默认工作路径

阿里云镜像加速

1、登录阿里云,找到容器镜像服务

在这里插入图片描述

2、找到镜像加速地址

在这里插入图片描述

3、配置使用,一共四条命令,依次执行即可!

sudo mkdir -p /etc/docker

sudo tee /etc/docker/daemon.json <<-'EOF'
{
  "registry-mirrors": ["https://o7f5db09.mirror.aliyuncs.com"]
}
EOF

sudo systemctl daemon-reload

sudo systemctl restart docker

分析HelloWorld镜像执行的流程

在这里插入图片描述

底层原理

Docker是怎么样工作的?

Docker是一个Client-Server结构的系统,Docker的守护进程运行在主机上。通过Socket从客户端访问!

DockerServer接收到DockerClient的指令,就会执行这个命令!

在这里插入图片描述

Docker为什么比虚拟机快?

1、Docker有着比虚拟机更少的抽象层。

2、Docker利用的是宿主机的内核,虚拟机需要的是Guest OS

在这里插入图片描述

所以说,新建一个容器的时候,docker不需要像虚拟机那样重新加载一个操作系统内核,而是直接利用宿主机的操作系统,十分地快

Docker常用命令

帮助命令

docker version # 显示docker的版本信息

docker info # 显示docker的系统信息,包括镜像和容器的数量

docker --help # 查看docker的所有命令

帮助文档的地址:https://docs.docker.com/engine/reference/commandline/docker

镜像命令

  • 查看镜像
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker images # 查看本地主机上的所有镜像
REPOSITORY    TAG       IMAGE ID       CREATED         SIZE
hello-world   latest    feb5d9fea6a5   10 months ago   13.3kB

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

===========================================================================================
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker images --help

Usage:  docker images [OPTIONS] [REPOSITORY[:TAG]]

List images

Options:
  -a, --all             Show all images (default hides intermediate images)
      --digests         Show digests
  -f, --filter filter   Filter output based on conditions provided
      --format string   Pretty-print images using a Go template
      --no-trunc        Don't truncate output
  -q, --quiet           Only show image IDs

# 可选项解释
Options:
  -a, --all             # 列出所有镜像
      --digests         Show digests
  -f, --filter filter   Filter output based on conditions provided
      --format string   Pretty-print images using a Go template
      --no-trunc        Don't truncate output
  -q, --quiet           # 只显示镜像的ID

  • 搜索镜像
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker search mysql # 搜索mysql镜像
NAME                            DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
mysql                           MySQL is a widely used, open-source relation…   12979     [OK]       
mariadb                         MariaDB Server is a high performing open sou…   4972      [OK]       
phpmyadmin                      phpMyAdmin - A web interface for MySQL and M…   594       [OK]       
percona                         Percona Server is a fork of the MySQL relati…   583       [OK]       
.............

===========================================================================================
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker search mysql --filter=STARS=3000
NAME      DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
mysql     MySQL is a widely used, open-source relation…   12979     [OK]       
mariadb   MariaDB Server is a high performing open sou…   4972      [OK]   

===========================================================================================
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker search --help

Usage:  docker search [OPTIONS] TERM

Search the Docker Hub for images

Options:
  -f, --filter filter   Filter output based on conditions provided
      --format string   Pretty-print search using a Go template
      --limit int       Max number of search results (default 25)
      --no-trunc        Don't truncate output

# 可选项解释
	--filter=STARS=3000 # 搜索出来的镜像的STARS是大于3000的

  • 下载镜像
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker pull mysql # 拉取下载mysql镜像
Using default tag: latest # 如果不写tag,默认是latest
latest: Pulling from library/mysql
72a69066d2fe: Pull complete # 分层下载,docker镜像的核心
93619dbc5b36: Pull complete 
99da31dd6142: Pull complete 
626033c43d70: Pull complete 
37d5d7efb64e: Pull complete 
ac563158d721: Pull complete 
d2ba16033dad: Pull complete 
688ba7d5c01a: Pull complete 
00e060b6d11d: Pull complete 
1c04857f594f: Pull complete 
4d7cfa90e6ea: Pull complete 
e0431212d27d: Pull complete 
Digest: sha256:e9027fe4d91c0153429607251656806cc784e914937271037f7738bd5b8e7709 # 签名
Status: Downloaded newer image for mysql:latest
docker.io/library/mysql:latest # 真实地址

===========================================================================================
# 这两条命令是等价的
docker pull mysql
docker pull docker.io/library/mysql:latest

===========================================================================================
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker pull mysql:5.7 # 拉取下载mysql 5.7版本的镜像
5.7: Pulling from library/mysql
72a69066d2fe: Already exists 
93619dbc5b36: Already exists 
99da31dd6142: Already exists 
626033c43d70: Already exists 
37d5d7efb64e: Already exists 
ac563158d721: Already exists 
d2ba16033dad: Already exists 
0ceb82207cd7: Pull complete 
37f2405cae96: Pull complete 
e2482e017e53: Pull complete 
70deed891d42: Pull complete 
Digest: sha256:f2ad209efe9c67104167fc609cca6973c8422939491c9345270175a300419f94
Status: Downloaded newer image for mysql:5.7
docker.io/library/mysql:5.7

  • 删除镜像
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED         SIZE
mysql         5.7       c20987f18b13   7 months ago    448MB
mysql         latest    3218b38490ce   7 months ago    516MB
hello-world   latest    feb5d9fea6a5   10 months ago   13.3kB
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker rmi -f c20987f18b13 # 根据镜像的ID删除
Untagged: mysql:5.7
Untagged: mysql@sha256:f2ad209efe9c67104167fc609cca6973c8422939491c9345270175a300419f94
Deleted: sha256:c20987f18b130f9d144c9828df630417e2a9523148930dc3963e9d0dab302a76
Deleted: sha256:6567396b065ee734fb2dbb80c8923324a778426dfd01969f091f1ab2d52c7989
Deleted: sha256:0910f12649d514b471f1583a16f672ab67e3d29d9833a15dc2df50dd5536e40f
Deleted: sha256:6682af2fb40555c448b84711c7302d0f86fc716bbe9c7dc7dbd739ef9d757150
Deleted: sha256:5c062c3ac20f576d24454e74781511a5f96739f289edaadf2de934d06e910b92
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED         SIZE
mysql         latest    3218b38490ce   7 months ago    516MB
hello-world   latest    feb5d9fea6a5   10 months ago   13.3kB
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker rmi -f $(docker images -aq) # 递归删除所有镜像
Untagged: mysql:latest
Untagged: mysql@sha256:e9027fe4d91c0153429607251656806cc784e914937271037f7738bd5b8e7709
Deleted: sha256:3218b38490cec8d31976a40b92e09d61377359eab878db49f025e5d464367f3b
Deleted: sha256:aa81ca46575069829fe1b3c654d9e8feb43b4373932159fe2cad1ac13524a2f5
Deleted: sha256:0558823b9fbe967ea6d7174999be3cc9250b3423036370dc1a6888168cbd224d
Deleted: sha256:a46013db1d31231a0e1bac7eeda5ad4786dea0b1773927b45f92ea352a6d7ff9
Deleted: sha256:af161a47bb22852e9e3caf39f1dcd590b64bb8fae54315f9c2e7dc35b025e4e3
Deleted: sha256:feff1495e6982a7e91edc59b96ea74fd80e03674d92c7ec8a502b417268822ff
Deleted: sha256:8805862fcb6ef9deb32d4218e9e6377f35fb351a8be7abafdf1da358b2b287ba
Deleted: sha256:872d2f24c4c64a6795e86958fde075a273c35c82815f0a5025cce41edfef50c7
Deleted: sha256:6fdb3143b79e1be7181d32748dd9d4a845056dfe16ee4c827410e0edef5ad3da
Deleted: sha256:b0527c827c82a8f8f37f706fcb86c420819bb7d707a8de7b664b9ca491c96838
Deleted: sha256:75147f61f29796d6528486d8b1f9fb5d122709ea35620f8ffcea0e0ad2ab0cd0
Deleted: sha256:2938c71ddf01643685879bf182b626f0a53b1356138ef73c40496182e84548aa
Deleted: sha256:ad6b69b549193f81b039a1d478bc896f6e460c77c1849a4374ab95f9a3d2cea2
Untagged: hello-world:latest
Untagged: hello-world@sha256:53f1bbee2f52c39e41682ee1d388285290c5c8a76cc92b42687eecf38e0af3f0
Deleted: sha256:feb5d9fea6a5e9606aa995e879d862b825965ba48de054caab5ef356dc6b3412
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker images
REPOSITORY   TAG       IMAGE ID   CREATED   SIZE

容器命令

说明一下:我们有了镜像才可以创建容器,我们下载一个centOS镜像来测试学习

准备工作

docker pull centos # 先下载centos镜像

新建容器并启动

[root@iZwz9cj1ytrolpgw50tiksZ /]# docker images
REPOSITORY   TAG       IMAGE ID       CREATED         SIZE
centos       latest    5d0da3dc9764   10 months ago   231MB
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker run -it centos /bin/bash # 启动并进入容器
[root@c529a20e21fb /]# ls # 查看容器内的centos,基础版本有很多命令是不完善的
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
[root@c529a20e21fb /]# exit # 容器停止运行并且退出,如果想容器不停止退出,直接按快捷键:CTRL + P + Q
exit

===========================================================================================
docker run [可选参数] 镜像

# 常用的参数说明
--name="Name" # 给容器起名字,用来区分容器

-d # 后台方式运行容器

-it # 使用交互方式运行,进入容器查看内容

-p # 指定容器的端口
	-p 主机端口:容器端口 # 这种方式比较常用
	-p 容器端口

-P # 随机指定端口

===========================================================================================
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker ps # 展示正在运行的容器
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker ps -a # 展示正在运行的容器和曾经运行过的容器
CONTAINER ID   IMAGE          COMMAND       CREATED             STATUS                         PORTS     NAMES
c529a20e21fb   centos         "/bin/bash"   9 minutes ago       Exited (0) 2 minutes ago                 optimistic_gagarin
7f3ded7e7be5   feb5d9fea6a5   "/hello"      About an hour ago   Exited (0) About an hour ago             admiring_fermat
d16cefadd3ca   feb5d9fea6a5   "/hello"      21 hours ago        Exited (0) 21 hours ago                  jolly_ganguly
d6a1f8116f07   feb5d9fea6a5   "/hello"      2 weeks ago         Exited (0) 2 weeks ago                   wonderful_beaver
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker ps -a -n=1 # 展示数量为1个
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS                     PORTS     NAMES
c529a20e21fb   centos    "/bin/bash"   13 minutes ago   Exited (0) 5 minutes ago             optimistic_gagarin
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker ps -aq # 只显示容器的编号
c529a20e21fb
7f3ded7e7be5
d16cefadd3ca
d6a1f8116f07

===========================================================================================
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker ps -a
CONTAINER ID   IMAGE          COMMAND       CREATED         STATUS                    PORTS     NAMES
4b1373db9eb2   centos         "/bin/bash"   3 minutes ago   Up 3 minutes                        dreamy_faraday
c529a20e21fb   centos         "/bin/bash"   2 hours ago     Exited (0) 2 hours ago              optimistic_gagarin
7f3ded7e7be5   feb5d9fea6a5   "/hello"      3 hours ago     Exited (0) 3 hours ago              admiring_fermat
d16cefadd3ca   feb5d9fea6a5   "/hello"      23 hours ago    Exited (0) 23 hours ago             jolly_ganguly
d6a1f8116f07   feb5d9fea6a5   "/hello"      2 weeks ago     Exited (0) 2 weeks ago              wonderful_beaver
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker rm c529a20e21fb # 根据容器ID删除,但是不能删除正在运行的容器
c529a20e21fb
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker ps -a
CONTAINER ID   IMAGE          COMMAND       CREATED         STATUS                    PORTS     NAMES
4b1373db9eb2   centos         "/bin/bash"   4 minutes ago   Up 4 minutes                        dreamy_faraday
7f3ded7e7be5   feb5d9fea6a5   "/hello"      3 hours ago     Exited (0) 3 hours ago              admiring_fermat
d16cefadd3ca   feb5d9fea6a5   "/hello"      23 hours ago    Exited (0) 23 hours ago             jolly_ganguly
d6a1f8116f07   feb5d9fea6a5   "/hello"      2 weeks ago     Exited (0) 2 weeks ago              wonderful_beaver
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker ps -aq
4b1373db9eb2
7f3ded7e7be5
d16cefadd3ca
d6a1f8116f07
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker rm -f $(docker ps -aq) # 根据容器ID,强制删除所有容器
4b1373db9eb2
7f3ded7e7be5
d16cefadd3ca
d6a1f8116f07
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker ps -aq
[root@iZwz9cj1ytrolpgw50tiksZ /]# 

===========================================================================================
docker start 容器id # 启动容器
docker restart 容器id # 重启容器
docker stop 容器id # 停止当前正在运行的容器
docker kill 容器id # 强制停止当前容器

其它命令

  • 后台启动容器
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker run -d centos # 后台启动centos
dba04ce2d4f8447ab380635893df0f16df29814460a26ef439bc89f5520c3b50
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker ps # 发现centos停止了
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker ps -a
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS                      PORTS     NAMES
dba04ce2d4f8   centos    "/bin/bash"   12 seconds ago   Exited (0) 11 seconds ago             friendly_goldstine
f019ecf49f75   centos    "/bin/bash"   4 minutes ago    Exited (0) 2 minutes ago              friendly_driscoll
[root@iZwz9cj1ytrolpgw50tiksZ /]# 

# 常见的坑:docker容器使用后台进行,就必须要有一个前台进程,docker发现没有前台应用,就会自动停止

  • 查看日志

在这里插入图片描述

  • 查看容器中的进程信息
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker ps
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS          PORTS     NAMES
e4d7e2783dc3   centos    "/bin/bash"   10 minutes ago   Up 10 minutes             crazy_vaughan
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker top e4d7e2783dc3 # 查看容器内部的进程信息
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                24104               24085               0                   13:48               ?                   00:00:00            /bin/bash
[root@iZwz9cj1ytrolpgw50tiksZ /]# 

  • 查看镜像的元数据
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker ps -a
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS                      PORTS     NAMES
e4d7e2783dc3   centos    "/bin/bash"   14 minutes ago   Up 14 minutes                         crazy_vaughan
dba04ce2d4f8   centos    "/bin/bash"   21 minutes ago   Exited (0) 21 minutes ago             friendly_goldstine
f019ecf49f75   centos    "/bin/bash"   25 minutes ago   Exited (0) 23 minutes ago             friendly_driscoll
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker inspect e4d7e2783dc3

  • 进入当前正在运行的容器
# 我们通常都是使用后台方式运行容器的,我们需要进入容器,修改一些配置

# 方式一
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker ps
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS          PORTS     NAMES
e4d7e2783dc3   centos    "/bin/bash"   20 minutes ago   Up 20 minutes             crazy_vaughan
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker exec -it e4d7e2783dc3 /bin/bash # 进入容器
[root@e4d7e2783dc3 /]# ls
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
[root@e4d7e2783dc3 /]# ps -ef
UID        PID  PPID  C STIME TTY          TIME CMD
root         1     0  0 05:48 pts/0    00:00:00 /bin/bash
root        15     0  0 06:10 pts/1    00:00:00 /bin/bash
root        30    15  0 06:10 pts/1    00:00:00 ps -ef
[root@e4d7e2783dc3 /]# 

===========================================================================================
# 方式二
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker ps
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS          PORTS     NAMES
e4d7e2783dc3   centos    "/bin/bash"   23 minutes ago   Up 23 minutes             crazy_vaughan
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker attach e4d7e2783dc3 # 进入容器
[root@e4d7e2783dc3 /]# 

===========================================================================================
# 方式一和方式二的区别
# 方式一进入容器后,开启一个新的终端,可以在里面操作(常用)
# 方式二进入容器后,进入当前打开的终端
  • 从容器内拷贝文件到主机上
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker run -it centos /bin/bash
[root@3b319aead5e4 /]# [root@iZwz9cj1ytrolpgw50tiksZ /]# docker ps
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS          PORTS     NAMES
3b319aead5e4   centos    "/bin/bash"   11 seconds ago   Up 10 seconds             jovial_kapitsa
[root@iZwz9cj1ytrolpgw50tiksZ /]# cd /home
[root@iZwz9cj1ytrolpgw50tiksZ home]# ls
hatea  kuangshen.java  kuangstudy
[root@iZwz9cj1ytrolpgw50tiksZ home]# docker attach 3b319aead5e4 # 进入docker容器内部
[root@3b319aead5e4 /]# cd /home
[root@3b319aead5e4 home]# ls
[root@3b319aead5e4 home]# touch test.java # 在容器内部新建文件
[root@3b319aead5e4 home]# exit
exit
[root@iZwz9cj1ytrolpgw50tiksZ home]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@iZwz9cj1ytrolpgw50tiksZ home]# docker ps -a
CONTAINER ID   IMAGE     COMMAND       CREATED         STATUS                     PORTS     NAMES
3b319aead5e4   centos    "/bin/bash"   6 minutes ago   Exited (0) 7 seconds ago             jovial_kapitsa
[root@iZwz9cj1ytrolpgw50tiksZ home]# docker cp 3b319aead5e4:/home/test.java /home # 从容器内拷贝文件到主机上
[root@iZwz9cj1ytrolpgw50tiksZ home]# ls
hatea  kuangshen.java  kuangstudy  test.java
[root@iZwz9cj1ytrolpgw50tiksZ home]# 

目前的拷贝是一个手动过程,未来我们会使用卷的技术,实现数据自动同步

小结

在这里插入图片描述

docker的命令是十分多的,上面我们学习的那些都是最常用的命令,之后我们还会学习很多命令!

作业练习

Docker安装Nginx

# 1、先搜索Nginx镜像,也可以去docker仓库网站上搜索
docker search nginx
# 2、下载镜像
docker pull nginx
# 3、检查一下是否下载成功
docker images
# 4、运行测试
# 	-d	后台运行
#	--name	给容器命名
#	-p	宿主机端口:容器内部端口
[root@iZwz9cj1ytrolpgw50tiksZ home]# docker run -d --name nginx01 -p 3344:80 nginx
da70d5e875c7a4bc9c8b9eab5383347ef75d8f1325124dce1503f23b3480f9db
[root@iZwz9cj1ytrolpgw50tiksZ home]# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED         STATUS         PORTS                  NAMES
da70d5e875c7   nginx     "/docker-entrypoint.…"   5 seconds ago   Up 3 seconds   0.0.0.0:3344->80/tcp   nginx01
[root@iZwz9cj1ytrolpgw50tiksZ home]# curl localhost:3344
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>
[root@iZwz9cj1ytrolpgw50tiksZ home]# 

# 5、进入nginx容器
[root@iZwz9cj1ytrolpgw50tiksZ home]# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED         STATUS         PORTS                  NAMES
da70d5e875c7   nginx     "/docker-entrypoint.…"   8 minutes ago   Up 8 minutes   0.0.0.0:3344->80/tcp   nginx01
[root@iZwz9cj1ytrolpgw50tiksZ home]# docker exec -it nginx01 /bin/bash
root@da70d5e875c7:/# whereis nginx
nginx: /usr/sbin/nginx /usr/lib/nginx /etc/nginx /usr/share/nginx
root@da70d5e875c7:/# cd /etc/nginx
root@da70d5e875c7:/etc/nginx# ls
conf.d	fastcgi_params	mime.types  modules  nginx.conf  scgi_params  uwsgi_params
root@da70d5e875c7:/etc/nginx# exit # 退出容器
exit

# 6、停止容器运行
[root@iZwz9cj1ytrolpgw50tiksZ home]# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS          PORTS                  NAMES
da70d5e875c7   nginx     "/docker-entrypoint.…"   12 minutes ago   Up 12 minutes   0.0.0.0:3344->80/tcp   nginx01
[root@iZwz9cj1ytrolpgw50tiksZ home]# docker stop da70d5e875c7
da70d5e875c7
[root@iZwz9cj1ytrolpgw50tiksZ home]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@iZwz9cj1ytrolpgw50tiksZ home]# curl localhost:3344
curl: (7) Failed to connect to ::1: No route to host
[root@iZwz9cj1ytrolpgw50tiksZ home]# 

端口暴露的概念!

在这里插入图片描述

思考问题:我们每次改动nginx配置文件,都需要进入容器内部,十分地麻烦,我是否可以在容器外部提供一个映射路径,实现在容器外部修改文件,容器内部就可以自动修改?后面我们会使用数据卷实现!

Docker安装Tomcat

# 官方的用法,我们一般不这么用
docker run -it --rm tomcat:9.0
# 我们之前的启动都是后台,停止了容器之后,容器还是可以查询到,而这种 docker run -it --rm 一般用来测试,容器用完即删


# 1、下载Tomcat
docker pull tomcat

# 2、启动运行
docker run -d -p 3355:8080 --name tomcat01 tomcat

# 3、本机localhost测试访问,如果是外网访问,还需要开启阿里云安全组对应的3355端口
curl localhost:3355

# 4、进入Tomcat容器
@iZwz9cj1ytrolpgw50tiksZ home]# docker exec -it tomcat01 /bin/bash
root@cf5cbc7fb824:/usr/local/tomcat# ls
BUILDING.txt  CONTRIBUTING.md  LICENSE	NOTICE	README.md  RELEASE-NOTES  RUNNING.txt  bin  conf  lib  logs  native-jni-lib  temp  webapps  webapps.dist  work
root@cf5cbc7fb824:/usr/local/tomcat# ls -al
total 176
drwxr-xr-x 1 root root  4096 Dec 22  2021 .
drwxr-xr-x 1 root root  4096 Aug  8 09:31 ..
-rw-r--r-- 1 root root 18994 Dec  2  2021 BUILDING.txt
-rw-r--r-- 1 root root  6210 Dec  2  2021 CONTRIBUTING.md
-rw-r--r-- 1 root root 60269 Dec  2  2021 LICENSE
-rw-r--r-- 1 root root  2333 Dec  2  2021 NOTICE
-rw-r--r-- 1 root root  3378 Dec  2  2021 README.md
-rw-r--r-- 1 root root  6905 Dec  2  2021 RELEASE-NOTES
-rw-r--r-- 1 root root 16517 Dec  2  2021 RUNNING.txt
drwxr-xr-x 2 root root  4096 Dec 22  2021 bin
drwxr-xr-x 1 root root  4096 Aug  8 09:30 conf
drwxr-xr-x 2 root root  4096 Dec 22  2021 lib
drwxrwxrwx 1 root root  4096 Aug  8 09:30 logs
drwxr-xr-x 2 root root  4096 Dec 22  2021 native-jni-lib
drwxrwxrwx 2 root root  4096 Dec 22  2021 temp
drwxr-xr-x 2 root root  4096 Dec 22  2021 webapps
drwxr-xr-x 7 root root  4096 Dec  2  2021 webapps.dist
drwxrwxrwx 2 root root  4096 Dec  2  2021 work
root@cf5cbc7fb824:/usr/local/tomcat# 

# 我们可以把webapps.dist目录下的内容全部复制到webapps目录下
# cp -r webapps.dist/* webapps

思考问题:我们以后要部署项目,如果每次都要进入容器就会十分麻烦,我是否可以在容器外部提供一个映射路径,我们在外部放置项目,就自动同步到内部?后面我们会使用数据卷实现!

Docker部署ES

# ES暴露的端口有很多
# ES十分地耗内存
# ES的数据一般需要放置到安全目录!
# 下载并且启动ES
docker run -d --name elasticsearch -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" elasticsearch:7.6.2

# ES启动后,会发现Linux十分地卡,因为ES十分耗内存,我们可以设置ES的内存限制
# 查看一下内存情况
docker stats

# 测试访问ES
[root@iZwz9cj1ytrolpgw50tiksZ home]# docker ps
CONTAINER ID   IMAGE                 COMMAND                  CREATED          STATUS          PORTS                                            NAMES
40c56e6a01ee   elasticsearch:7.6.2   "/usr/local/bin/dock…"   31 seconds ago   Up 30 seconds   0.0.0.0:9200->9200/tcp, 0.0.0.0:9300->9300/tcp   elasticsearch
[root@iZwz9cj1ytrolpgw50tiksZ home]# curl localhost:9200
{
  "name" : "40c56e6a01ee",
  "cluster_name" : "docker-cluster",
  "cluster_uuid" : "fEoeJoV9Q6ye39C99yOHQw",
  "version" : {
    "number" : "7.6.2",
    "build_flavor" : "default",
    "build_type" : "docker",
    "build_hash" : "ef48eb35cf30adf4db14086e8aabd07ef6fb113f",
    "build_date" : "2020-03-26T06:34:37.794943Z",
    "build_snapshot" : false,
    "lucene_version" : "8.4.0",
    "minimum_wire_compatibility_version" : "6.8.0",
    "minimum_index_compatibility_version" : "6.0.0-beta1"
  },
  "tagline" : "You Know, for Search"
}
[root@iZwz9cj1ytrolpgw50tiksZ home]# 

# 启动的同时,限制ES占用内存的大小
docker run -d --name elasticsearch -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" -e ES_JAVA_OPTS="-Xms64m -Xmx512m" elasticsearch:7.6.2

# 查看一下内存情况
docker stats

思考问题,Kibana如何连接ES?

在这里插入图片描述

可视化面板安装

  • portainer(先用这个)

  • Rancher(CI/CD的时候我们再用)

什么是portainer?

它是Docker图形化界面管理工具!可以提供一个后台面板供我们操作!

# 下载并且启动
docker run -d -p 8088:9000 \
--restart=always -v /var/run/docker.sock:/var/run/docker.sock --privileged=true portainer/portainer

访问测试:http://47.106.9.114:8088/
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

这个可视化面板我们平时不会使用,大家自己测试玩玩即可!

Docker镜像讲解

镜像是什么?

镜像是一种轻量级、可执行的独立软件包,用来打包软件运行环境和基于运行环境开发的软件,它包含运行某个软件所需要的所有内容,包括代码、运行时库、环境变量和配置文件

以后所有的应用,直接打包成Docker镜像,就可以直接跑起来!

如何得到镜像?

  • 从远程仓库下载
  • 朋友拷贝给你
  • 自己制作一个镜像

Docker镜像加载原理

在这里插入图片描述

在这里插入图片描述

关于分层的理解

在这里插入图片描述

# 查看镜像分层的方式可以通过 docker image inspect 命令!
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker image inspect redis:latest
[
    //...............................................
        "RootFS": {
            "Type": "layers",
            "Layers": [
                "sha256:2edcec3590a4ec7f40cf0743c15d78fb39d8326bc029073b41ef9727da6c851f",
                "sha256:9b24afeb7c2f21e50a686ead025823cd2c6e9730c013ca77ad5f115c079b57cb",
                "sha256:4b8e2801e0f956a4220c32e2c8b0a590e6f9bd2420ec65453685246b82766ea1",
                "sha256:529cdb636f61e95ab91a62a51526a84fd7314d6aab0d414040796150b4522372",
                "sha256:9975392591f2777d6bf4d9919ad1b2c9afa12f9a9b4d260f45025ec3cc9b18ed",
                "sha256:8e5669d8329116b8444b9bbb1663dda568ede12d3dbcce950199b582f6e94952"
            ]
        },
        "Metadata": {
            "LastTagTime": "0001-01-01T00:00:00Z"
        }
    }
]

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

特点:

  • Docker镜像都是只读的,当容器启动时,一个新的可写层被加载到镜像的顶部!这一层就是我们通常说的容器层,容器之下的都叫镜像层。我们的所有操作都是基于容器层的

在这里插入图片描述

Commit镜像

docker commit # 提交容器成为一个新的副本

# 命令和Git原理类似
docker commit -m="提交的描述信息" -a="作者" 容器ID 目标镜像名:标签

实战测试

# 1、启动Tomcat容器
docker run -it -p 8001:8080 tomcat
# 官方镜像默认的Tomcat是没有webapps应用的,我们自己拷贝内容进去

# 2、开启一个新的会话窗口,进入Tomcat容器,把webapps.dist目录下的内容全部复制到webapps目录下
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker ps
CONTAINER ID   IMAGE     COMMAND             CREATED          STATUS          PORTS                    NAMES
f551c9684d37   tomcat    "catalina.sh run"   56 seconds ago   Up 55 seconds   0.0.0.0:8001->8080/tcp   relaxed_moore
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker exec -it f551c9684d37 /bin/bash
root@f551c9684d37:/usr/local/tomcat# cd webapps
root@f551c9684d37:/usr/local/tomcat/webapps# ls
root@f551c9684d37:/usr/local/tomcat/webapps# cd ..
root@f551c9684d37:/usr/local/tomcat# ls
BUILDING.txt  CONTRIBUTING.md  LICENSE	NOTICE	README.md  RELEASE-NOTES  RUNNING.txt  bin  conf  lib  logs  native-jni-lib  temp  webapps  webapps.dist  work
root@f551c9684d37:/usr/local/tomcat# cp -r webapps.dist/* webapps # 我们可以把webapps.dist目录下的内容全部复制到webapps目录下
root@f551c9684d37:/usr/local/tomcat# cd webapps
root@f551c9684d37:/usr/local/tomcat/webapps# ls
ROOT  docs  examples  host-manager  manager
root@f551c9684d37:/usr/local/tomcat/webapps# exit
exit
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker ps
CONTAINER ID   IMAGE     COMMAND             CREATED          STATUS          PORTS                    NAMES
f551c9684d37   tomcat    "catalina.sh run"   11 minutes ago   Up 11 minutes   0.0.0.0:8001->8080/tcp   relaxed_moore

# 3、我们以后想使用有webapps应用的tomcat,只需要把我们修改过的tomcat容器再一次打包成镜像提交即可
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker commit -a="kuangshen" -m="add webapps app" f551c9684d37 tomcat02:1.0
sha256:b3465ddd8d800e08a6d0d2c4aaefcfa1b0522b596034364762ae0eb1935e55f2
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker images
REPOSITORY            TAG       IMAGE ID       CREATED         SIZE
tomcat02              1.0       b3465ddd8d80   2 minutes ago   684MB # 这里会发现我们提交的新版本的Tomcat镜像
nginx                 latest    605c77e624dd   7 months ago    141MB
tomcat                9.0       b8e65a4d736d   7 months ago    680MB
tomcat                latest    fb5657adc892   7 months ago    680MB
redis                 latest    7614ae9453d1   7 months ago    113MB
centos                latest    5d0da3dc9764   10 months ago   231MB
portainer/portainer   latest    580c0e4e98b0   16 months ago   79.1MB
elasticsearch         7.6.2     f29a1ee41030   2 years ago     791MB
[root@iZwz9cj1ytrolpgw50tiksZ /]# 

如果你想要保存当前容器的状态,就可以通过commit来提交一个镜像,就好比虚拟机的快照一样

容器数据卷

什么是容器数据卷

Docker的理念回顾:将应用和环境打包成一个镜像!

如果数据都在容器中,那么我们容器一旦删除,数据就会丢失!所以我们需要数据持久化

我们希望Docker容器中产生的数据,能同步到本地!这就是容器数据卷技术

在这里插入图片描述

总结一句话:容器数据的持久化和同步操作!容器间也是可以数据共享的

使用数据卷

方式一:

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

# 启动测试
docker run -it -v /home/ceshi:/home centos /bin/bash # 直接使用命令来挂载

# 启动后,我们可以查看一下挂载信息
[root@iZwz9cj1ytrolpgw50tiksZ home]# docker ps
CONTAINER ID   IMAGE     COMMAND       CREATED              STATUS              PORTS     NAMES
049ef2ec490f   centos    "/bin/bash"   About a minute ago   Up About a minute             amazing_ptolemy
[root@iZwz9cj1ytrolpgw50tiksZ home]# docker inspect 049ef2ec490f
[
    {
        ..........................................
        "Mounts": [
            {
                "Type": "bind",
                "Source": "/home/ceshi", # 主机内地址
                "Destination": "/home", # docker容器内的地址
                "Mode": "",
                "RW": true,
                "Propagation": "rprivate"
            }
        ],
        ..........................................
    }
]

测试的具体效果:容器和主机互相同步,相当于Vue的双向绑定

在这里插入图片描述

在这里插入图片描述

实现挂载后,我们以后修改配置文件只需要在本地修改即可!容器内会自动同步!这样就不用进入容器内修改。

实战:MySQL同步数据

# 1、下载MySQL镜像
docker pull mysql:5.7

# 2、运行容器,需要做数据挂载。安装启动mysql的时候,注意是需要配置密码的!
# 这是官方启动MySQL的命令:docker run --name some-mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:tag
# 我们运行MySQL容器使用如下命令
docker run -d -p 3310: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
# 简单说明:
	-d 后台运行
	-p 端口映射
	-v 数据卷挂载
	-e 环境配置
	--name 容器名字


# 可以使用SQLyog,在本地连接这个MySql,只要使用对应的服务器IP地址和3310端口(阿里云必须先开启这个端口的安全组),使用对应的
# 用户名和密码即可连接这个MySql,操作这个MySql

假设我们将这个MySQL容器删除,我们挂载到本地的数据卷依旧没有丢失,这就实现了容器数据持久化的功能!

匿名挂载和具名挂载

# 匿名挂载
-v 容器内路径 # 不指定主机内路径,它就会自动帮我们生成一个目录

# 1、我们先启动nginx
docker run -d -P --name nginx01 -v /etc/nginx nginx # -P是随机映射一个端口

# 2、查看所有卷的情况
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker volume ls
DRIVER    VOLUME NAME
local     796a763561bf334ffcd4d51c7ad2ff9bf5d0e2cc387504f0925001917f384e17 # 这些就是匿名挂载
local     708508d97aac13f432e3fb84d13d3b17075c541a3cfebba163b833f1b3abe24a # 这些就是匿名挂载
#         这些匿名挂载,是因为我们在 -v 的时候,只写了容器内路径,并没有给予名称



# 具名挂载
-v 卷名:容器内路径

# 1、我们先启动nginx
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker run -d -P --name nginx02 -v juming-nginx:/etc/nginx nginx
20b9a702f11ff1be9a12022487f9dab24f0efe3137dfa74d18b993dd485f5f73

# 2、查看所有卷的情况
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker volume ls
DRIVER    VOLUME NAME
local     796a763561bf334ffcd4d51c7ad2ff9bf5d0e2cc387504f0925001917f384e17
local     708508d97aac13f432e3fb84d13d3b17075c541a3cfebba163b833f1b3abe24a
local     juming-nginx # 这就是具名挂载

# 3、查看卷挂载的主机路径
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker volume inspect juming-nginx
[
    {
        "CreatedAt": "2022-08-09T14:48:53+08:00",
        "Driver": "local",
        "Labels": null,
        "Mountpoint": "/var/lib/docker/volumes/juming-nginx/_data",
        "Name": "juming-nginx",
        "Options": null,
        "Scope": "local"
    }
]
[root@iZwz9cj1ytrolpgw50tiksZ /]# 

所有的docker容器内的卷,在没有指定主机目录的情况下,都是在主机的 /var/lib/docker/volumes/卷名/_data 目录下

[root@iZwz9cj1ytrolpgw50tiksZ /]# cd /var/lib/docker/volumes/
[root@iZwz9cj1ytrolpgw50tiksZ volumes]# ll
total 36
drwx-----x 3 root root   4096 Aug  9 14:36 708508d97aac13f432e3fb84d13d3b17075c541a3cfebba163b833f1b3abe24a
drwx-----x 3 root root   4096 Aug  8 20:46 796a763561bf334ffcd4d51c7ad2ff9bf5d0e2cc387504f0925001917f384e17
brw------- 1 root root 253, 1 Aug  7 17:31 backingFsBlockDev
drwx-----x 3 root root   4096 Aug  9 14:48 juming-nginx
-rw------- 1 root root  32768 Aug  9 14:48 metadata.db
[root@iZwz9cj1ytrolpgw50tiksZ volumes]# 

我们通过具名挂载可以方便找到我们挂载的卷,大多数情况下都是使用具名挂载

# 如何确定是具名挂载还是匿名挂载,还是指定路径挂载!
-v 容器内路径 # 匿名挂载

-v 卷名:容器内路径 # 具名挂载

-v 宿主机路径:容器内路径 # 指定路径挂载

拓展知识

# 设置容器的权限
ro:readonly # 只读	说明这个容器只能通过宿主机来操作,容器内部是无法操作的
rw:readwrite # 可读可写

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

初识DockerFile

DockerFile 就是用来构建 docker镜像 的构建文件!(我们之前学习过commit来构建镜像)

这个构建文件说白了就是命令脚本,通过这个命令脚本我们可以生成镜像。镜像是一层一层的,脚本就是一个一个的命令,每个命令都是一层

体验一下DockerFile

[root@iZwz9cj1ytrolpgw50tiksZ home]# ls
ceshi  hatea  kuangshen.java  kuangstudy  mysql  test.java
[root@iZwz9cj1ytrolpgw50tiksZ home]# mkdir docker-test-volume # 新建docker-test-volume目录
[root@iZwz9cj1ytrolpgw50tiksZ home]# ls
ceshi  docker-test-volume  hatea  kuangshen.java  kuangstudy  mysql  test.java
[root@iZwz9cj1ytrolpgw50tiksZ home]# cd docker-test-volume/
[root@iZwz9cj1ytrolpgw50tiksZ docker-test-volume]# vim dockerfile1
[root@iZwz9cj1ytrolpgw50tiksZ docker-test-volume]# cat dockerfile1 # 文件中的内容如下
FROM centos

VOLUME ["volume01","volume02"] # 这一层主要是挂载卷,这是匿名挂载!

CMD echo "----end----"

CMD /bin/bash
[root@iZwz9cj1ytrolpgw50tiksZ docker-test-volume]# docker build -f /home/docker-test-volume/dockerfile1 -t kuangshen/centos:1.0 . # 注意命令最后面还有一个.
Sending build context to Docker daemon  2.048kB
Step 1/4 : FROM centos
 ---> 5d0da3dc9764
Step 2/4 : VOLUME ["volume01","volume02"]
 ---> Running in e11f083e4151
Removing intermediate container e11f083e4151
 ---> a87fb160017f
Step 3/4 : CMD echo "----end----"
 ---> Running in 1e7b2277e2f5
Removing intermediate container 1e7b2277e2f5
 ---> bb5eb48223de
Step 4/4 : CMD /bin/bash
 ---> Running in 18e7a69cb3e9
Removing intermediate container 18e7a69cb3e9
 ---> 51285060a549
Successfully built 51285060a549
Successfully tagged kuangshen/centos:1.0
[root@iZwz9cj1ytrolpgw50tiksZ docker-test-volume]# docker images
REPOSITORY            TAG       IMAGE ID       CREATED          SIZE
kuangshen/centos      1.0       51285060a549   28 seconds ago   231MB # 这就是通过DockerFile构建的镜像
tomcat02              1.0       b3465ddd8d80   18 hours ago     684MB
nginx                 latest    605c77e624dd   7 months ago     141MB
tomcat                9.0       b8e65a4d736d   7 months ago     680MB
tomcat                latest    fb5657adc892   7 months ago     680MB
redis                 latest    7614ae9453d1   7 months ago     113MB
mysql                 5.7       c20987f18b13   7 months ago     448MB
centos                latest    5d0da3dc9764   10 months ago    231MB
portainer/portainer   latest    580c0e4e98b0   16 months ago    79.1MB
elasticsearch         7.6.2     f29a1ee41030   2 years ago      791MB
[root@iZwz9cj1ytrolpgw50tiksZ docker-test-volume]# 
# 我们来启动一下通过DockerFile构建的镜像
[root@iZwz9cj1ytrolpgw50tiksZ docker-test-volume]# docker images
REPOSITORY            TAG       IMAGE ID       CREATED          SIZE
kuangshen/centos      1.0       51285060a549   11 minutes ago   231MB
tomcat02              1.0       b3465ddd8d80   18 hours ago     684MB
nginx                 latest    605c77e624dd   7 months ago     141MB
tomcat                9.0       b8e65a4d736d   7 months ago     680MB
tomcat                latest    fb5657adc892   7 months ago     680MB
redis                 latest    7614ae9453d1   7 months ago     113MB
mysql                 5.7       c20987f18b13   7 months ago     448MB
centos                latest    5d0da3dc9764   10 months ago    231MB
portainer/portainer   latest    580c0e4e98b0   16 months ago    79.1MB
elasticsearch         7.6.2     f29a1ee41030   2 years ago      791MB
[root@iZwz9cj1ytrolpgw50tiksZ docker-test-volume]# docker run -it 51285060a549 /bin/bash
[root@ed0bb150f4af /]# ls -l
total 56
lrwxrwxrwx  1 root root    7 Nov  3  2020 bin -> usr/bin
drwxr-xr-x  5 root root  360 Aug  9 08:44 dev
drwxr-xr-x  1 root root 4096 Aug  9 08:44 etc
drwxr-xr-x  2 root root 4096 Nov  3  2020 home
lrwxrwxrwx  1 root root    7 Nov  3  2020 lib -> usr/lib
lrwxrwxrwx  1 root root    9 Nov  3  2020 lib64 -> usr/lib64
drwx------  2 root root 4096 Sep 15  2021 lost+found
drwxr-xr-x  2 root root 4096 Nov  3  2020 media
drwxr-xr-x  2 root root 4096 Nov  3  2020 mnt
drwxr-xr-x  2 root root 4096 Nov  3  2020 opt
dr-xr-xr-x 96 root root    0 Aug  9 08:44 proc
dr-xr-x---  2 root root 4096 Sep 15  2021 root
drwxr-xr-x 11 root root 4096 Sep 15  2021 run
lrwxrwxrwx  1 root root    8 Nov  3  2020 sbin -> usr/sbin
drwxr-xr-x  2 root root 4096 Nov  3  2020 srv
dr-xr-xr-x 13 root root    0 Jul 18 13:43 sys
drwxrwxrwt  7 root root 4096 Sep 15  2021 tmp
drwxr-xr-x 12 root root 4096 Sep 15  2021 usr
drwxr-xr-x 20 root root 4096 Sep 15  2021 var
drwxr-xr-x  2 root root 4096 Aug  9 08:44 volume01
drwxr-xr-x  2 root root 4096 Aug  9 08:44 volume02
[root@ed0bb150f4af /]# 

在这里插入图片描述

[root@iZwz9cj1ytrolpgw50tiksZ data]# docker ps
CONTAINER ID   IMAGE          COMMAND                  CREATED              STATUS              PORTS                   NAMES
daa19f2a8067   51285060a549   "/bin/bash"              About a minute ago   Up About a minute                           zen_kare
20b9a702f11f   nginx          "/docker-entrypoint.…"   2 hours ago          Up 2 hours          0.0.0.0:49154->80/tcp   nginx02
ff02086fec67   nginx          "/docker-entrypoint.…"   2 hours ago          Up 2 hours          0.0.0.0:49153->80/tcp   nginx01
[root@iZwz9cj1ytrolpgw50tiksZ data]# docker inspect daa19f2a8067 # 我们可以查看这个容器数据卷匿名挂载具体的信息
[
    {
     	........................................   
        "Mounts": [
            {
                "Type": "volume",
                "Name": "928b2cc33c746054df4d628b8f30d94b075a9d9362497b9ef8f352f23f42351d",
                "Source": "/var/lib/docker/volumes/928b2cc33c746054df4d628b8f30d94b075a9d9362497b9ef8f352f23f42351d/_data",
                "Destination": "volume02",
                "Driver": "local",
                "Mode": "",
                "RW": true,
                "Propagation": ""
            },
            {
                "Type": "volume",
                "Name": "655e194c2ae76dac6cdce3a29bb232967be6b24f85dc0feb83be16dba0e84947",
                "Source": "/var/lib/docker/volumes/655e194c2ae76dac6cdce3a29bb232967be6b24f85dc0feb83be16dba0e84947/_data",
                "Destination": "volume01",
                "Driver": "local",
                "Mode": "",
                "RW": true,
                "Propagation": ""
            }
        ],
        ........................................   
    }
]
[root@iZwz9cj1ytrolpgw50tiksZ data]# cd /
[root@iZwz9cj1ytrolpgw50tiksZ /]# cd /var/lib/docker/volumes/
[root@iZwz9cj1ytrolpgw50tiksZ volumes]# ls
655e194c2ae76dac6cdce3a29bb232967be6b24f85dc0feb83be16dba0e84947  796a763561bf334ffcd4d51c7ad2ff9bf5d0e2cc387504f0925001917f384e17  backingFsBlockDev
6cd8d41bc849d88c4595d30a543b7795d78c293bbda54f63803c5a161abaf307  87a789c4a1e0a50a6cf5302c4195bccb5bfa33d545494e7be5a00dfb68156635  juming-nginx
708508d97aac13f432e3fb84d13d3b17075c541a3cfebba163b833f1b3abe24a  928b2cc33c746054df4d628b8f30d94b075a9d9362497b9ef8f352f23f42351d  metadata.db
[root@iZwz9cj1ytrolpgw50tiksZ volumes]# 

这种方式我们未来使用使用的非常多,因为我们通常会构建自己的镜像!

容器间的数据共享(数据卷容器)

抛出问题:思考一下多个MySQL容器之间的数据如何同步?

# 启动三个容器,通过我们刚才自己使用DockerFile构建的镜像启动

# 1、启动docker01
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker images
REPOSITORY            TAG       IMAGE ID       CREATED         SIZE
kuangshen/centos      1.0       51285060a549   5 hours ago     231MB
tomcat02              1.0       b3465ddd8d80   23 hours ago    684MB
nginx                 latest    605c77e624dd   7 months ago    141MB
tomcat                9.0       b8e65a4d736d   7 months ago    680MB
tomcat                latest    fb5657adc892   7 months ago    680MB
redis                 latest    7614ae9453d1   7 months ago    113MB
mysql                 5.7       c20987f18b13   7 months ago    448MB
centos                latest    5d0da3dc9764   10 months ago   231MB
portainer/portainer   latest    580c0e4e98b0   16 months ago   79.1MB
elasticsearch         7.6.2     f29a1ee41030   2 years ago     791MB
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker run -it --name docker01 kuangshen/centos:1.0
[root@cab7619c197d /]# ls -l
total 56
lrwxrwxrwx  1 root root    7 Nov  3  2020 bin -> usr/bin
drwxr-xr-x  5 root root  360 Aug  9 13:34 dev
drwxr-xr-x  1 root root 4096 Aug  9 13:34 etc
drwxr-xr-x  2 root root 4096 Nov  3  2020 home
lrwxrwxrwx  1 root root    7 Nov  3  2020 lib -> usr/lib
lrwxrwxrwx  1 root root    9 Nov  3  2020 lib64 -> usr/lib64
drwx------  2 root root 4096 Sep 15  2021 lost+found
drwxr-xr-x  2 root root 4096 Nov  3  2020 media
drwxr-xr-x  2 root root 4096 Nov  3  2020 mnt
drwxr-xr-x  2 root root 4096 Nov  3  2020 opt
dr-xr-xr-x 96 root root    0 Aug  9 13:34 proc
dr-xr-x---  2 root root 4096 Sep 15  2021 root
drwxr-xr-x 11 root root 4096 Sep 15  2021 run
lrwxrwxrwx  1 root root    8 Nov  3  2020 sbin -> usr/sbin
drwxr-xr-x  2 root root 4096 Nov  3  2020 srv
dr-xr-xr-x 13 root root    0 Jul 18 13:43 sys
drwxrwxrwt  7 root root 4096 Sep 15  2021 tmp
drwxr-xr-x 12 root root 4096 Sep 15  2021 usr
drwxr-xr-x 20 root root 4096 Sep 15  2021 var
drwxr-xr-x  2 root root 4096 Aug  9 13:34 volume01
drwxr-xr-x  2 root root 4096 Aug  9 13:34 volume02
[root@cab7619c197d /]# (按CTRL + P + Q退出当前这个容器,但不停止容器)

# 2、启动docker02,关键命令是 --volumes-from 。实现容器间的数据共享
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker run -it --name docker02 --volumes-from docker01 kuangshen/centos:1.0
[root@2d64aa4e2b9a /]# ls -l 
total 56
lrwxrwxrwx  1 root root    7 Nov  3  2020 bin -> usr/bin
drwxr-xr-x  5 root root  360 Aug  9 13:43 dev
drwxr-xr-x  1 root root 4096 Aug  9 13:43 etc
drwxr-xr-x  2 root root 4096 Nov  3  2020 home
lrwxrwxrwx  1 root root    7 Nov  3  2020 lib -> usr/lib
lrwxrwxrwx  1 root root    9 Nov  3  2020 lib64 -> usr/lib64
drwx------  2 root root 4096 Sep 15  2021 lost+found
drwxr-xr-x  2 root root 4096 Nov  3  2020 media
drwxr-xr-x  2 root root 4096 Nov  3  2020 mnt
drwxr-xr-x  2 root root 4096 Nov  3  2020 opt
dr-xr-xr-x 98 root root    0 Aug  9 13:43 proc
dr-xr-x---  2 root root 4096 Sep 15  2021 root
drwxr-xr-x 11 root root 4096 Sep 15  2021 run
lrwxrwxrwx  1 root root    8 Nov  3  2020 sbin -> usr/sbin
drwxr-xr-x  2 root root 4096 Nov  3  2020 srv
dr-xr-xr-x 13 root root    0 Jul 18 13:43 sys
drwxrwxrwt  7 root root 4096 Sep 15  2021 tmp
drwxr-xr-x 12 root root 4096 Sep 15  2021 usr
drwxr-xr-x 20 root root 4096 Sep 15  2021 var
drwxr-xr-x  2 root root 4096 Aug  9 13:34 volume01
drwxr-xr-x  2 root root 4096 Aug  9 13:34 volume02
[root@2d64aa4e2b9a /]# 

测试一下:

  • 进入docker01容器里面,在volume01目录下新建一个文件 a
  • 然后进入docker02容器里面,我们会发现在volume01目录下也出现了文件 a
  • 我们实现了容器间的数据共享
# 3、再启动一个docker03,我们测试后会发现docker03和docker02和docker01容器之间的数据依旧是共享的!
docker run -it --name docker03 --volumes-from docker01 kuangshen/centos:1.0

# 4、我们把容器docker01删除,发现docker03和docker02容器之间共享的数据仍然存在!

===================================================================================================

一名网友的回答,数据卷容器背后可能的原理:感谢狂神分享,关于数据卷容器这一段,容器3和容器2从容器1挂载数据卷的操作,包括容器4从容器3挂载数据,经过实验是对容器1的外部匿名数据卷的挂载的共享,通过inspect查看容器1、2、3、4的mounts挂载配置,可以看到他们的source地址都是宿主机上的同一个匿名卷。猜测,–volume-from的命令其实是新容器通过复制了旧容器中的mounts配置的source和destination来实现的,并且优先于dockerfile中的卷挂载定义(根据视频演示中的centos容器镜像是包含启动时挂载的),所以可能称这种操作为挂载共享(复制)可能更容易理解

===================================================================================================

在这里插入图片描述

主要应用场景:

  • 实现多个MySQL容器间的数据共享

    # 1、启动mysql01
    docker run -d -p 3310:3306 -v /etc/mysql/conf.d -v /var/lib/mysql -e MYSQL_ROOT_PASSWORD=123456 --name mysql01 mysql:5.7
    
    # 2、启动mysql02,这样即可实现两个mysql容器间的数据共享
    docker run -d -p 3310:3306 -e MYSQL_ROOT_PASSWORD=123456 --name mysql02 --volumes-from mysql01 mysql:5.7
    

结论:

  • 数据卷容器的生命周期一直持续到没有容器使用为止
  • 但是一旦你持久化数据到宿主机(本地),这个时候,就算容器被删除了,宿主机的数据仍然存在!

名词的理解:

  • 容器数据卷:容器持久化数据到本地(容器数据共享到本地)
  • 数据卷容器:容器之间的数据共享

DockerFile

DockerFile介绍

DockerFile 就是用来构建 docker镜像 的构建文件!(我们之前学习过commit来构建镜像)

这个构建文件说白了就是命令脚本,通过这个命令脚本我们可以生成镜像。镜像是一层一层的,脚本就是一个一个的命令,每个命令都是一层

构建镜像的步骤:

1、编写一个dockerfile文件

2、通过 docker build 命令构建成为一个镜像

3、运行镜像即可

4、我们也可以发布镜像,可以发布到DockerHub、阿里云镜像仓库

很多官方镜像都是基础包,很多的功能都没有,我们通常会自己构建自己的镜像!

官方既然可以制作镜像,那么我们也可以!

DockerFile的构建过程

基础知识:

  • 每个保留关键字(指令)都必须为大写字母
  • 指令的执行是从上到下顺序执行
  • # 表示注释
  • 每一个指令都会创建提交一个新的镜像层,并提交!

在这里插入图片描述

DockerFile是面向开发的,我们以后要发布项目,做镜像,就需要编写dockerfile文件,这个文件十分简单!

以前交付的是jar包或者war包,现在企业交付的标准是Docker镜像

步骤:开发,部署,上线运维!缺一不可

三个概念的理解

  • DockerFile:构建文件,定义了一切的步骤,相当于源代码
  • DockerImages:通过DockerFile构建生成的镜像,最终发布和运行的产品
  • Docker容器:容器就是DockerImages运行起来提供的服务

DockerFile指令

在这里插入图片描述

常用指令说明:

FROM # 基础镜像,一切从这里开始构建

MAINTAINER # 镜像是谁写的,姓名+邮箱

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

ADD # 在基础镜像的基础上,添加内容

WORKDIR # 镜像的工作目录

VOLUME # 挂载卷的目录

EXPOSE # 镜像启动创建容器时,暴露端口配置

CMD # 指定这个镜像启动的时候要运行的命令,只有最后一个会生效,可被替代

ENTRYPOINT # 指定这个镜像启动的时候要运行的命令,可以追加命令

ONBUILD # 触发指令

COPY # 将我们的文件拷贝到镜像中,类似ADD

ENV # 构建的时候设置环境变量

实战:构建CentOS镜像

在Docker Hub中99%的镜像都是从这个基础镜像 scratch 开始的,然后配置需要的软件和配置来进行构建的

在这里插入图片描述

创建一个自己的centos

# 1、编写DockerFile文件
[root@iZwz9cj1ytrolpgw50tiksZ dockerfile]# pwd
/home/dockerfile
[root@iZwz9cj1ytrolpgw50tiksZ dockerfile]# ls
[root@iZwz9cj1ytrolpgw50tiksZ dockerfile]# vim mydockerfile-centos
[root@iZwz9cj1ytrolpgw50tiksZ dockerfile]# cat mydockerfile-centos # 查看配置文件的内容
FROM centos:7
MAINTAINER caoguowei<398156587@qq.com>

ENV MYPATH /usr/local
WORKDIR $MYPATH

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

EXPOSE 80

CMD echo $MYPATH
CMD echo "----end----"
CMD /bin/bash

[root@iZwz9cj1ytrolpgw50tiksZ dockerfile]# 

# 2、通过DockerFile文件构建镜像
[root@iZwz9cj1ytrolpgw50tiksZ dockerfile]# docker build -f mydockerfile-centos -t mycentos:0.1 .

# 3、查看我们构建出来的镜像
[root@iZwz9cj1ytrolpgw50tiksZ dockerfile]# docker images
REPOSITORY            TAG       IMAGE ID       CREATED         SIZE
mycentos              0.1       88a65e324284   5 seconds ago   613MB # 这就是我们构建的镜像
tomcat02              1.0       b3465ddd8d80   45 hours ago    684MB
nginx                 latest    605c77e624dd   7 months ago    141MB
tomcat                9.0       b8e65a4d736d   7 months ago    680MB
tomcat                latest    fb5657adc892   7 months ago    680MB
redis                 latest    7614ae9453d1   7 months ago    113MB
mysql                 5.7       c20987f18b13   7 months ago    448MB
centos                7         eeb6ee3f44bd   10 months ago   204MB
centos                latest    5d0da3dc9764   10 months ago   231MB
portainer/portainer   latest    580c0e4e98b0   16 months ago   79.1MB
elasticsearch         7.6.2     f29a1ee41030   2 years ago     791MB

# 4、测试运行镜像
[root@iZwz9cj1ytrolpgw50tiksZ dockerfile]# docker run -it mycentos:0.1
[root@44290cc9fe2d local]# pwd # 查看工作目录,原生的centos的默认目录为/
/usr/local
[root@44290cc9fe2d local]# ifconfig # 原生的centos没有ifconfig命令
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 172.17.0.2  netmask 255.255.0.0  broadcast 172.17.255.255
        ether 02:42:ac:11:00:02  txqueuelen 0  (Ethernet)
        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

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        loop  txqueuelen 1000  (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

[root@44290cc9fe2d local]# vim test # 原生的centos没有vim命令
[root@44290cc9fe2d local]# ls
bin  etc  games  include  lib  lib64  libexec  sbin  share  src  test

# 5、我们还可以查看一下镜像构建的历史,我们平时拿到镜像也可以查看一下镜像的构建历史
[root@iZwz9cj1ytrolpgw50tiksZ dockerfile]# docker images
REPOSITORY            TAG       IMAGE ID       CREATED             SIZE
mycentos              0.1       88a65e324284   About an hour ago   613MB
tomcat02              1.0       b3465ddd8d80   46 hours ago        684MB
nginx                 latest    605c77e624dd   7 months ago        141MB
tomcat                9.0       b8e65a4d736d   7 months ago        680MB
tomcat                latest    fb5657adc892   7 months ago        680MB
redis                 latest    7614ae9453d1   7 months ago        113MB
mysql                 5.7       c20987f18b13   7 months ago        448MB
centos                7         eeb6ee3f44bd   10 months ago       204MB
centos                latest    5d0da3dc9764   10 months ago       231MB
portainer/portainer   latest    580c0e4e98b0   16 months ago       79.1MB
elasticsearch         7.6.2     f29a1ee41030   2 years ago         791MB
[root@iZwz9cj1ytrolpgw50tiksZ dockerfile]# docker history 88a65e324284
IMAGE          CREATED             CREATED BY                                      SIZE      COMMENT
88a65e324284   About an hour ago   /bin/sh -c #(nop)  CMD ["/bin/sh" "-c" "/bin…   0B        
a9f90f576cd7   About an hour ago   /bin/sh -c #(nop)  CMD ["/bin/sh" "-c" "echo…   0B        
1cde54c7eca4   About an hour ago   /bin/sh -c #(nop)  CMD ["/bin/sh" "-c" "echo…   0B        
9ef8b8092d7a   About an hour ago   /bin/sh -c #(nop)  EXPOSE 80                    0B        
6ec5c476fe41   About an hour ago   /bin/sh -c yum -y install net-tools             177MB     
44e437be8bd4   About an hour ago   /bin/sh -c yum -y install vim                   232MB     
0b5fa00161f7   About an hour ago   /bin/sh -c #(nop) WORKDIR /usr/local            0B        
bfa05c42b144   About an hour ago   /bin/sh -c #(nop)  ENV MYPATH=/usr/local        0B        
fe1f83c414ac   About an hour ago   /bin/sh -c #(nop)  MAINTAINER caoguowei<3981…   0B        
eeb6ee3f44bd   10 months ago       /bin/sh -c #(nop)  CMD ["/bin/bash"]            0B        
<missing>      10 months ago       /bin/sh -c #(nop)  LABEL org.label-schema.sc…   0B        
<missing>      10 months ago       /bin/sh -c #(nop) ADD file:b3ebbe8bd304723d4…   204MB     
[root@iZwz9cj1ytrolpgw50tiksZ dockerfile]# 

CMD和ENTRYPOINT的区别

测试CMD命令

[root@iZwz9cj1ytrolpgw50tiksZ dockerfile]# ls
mydockerfile-centos
[root@iZwz9cj1ytrolpgw50tiksZ dockerfile]# vim dockerfile-cmd-test # 编写dockerfile文件
[root@iZwz9cj1ytrolpgw50tiksZ dockerfile]# ls
dockerfile-cmd-test  mydockerfile-centos
[root@iZwz9cj1ytrolpgw50tiksZ dockerfile]# cat dockerfile-cmd-test 
FROM centos:7

CMD ["ls","-a"]

[root@iZwz9cj1ytrolpgw50tiksZ dockerfile]# docker build -f dockerfile-cmd-test -t cmdtest . # 构建镜像
Sending build context to Docker daemon  3.072kB
Step 1/2 : FROM centos:7
 ---> eeb6ee3f44bd
Step 2/2 : CMD ["ls","-a"]
 ---> Running in 9ef0abad2bd6
Removing intermediate container 9ef0abad2bd6
 ---> a139fb82e24a
Successfully built a139fb82e24a
Successfully tagged cmdtest:latest
[root@iZwz9cj1ytrolpgw50tiksZ dockerfile]# docker run a139fb82e24a # 运行镜像,发现 ls -a 命令生效
.
..
.dockerenv
anaconda-post.log
bin
dev
etc
home
lib
lib64
media
mnt
opt
proc
root
run
sbin
srv
sys
tmp
usr
var
[root@iZwz9cj1ytrolpgw50tiksZ dockerfile]# 

# 当我们希望追加一个 -l ,期望执行的命令是 ls -al ,结果报错!
[root@iZwz9cj1ytrolpgw50tiksZ dockerfile]# docker run a139fb82e24a -l # 当我们希望 ls -al
docker: Error response from daemon: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: exec: "-l": executable file not found in $PATH: unknown.
[root@iZwz9cj1ytrolpgw50tiksZ dockerfile]# 

# 报错原因:在cmd的情况下, -l 会直接替换 ls -a 命令,-l 本身并不是命令,所以会报错!
# ENTRYPOINT才支持命令的追加

测试ENTRYPOINT命令

[root@iZwz9cj1ytrolpgw50tiksZ dockerfile]# pwd
/home/dockerfile
[root@iZwz9cj1ytrolpgw50tiksZ dockerfile]# ls
dockerfile-cmd-test  mydockerfile-centos
[root@iZwz9cj1ytrolpgw50tiksZ dockerfile]# vim dockerfile-entrypoint-test
[root@iZwz9cj1ytrolpgw50tiksZ dockerfile]# cat dockerfile-entrypoint-test 
FROM centos:7

ENTRYPOINT ["ls","-a"]
[root@iZwz9cj1ytrolpgw50tiksZ dockerfile]# docker build -f dockerfile-entrypoint-test -t entrypoint-test .
Sending build context to Docker daemon  4.096kB
Step 1/2 : FROM centos:7
 ---> eeb6ee3f44bd
Step 2/2 : ENTRYPOINT ["ls","-a"]
 ---> Running in 61353973a5d1
Removing intermediate container 61353973a5d1
 ---> 44a205ee4f16
Successfully built 44a205ee4f16
Successfully tagged entrypoint-test:latest
[root@iZwz9cj1ytrolpgw50tiksZ dockerfile]# docker run 44a205ee4f16
.
..
.dockerenv
anaconda-post.log
bin
dev
etc
home
lib
lib64
media
mnt
opt
proc
root
run
sbin
srv
sys
tmp
usr
var
[root@iZwz9cj1ytrolpgw50tiksZ dockerfile]# docker run 44a205ee4f16 -l # ENTRYPOINT支持命令的追加
total 64
drwxr-xr-x  1 root root  4096 Aug 10 13:03 .
drwxr-xr-x  1 root root  4096 Aug 10 13:03 ..
-rwxr-xr-x  1 root root     0 Aug 10 13:03 .dockerenv
-rw-r--r--  1 root root 12114 Nov 13  2020 anaconda-post.log
lrwxrwxrwx  1 root root     7 Nov 13  2020 bin -> usr/bin
drwxr-xr-x  5 root root   340 Aug 10 13:03 dev
drwxr-xr-x  1 root root  4096 Aug 10 13:03 etc
drwxr-xr-x  2 root root  4096 Apr 11  2018 home
lrwxrwxrwx  1 root root     7 Nov 13  2020 lib -> usr/lib
lrwxrwxrwx  1 root root     9 Nov 13  2020 lib64 -> usr/lib64
drwxr-xr-x  2 root root  4096 Apr 11  2018 media
drwxr-xr-x  2 root root  4096 Apr 11  2018 mnt
drwxr-xr-x  2 root root  4096 Apr 11  2018 opt
dr-xr-xr-x 97 root root     0 Aug 10 13:03 proc
dr-xr-x---  2 root root  4096 Nov 13  2020 root
drwxr-xr-x 11 root root  4096 Nov 13  2020 run
lrwxrwxrwx  1 root root     8 Nov 13  2020 sbin -> usr/sbin
drwxr-xr-x  2 root root  4096 Apr 11  2018 srv
dr-xr-xr-x 13 root root     0 Jul 18 13:43 sys
drwxrwxrwt  7 root root  4096 Nov 13  2020 tmp
drwxr-xr-x 13 root root  4096 Nov 13  2020 usr
drwxr-xr-x 18 root root  4096 Nov 13  2020 var
[root@iZwz9cj1ytrolpgw50tiksZ dockerfile]# 

实战:构建Tomcat镜像

1、准备镜像文件(tomcat压缩包,jdk的压缩包)

在这里插入图片描述

2、编写DockerFile文件,DockerFile文件的官方命名: Dockerfile ,如果使用官方命名,那么build的时候,就会自动寻找这个 Dockerfile 文件,不需要使用 -f 指定文件了。

[root@iZwz9cj1ytrolpgw50tiksZ kuangshen]# pwd
/home/kuangshen
[root@iZwz9cj1ytrolpgw50tiksZ kuangshen]# touch readme.txt # 一般会创建一个readme.txt文件
[root@iZwz9cj1ytrolpgw50tiksZ kuangshen]# vim Dockerfile # 编写DockerFile文件,使用官方命名:Dockerfile
[root@iZwz9cj1ytrolpgw50tiksZ kuangshen]# cat Dockerfile # 查看编写的内容
FROM centos:7

MAINTAINER caoguowei<398156587@qq.com>

COPY readme.txt /usr/local/readme.txt

ADD jdk-8u221-linux-x64.tar.gz /usr/local/
ADD apache-tomcat-9.0.22.tar.gz /usr/local/

RUN yum -y install vim

ENV MYPATH /usr/local
WORKDIR $MYPATH

ENV JAVA_HOME /usr/local/jdk1.8.0_221
ENV CLASSPATH $JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar

ENV CATALINA_HOME /usr/local/apache-tomcat-9.0.22
ENV CATALINA_BASE /usr/local/apache-tomcat-9.0.22
ENV PATH $PATH:$JAVA_HOME/bin:$CATALINA_HOME/lib:$CATALINA_HOME/bin

EXPOSE 8080

CMD /usr/local/apache-tomcat-9.0.22/bin/startup.sh && tail -F /usr/local/apache-tomcat-9.0.22/logs/catalina.out

[root@iZwz9cj1ytrolpgw50tiksZ kuangshen]# ls -l
total 201204
-rw-r--r-- 1 root root  10929702 Aug 11 10:59 apache-tomcat-9.0.22.tar.gz
-rw-r--r-- 1 root root       643 Aug 11 11:15 Dockerfile
-rw-r--r-- 1 root root 195094741 Aug 11 10:58 jdk-8u221-linux-x64.tar.gz
-rw-r--r-- 1 root root         0 Aug 11 11:08 readme.txt
[root@iZwz9cj1ytrolpgw50tiksZ kuangshen]# 

3、构建镜像,因为使用官方命名,所以build的时候,会自动寻找这个 Dockerfile 文件,因此不需要使用 -f 指定文件了。

[root@iZwz9cj1ytrolpgw50tiksZ kuangshen]# docker build -t diytomcat . # 构建镜像

4、查看镜像

[root@iZwz9cj1ytrolpgw50tiksZ kuangshen]# docker images
REPOSITORY            TAG       IMAGE ID       CREATED          SIZE
diytomcat             latest    cc7b040014fb   39 seconds ago   858MB # 这就是我们构建的镜像
entrypoint-test       latest    44a205ee4f16   14 hours ago     204MB
cmdtest               latest    a139fb82e24a   15 hours ago     204MB
mycentos              0.1       88a65e324284   16 hours ago     613MB
tomcat02              1.0       b3465ddd8d80   2 days ago       684MB
nginx                 latest    605c77e624dd   7 months ago     141MB
tomcat                9.0       b8e65a4d736d   7 months ago     680MB
tomcat                latest    fb5657adc892   7 months ago     680MB
redis                 latest    7614ae9453d1   7 months ago     113MB
mysql                 5.7       c20987f18b13   7 months ago     448MB
centos                7         eeb6ee3f44bd   10 months ago    204MB
centos                latest    5d0da3dc9764   10 months ago    231MB
portainer/portainer   latest    580c0e4e98b0   17 months ago    79.1MB
elasticsearch         7.6.2     f29a1ee41030   2 years ago      791MB
[root@iZwz9cj1ytrolpgw50tiksZ kuangshen]# 

5、启动镜像测试

# 启动镜像(后台启动,端口映射,容器命名,挂载卷)
# Dockerfile文件中的 tail -F 能够使后台运行容器不结束
[root@iZwz9cj1ytrolpgw50tiksZ kuangshen]# docker run -d -p 8002:8080 --name kuangshentomcat -v /home/kuangshen/build/tomcat/test:/usr/local/apache-tomcat-9.0.22/webapps/test -v /home/kuangshen/build/tomcat/tomcatlogs/:/usr/local/apache-tomcat-9.0.22/logs diytomcat
14a2c72b6cf0adb1e00b9bc96bd168260c9ce16a65492f596c6c0a6383799cf4
[root@iZwz9cj1ytrolpgw50tiksZ kuangshen]# docker ps # 查看当前运行的容器
CONTAINER ID   IMAGE       COMMAND                  CREATED         STATUS         PORTS                    NAMES
14a2c72b6cf0   diytomcat   "/bin/sh -c '/usr/lo…"   4 minutes ago   Up 4 minutes   0.0.0.0:8002->8080/tcp   kuangshentomcat
[root@iZwz9cj1ytrolpgw50tiksZ kuangshen]# 

6、连接测试

# 测试成功!
[root@iZwz9cj1ytrolpgw50tiksZ kuangshen]# curl localhost:8002

在这里插入图片描述

在这里插入图片描述

7、进入容器查看一下

[root@iZwz9cj1ytrolpgw50tiksZ kuangshen]# docker ps
CONTAINER ID   IMAGE       COMMAND                  CREATED          STATUS          PORTS                    NAMES
14a2c72b6cf0   diytomcat   "/bin/sh -c '/usr/lo…"   11 minutes ago   Up 11 minutes   0.0.0.0:8002->8080/tcp   kuangshentomcat
[root@iZwz9cj1ytrolpgw50tiksZ kuangshen]# docker exec -it 14a2c72b6cf0 /bin/bash
[root@14a2c72b6cf0 local]# pwd
/usr/local
[root@14a2c72b6cf0 local]# ls -l
total 56
drwxr-xr-x 3 root root 4096 Aug 11 06:35 aegis
drwxr-xr-x 1 root root 4096 Aug 11 06:24 apache-tomcat-9.0.22
drwxr-xr-x 2 root root 4096 Apr 11  2018 bin
drwxr-xr-x 2 root root 4096 Apr 11  2018 etc
drwxr-xr-x 2 root root 4096 Apr 11  2018 games
drwxr-xr-x 2 root root 4096 Apr 11  2018 include
drwxr-xr-x 7   10  143 4096 Jul  4  2019 jdk1.8.0_221
drwxr-xr-x 2 root root 4096 Apr 11  2018 lib
drwxr-xr-x 2 root root 4096 Apr 11  2018 lib64
drwxr-xr-x 2 root root 4096 Apr 11  2018 libexec
-rw-r--r-- 1 root root    0 Aug 11 03:08 readme.txt
drwxr-xr-x 2 root root 4096 Apr 11  2018 sbin
drwxr-xr-x 5 root root 4096 Nov 13  2020 share
drwxr-xr-x 2 root root 4096 Apr 11  2018 src
[root@14a2c72b6cf0 local]# 

8、我们可以发布项目了,由于做了卷挂载,我们直接在本地编写项目就可以发布了。本地编写的项目,会自动同步到容器中。

[root@iZwz9cj1ytrolpgw50tiksZ test]# pwd
/home/kuangshen/build/tomcat/test
[root@iZwz9cj1ytrolpgw50tiksZ test]# mkdir WEB-INF
[root@iZwz9cj1ytrolpgw50tiksZ test]# ls
WEB-INF
[root@iZwz9cj1ytrolpgw50tiksZ test]# cd WEB-INF/
[root@iZwz9cj1ytrolpgw50tiksZ WEB-INF]# vim web.xml # 编写web.xml文件
[root@iZwz9cj1ytrolpgw50tiksZ WEB-INF]# cat web.xml # 查看web.xml编写的内容
<?xml version="1.0" encoding="UTF-8"?>
<!--
      Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  version="4.0"
  metadata-complete="true">

  <display-name>Welcome to Tomcat</display-name>
  <description>
     Welcome to Tomcat
  </description>

</web-app>

[root@iZwz9cj1ytrolpgw50tiksZ WEB-INF]# ls
web.xml
[root@iZwz9cj1ytrolpgw50tiksZ WEB-INF]# cd ..
[root@iZwz9cj1ytrolpgw50tiksZ test]# vim index.jsp # 编写一个简单页面index.jsp
[root@iZwz9cj1ytrolpgw50tiksZ test]# cat index.jsp # 查看index.jsp的内容
<%--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements.  See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--%>
<%@ page session="false" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" %>
<%
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy");
request.setAttribute("year", sdf.format(new java.util.Date()));
request.setAttribute("tomcatUrl", "https://tomcat.apache.org/");
request.setAttribute("tomcatDocUrl", "/docs/");
request.setAttribute("tomcatExamplesUrl", "/examples/");
%>
%<!DOCTYPE html>
%<html lang="en">
%    <head>
%            <meta charset="UTF-8" />
%                    <title><%=request.getServletContext().getServerInfo() %></title>
%                            <link href="favicon.ico" rel="icon" type="image/x-icon" />
%                                    <link href="tomcat.css" rel="stylesheet" type="text/css" />
%                                        </head>
%
%                                            <body>
%                                            	<h1>九九导师报名,三折起步!</h1>
%                                            	    </body>
%
%                                            	    </html>
[root@iZwz9cj1ytrolpgw50tiksZ test]# ls
index.jsp  WEB-INF

9、查看发布的项目,项目部署成功,可以直接访问!

在这里插入图片描述

我们以后开发的步骤:需要掌握Dockfile的编写!我们以后的一切都是使用docker镜像来发布运行!

发布自己的镜像

发布镜像到DockerHub

DockerHub地址:https://hub.docker.com

1、首先注册账号,然后登录

2、在我们的服务器上提交自己的镜像

[root@iZwz9cj1ytrolpgw50tiksZ /]# docker login --help

Usage:  docker login [OPTIONS] [SERVER]

Log in to a Docker registry.
If no server is specified, the default is defined by the daemon.

Options:
  -p, --password string   Password
      --password-stdin    Take the password from stdin
  -u, --username string   Username
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker login -u kkoyy459 # 登录DockerHub的账号
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 # 登录成功!
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker images
REPOSITORY            TAG       IMAGE ID       CREATED         SIZE
diytomcat             latest    5142069d2a2a   8 minutes ago   858MB
entrypoint-test       latest    44a205ee4f16   19 hours ago    204MB
cmdtest               latest    a139fb82e24a   19 hours ago    204MB
mycentos              0.1       88a65e324284   21 hours ago    613MB
tomcat02              1.0       b3465ddd8d80   2 days ago      684MB
nginx                 latest    605c77e624dd   7 months ago    141MB
tomcat                9.0       b8e65a4d736d   7 months ago    680MB
tomcat                latest    fb5657adc892   7 months ago    680MB
redis                 latest    7614ae9453d1   7 months ago    113MB
mysql                 5.7       c20987f18b13   7 months ago    448MB
centos                7         eeb6ee3f44bd   10 months ago   204MB
centos                latest    5d0da3dc9764   10 months ago   231MB
portainer/portainer   latest    580c0e4e98b0   17 months ago   79.1MB
elasticsearch         7.6.2     f29a1ee41030   2 years ago     791MB
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker tag 5142069d2a2a kkoyy459/tomcat:1.0 # 给diytomcat镜像添加版本号
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker images
REPOSITORY            TAG       IMAGE ID       CREATED          SIZE
kkoyy459/tomcat       1.0       5142069d2a2a   10 minutes ago   858MB
diytomcat             latest    5142069d2a2a   10 minutes ago   858MB
entrypoint-test       latest    44a205ee4f16   19 hours ago     204MB
cmdtest               latest    a139fb82e24a   19 hours ago     204MB
mycentos              0.1       88a65e324284   21 hours ago     613MB
tomcat02              1.0       b3465ddd8d80   2 days ago       684MB
nginx                 latest    605c77e624dd   7 months ago     141MB
tomcat                9.0       b8e65a4d736d   7 months ago     680MB
tomcat                latest    fb5657adc892   7 months ago     680MB
redis                 latest    7614ae9453d1   7 months ago     113MB
mysql                 5.7       c20987f18b13   7 months ago     448MB
centos                7         eeb6ee3f44bd   10 months ago    204MB
centos                latest    5d0da3dc9764   10 months ago    231MB
portainer/portainer   latest    580c0e4e98b0   17 months ago    79.1MB
elasticsearch         7.6.2     f29a1ee41030   2 years ago      791MB
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker push kkoyy459/tomcat:1.0 # 推送即可!
The push refers to repository [docker.io/kkoyy459/tomcat]
7eec4872c9a5: Pushed 
2c39b8774a81: Pushed 
8cd1bc2ed135: Pushed 
dfee333b32e0: Pushed 
174f56854903: Pushed 
1.0: digest: sha256:20d04f5dd25517ca9ec9a38d4364b304e4c96526bfd240eae8ce52ef0c88f020 size: 1373
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker logout # 推送完成退出登录
Removing login credentials for https://index.docker.io/v1/
[root@iZwz9cj1ytrolpgw50tiksZ /]# 

在这里插入图片描述

push的时候,也是按照镜像一层一层来进行的

发布镜像到阿里云上

1、登录阿里云

2、找到容器镜像服务

在这里插入图片描述

3、创建命名空间

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

4、创建镜像仓库

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

操作指南有详细的教程

[root@iZwz9cj1ytrolpgw50tiksZ /]# docker login --username=kkoyy459 registry.cn-shenzhen.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
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker images
REPOSITORY                                                         TAG       IMAGE ID       CREATED         SIZE
kkoyy459/tomcat                                                    1.0       5142069d2a2a   2 hours ago     858MB
diytomcat                                                          latest    5142069d2a2a   2 hours ago     858MB
entrypoint-test                                                    latest    44a205ee4f16   21 hours ago    204MB
cmdtest                                                            latest    a139fb82e24a   21 hours ago    204MB
mycentos                                                           0.1       88a65e324284   23 hours ago    613MB
tomcat02                                                           1.0       b3465ddd8d80   2 days ago      684MB
nginx                                                              latest    605c77e624dd   7 months ago    141MB
tomcat                                                             9.0       b8e65a4d736d   7 months ago    680MB
tomcat                                                             latest    fb5657adc892   7 months ago    680MB
redis                                                              latest    7614ae9453d1   7 months ago    113MB
mysql                                                              5.7       c20987f18b13   7 months ago    448MB
centos                                                             7         eeb6ee3f44bd   10 months ago   204MB
centos                                                             latest    5d0da3dc9764   10 months ago   231MB
portainer/portainer                                                latest    580c0e4e98b0   17 months ago   79.1MB
elasticsearch                                                      7.6.2     f29a1ee41030   2 years ago     791MB
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker tag 5142069d2a2a registry.cn-shenzhen.aliyuncs.com/kkoyy459-test/kkoyy459-test-01:1.0
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker images
REPOSITORY                                                         TAG       IMAGE ID       CREATED         SIZE
kkoyy459/tomcat                                                    1.0       5142069d2a2a   2 hours ago     858MB
diytomcat                                                          latest    5142069d2a2a   2 hours ago     858MB
registry.cn-shenzhen.aliyuncs.com/kkoyy459-test/kkoyy459-test-01   1.0       5142069d2a2a   2 hours ago     858MB
entrypoint-test                                                    latest    44a205ee4f16   21 hours ago    204MB
cmdtest                                                            latest    a139fb82e24a   21 hours ago    204MB
mycentos                                                           0.1       88a65e324284   23 hours ago    613MB
tomcat02                                                           1.0       b3465ddd8d80   2 days ago      684MB
nginx                                                              latest    605c77e624dd   7 months ago    141MB
tomcat                                                             9.0       b8e65a4d736d   7 months ago    680MB
tomcat                                                             latest    fb5657adc892   7 months ago    680MB
redis                                                              latest    7614ae9453d1   7 months ago    113MB
mysql                                                              5.7       c20987f18b13   7 months ago    448MB
centos                                                             7         eeb6ee3f44bd   10 months ago   204MB
centos                                                             latest    5d0da3dc9764   10 months ago   231MB
portainer/portainer                                                latest    580c0e4e98b0   17 months ago   79.1MB
elasticsearch                                                      7.6.2     f29a1ee41030   2 years ago     791MB
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker push registry.cn-shenzhen.aliyuncs.com/kkoyy459-test/kkoyy459-test-01:1.0
The push refers to repository [registry.cn-shenzhen.aliyuncs.com/kkoyy459-test/kkoyy459-test-01]
7eec4872c9a5: Pushed 
2c39b8774a81: Pushed 
8cd1bc2ed135: Pushed 
dfee333b32e0: Pushed 
174f56854903: Pushed 
1.0: digest: sha256:20d04f5dd25517ca9ec9a38d4364b304e4c96526bfd240eae8ce52ef0c88f020 size: 1373
[root@iZwz9cj1ytrolpgw50tiksZ /]# 

5、查看镜像版本

在这里插入图片描述

小结

在这里插入图片描述

Docker网络

学习Docker网络前,建议先清空Docker所有容器和镜像,保证环境干净!

[root@iZwz9cj1ytrolpgw50tiksZ /]# docker images
REPOSITORY   TAG       IMAGE ID   CREATED   SIZE
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker ps -a
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@iZwz9cj1ytrolpgw50tiksZ /]# 

理解Docker0

首先查看一下网卡: ip addr

在这里插入图片描述

# 1、首先查看一下网卡
[root@iZwz9cj1ytrolpgw50tiksZ /]# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 00:16:3e:12:41:aa brd ff:ff:ff:ff:ff:ff
    inet 172.22.201.59/20 brd 172.22.207.255 scope global dynamic eth0
       valid_lft 313269631sec preferred_lft 313269631sec
3: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default 
    link/ether 02:42:70:7c:58:9f brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
       valid_lft forever preferred_lft forever
[root@iZwz9cj1ytrolpgw50tiksZ /]# 

# 2、下载tomcat:7.0镜像,并且后台启动
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker run -d -P --name tomcat01 tomcat:7.0
Unable to find image 'tomcat:7.0' locally
7.0: Pulling from library/tomcat
0bc3020d05f1: Pull complete 
a110e5871660: Pull complete 
83d3c0fa203a: Pull complete 
a8fd09c11b02: Pull complete 
96ebf1506065: Pull complete 
26b72ffca293: Pull complete 
0bffa2ea17aa: Pull complete 
d880cebcc7a6: Pull complete 
d19ab8039b36: Pull complete 
5057492dc495: Pull complete 
Digest: sha256:f7d37d248d0eacec1e5995736234c9c22155626fcb27ea3ead13b9db24e698f7
Status: Downloaded newer image for tomcat:7.0
2e205f080b85b96fc1c2e8b972869832d82fba0c3f8dc8214e9176c41368b1a7
[root@iZwz9cj1ytrolpgw50tiksZ /]# 

# 3、查看容器tomcat01的内部网络地址,会发现容器启动的时候会得到一个 eth0@if165 这样的ip地址,这是Docker分配的!
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker exec -it tomcat01 ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
164: eth0@if165: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default 
    link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff link-netnsid 0
    inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0
       valid_lft forever preferred_lft forever
[root@iZwz9cj1ytrolpgw50tiksZ /]# 

# 4、linux服务器可以直接ping通docker容器内部
#   因为网卡中的docker0的地址为:172.17.0.1
# 	172.17.0.1 和 172.17.0.2 属于同一网段,同一网段是可以ping通的
[root@iZwz9cj1ytrolpgw50tiksZ /]# ping 172.17.0.2
PING 172.17.0.2 (172.17.0.2) 56(84) bytes of data.
64 bytes from 172.17.0.2: icmp_seq=1 ttl=64 time=0.081 ms
64 bytes from 172.17.0.2: icmp_seq=2 ttl=64 time=0.074 ms
64 bytes from 172.17.0.2: icmp_seq=3 ttl=64 time=0.081 ms
64 bytes from 172.17.0.2: icmp_seq=4 ttl=64 time=0.090 ms
64 bytes from 172.17.0.2: icmp_seq=5 ttl=64 time=0.069 ms

# 5、再次查看网卡
[root@iZwz9cj1ytrolpgw50tiksZ /]# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 00:16:3e:12:41:aa brd ff:ff:ff:ff:ff:ff
    inet 172.22.201.59/20 brd 172.22.207.255 scope global dynamic eth0
       valid_lft 313266790sec preferred_lft 313266790sec
3: docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default 
    link/ether 02:42:70:7c:58:9f brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
       valid_lft forever preferred_lft forever
165: veth1553d6c@if164: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master docker0 state UP group default 
    link/ether c2:87:11:ca:36:79 brd ff:ff:ff:ff:ff:ff link-netnsid 0
[root@iZwz9cj1ytrolpgw50tiksZ /]# 

# 6、再启动一个容器tomcat02
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker run -d -P --name tomcat02 tomcat:7.0
06dc90dd704e04ddac671b7042ae8f430e8a2c8c9516ce5fecfcb13e71ee6abf

# 7、查看tomcat02容器的内部网络地址
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker exec -it tomcat02 ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
166: eth0@if167: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default 
    link/ether 02:42:ac:11:00:03 brd ff:ff:ff:ff:ff:ff link-netnsid 0
    inet 172.17.0.3/16 brd 172.17.255.255 scope global eth0
       valid_lft forever preferred_lft forever
[root@iZwz9cj1ytrolpgw50tiksZ /]# 

# 8、再次查看网卡
[root@iZwz9cj1ytrolpgw50tiksZ /]# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 00:16:3e:12:41:aa brd ff:ff:ff:ff:ff:ff
    inet 172.22.201.59/20 brd 172.22.207.255 scope global dynamic eth0
       valid_lft 313266211sec preferred_lft 313266211sec
3: docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default 
    link/ether 02:42:70:7c:58:9f brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
       valid_lft forever preferred_lft forever
165: veth1553d6c@if164: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master docker0 state UP group default 
    link/ether c2:87:11:ca:36:79 brd ff:ff:ff:ff:ff:ff link-netnsid 0
167: vethde9e904@if166: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master docker0 state UP group default 
    link/ether d2:b9:d2:81:e6:f3 brd ff:ff:ff:ff:ff:ff link-netnsid 1
[root@iZwz9cj1ytrolpgw50tiksZ /]# 

# 我们发现容器启动后,这些容器带来的网卡都是一对一对的
# evth-pair技术就是一对虚拟设备接口,它们都是成对出现的,一端连着协议,一端彼此相连
# 正因为有这个特性,通常利用evth-pair的这个特性来充当桥梁,专门连接各种虚拟网络设备
# OpenStac,Docker容器之间的连接,OVS的连接,都是使用evth-pair技术

# 9、测试一下tomcat01和tomcat02是否可以ping通,测试结果是可以ping通
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker exec -it tomcat02 ping 172.17.0.2
PING 172.17.0.2 (172.17.0.2) 56(84) bytes of data.
64 bytes from 172.17.0.2: icmp_seq=1 ttl=64 time=0.164 ms
64 bytes from 172.17.0.2: icmp_seq=2 ttl=64 time=0.098 ms
64 bytes from 172.17.0.2: icmp_seq=3 ttl=64 time=0.106 ms
64 bytes from 172.17.0.2: icmp_seq=4 ttl=64 time=0.126 ms
^C
--- 172.17.0.2 ping statistics ---
12 packets transmitted, 12 received, 0% packet loss, time 1009ms
rtt min/avg/max/mdev = 0.098/0.121/0.164/0.022 ms
[root@iZwz9cj1ytrolpgw50tiksZ /]# 

结论:容器和容器之间是可以互相ping通的!

结合网络模型图理解一下tomcat01 ping通 tomcat02 的过程:

在这里插入图片描述

  • 原理

1、只要我们安装了Docker,就会有一个网卡docker0。它是桥接模式,使用的是 evth-pair 技术!

2、我们每启动一个docker容器,Docker就会给docker容器分配一个默认的可用IP,这些IP地址都和docker0属于同一个网段

3、所有的容器在不指定网络的情况下,都是 docker0 路由的

在这里插入图片描述

Docker 中所有的网络接口都是虚拟的,为什么用虚拟,因为虚拟的转发效率高。

只要容器删除,容器对应的一对IP也没了

–link

[root@iZwz9cj1ytrolpgw50tiksZ /]# docker ps -a
CONTAINER ID   IMAGE        COMMAND             CREATED             STATUS             PORTS                     NAMES
06dc90dd704e   tomcat:7.0   "catalina.sh run"   About an hour ago   Up About an hour   0.0.0.0:49157->8080/tcp   tomcat02
2e205f080b85   tomcat:7.0   "catalina.sh run"   2 hours ago         Up 2 hours         0.0.0.0:49156->8080/tcp   tomcat01
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker exec -it tomcat02 ping tomcat01
ping: tomcat01: Name or service not known
[root@iZwz9cj1ytrolpgw50tiksZ /]# 

# 思考:如何直接通过 tomcat01 这个容器名字直接ping通呢?而不是ping tomcat01的ip地址。使用 --link 

# 通过 --link 来解决这个问题
# 启动tomcat03容器,tomcat03可以直接通过tomcat02的容器名字ping通,反过来则无法ping通
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker run -d -P --name tomcat03 --link tomcat02 tomcat:7.0
65de959793345065b24b252490dad0f740c4f7d69c92353e938d4d73af78b7f0
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker exec -it tomcat03 ping tomcat02
PING tomcat02 (172.17.0.3) 56(84) bytes of data.
64 bytes from tomcat02 (172.17.0.3): icmp_seq=1 ttl=64 time=0.140 ms
64 bytes from tomcat02 (172.17.0.3): icmp_seq=2 ttl=64 time=0.106 ms
64 bytes from tomcat02 (172.17.0.3): icmp_seq=3 ttl=64 time=0.128 ms
64 bytes from tomcat02 (172.17.0.3): icmp_seq=4 ttl=64 time=0.109 ms
^C
--- tomcat02 ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 0.106/0.120/0.140/0.019 ms

# 反过来则无法ping通
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker exec -it tomcat02 ping tomcat03
ping: tomcat03: Name or service not known
[root@iZwz9cj1ytrolpgw50tiksZ /]# 

# --link 的原理探究
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker exec -it tomcat03 cat /etc/hosts
127.0.0.1	localhost
::1	localhost ip6-localhost ip6-loopback
fe00::0	ip6-localnet
ff00::0	ip6-mcastprefix
ff02::1	ip6-allnodes
ff02::2	ip6-allrouters
172.17.0.3	tomcat02 06dc90dd704e # --link 就是在hosts配置中增加了一个tomcat02的映射,所以我们的tomcat03可以通过tomcat02的容器名直接ping通
172.17.0.4	65de95979334
[root@iZwz9cj1ytrolpgw50tiksZ /]# 

查看docker网络配置

# 查看一下docker的网络
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker network --help

Usage:  docker network COMMAND

Manage networks

Commands:
  connect     Connect a container to a network
  create      Create a network
  disconnect  Disconnect a container from a network
  inspect     Display detailed information on one or more networks
  ls          List networks
  prune       Remove all unused networks
  rm          Remove one or more networks

Run 'docker network COMMAND --help' for more information on a command.
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker network ls # 查看一下docker的网络
NETWORK ID     NAME      DRIVER    SCOPE
2ae1b6cc0e45   bridge    bridge    local
70e167929bc6   host      host      local
6b2e507e4080   none      null      local
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker network inspect 2ae1b6cc0e45
[
    {
        "Name": "bridge",
        "Id": "2ae1b6cc0e45cd99e9c8097a20e3076dc555788ac916da6bff4bd982dded53cc",
        "Created": "2022-08-07T17:31:18.220127161+08:00",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": null,
            "Config": [
                {
                    "Subnet": "172.17.0.0/16",
                    "Gateway": "172.17.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {
            "06dc90dd704e04ddac671b7042ae8f430e8a2c8c9516ce5fecfcb13e71ee6abf": {
                "Name": "tomcat02",
                "EndpointID": "2a72b4d2a5d54257ef2d0376e0235bedac0f5f5759326346e5d80edbe1b187ec",
                "MacAddress": "02:42:ac:11:00:03",
                "IPv4Address": "172.17.0.3/16",
                "IPv6Address": ""
            },
            "2e205f080b85b96fc1c2e8b972869832d82fba0c3f8dc8214e9176c41368b1a7": {
                "Name": "tomcat01",
                "EndpointID": "6093996f3da4e23d8a6bc7c2dd806b985609e243049a0da830a395d92328fc2a",
                "MacAddress": "02:42:ac:11:00:02",
                "IPv4Address": "172.17.0.2/16",
                "IPv6Address": ""
            },
            "65de959793345065b24b252490dad0f740c4f7d69c92353e938d4d73af78b7f0": {
                "Name": "tomcat03",
                "EndpointID": "7a1f64c446d47cd46de6ade37be780394839765e6fecff3f8943b88b6c61a8c4",
                "MacAddress": "02:42:ac:11:00:04",
                "IPv4Address": "172.17.0.4/16",
                "IPv6Address": ""
            }
        },
        "Options": {
            "com.docker.network.bridge.default_bridge": "true",
            "com.docker.network.bridge.enable_icc": "true",
            "com.docker.network.bridge.enable_ip_masquerade": "true",
            "com.docker.network.bridge.host_binding_ipv4": "0.0.0.0",
            "com.docker.network.bridge.name": "docker0",
            "com.docker.network.driver.mtu": "1500"
        },
        "Labels": {}
    }
]
[root@iZwz9cj1ytrolpgw50tiksZ /]# 

docker0存在的问题:它不支持通过容器名连接访问。使用 --link 可以解决这个问题

但是我们现在玩Docker已经不建议使用 --link 了!

我们通常自定义网络,不使用 docker0 了

自定义网络

使用 --link 和自定义网络都是为了容器互连

# 1、查看所有的docker网络
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker network ls
NETWORK ID     NAME      DRIVER    SCOPE
2ae1b6cc0e45   bridge    bridge    local
70e167929bc6   host      host      local
6b2e507e4080   none      null      local
[root@iZwz9cj1ytrolpgw50tiksZ /]# 

# 网络模式
#	bridge:桥接模式,桥接docker(默认)
#	none:不配置网络
#	host:主机模式,和宿主机共享网络
#	container:容器内网络连通(用得少,了解即可)

# 我们之前启动的命令默认就会有 --net bridge ,而这个就是我们的docker0
# docker run -d -P --name tomcat01 tomcat:7.0
# docker run -d -P --name tomcat01 --net bridge tomcat:7.0

# 2、我们自定义一个docker网络
#	--driver bridge 桥接模式
#	--subnet 192.168.0.0/16 子网地址
#	--gateway 192.168.0.1 网关地址
[root@iZwz9cj1ytrolpgw50tiksZ /]# ip addr # 先查看一下网卡
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 00:16:3e:12:41:aa brd ff:ff:ff:ff:ff:ff
    inet 172.22.201.59/20 brd 172.22.207.255 scope global dynamic eth0
       valid_lft 313214402sec preferred_lft 313214402sec
3: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default 
    link/ether 02:42:70:7c:58:9f brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
       valid_lft forever preferred_lft forever
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker network create --driver bridge --subnet 192.168.0.0/16 --gateway 192.168.0.1 mynet 
ec8a763caf1d574d289b39e096f282736c0ea37aa5bd2681a1505959805cb17e
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker network ls # 查看docker网络
NETWORK ID     NAME      DRIVER    SCOPE
2ae1b6cc0e45   bridge    bridge    local
70e167929bc6   host      host      local
ec8a763caf1d   mynet     bridge    local # 这就是我们自定义的docker网络
6b2e507e4080   none      null      local
[root@iZwz9cj1ytrolpgw50tiksZ /]# ip addr # 再次查看一下网卡
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 00:16:3e:12:41:aa brd ff:ff:ff:ff:ff:ff
    inet 172.22.201.59/20 brd 172.22.207.255 scope global dynamic eth0
       valid_lft 313213333sec preferred_lft 313213333sec
3: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default 
    link/ether 02:42:70:7c:58:9f brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
       valid_lft forever preferred_lft forever
170: br-ec8a763caf1d: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default 
    link/ether 02:42:ed:46:1f:07 brd ff:ff:ff:ff:ff:ff
    inet 192.168.0.1/16 brd 192.168.255.255 scope global br-ec8a763caf1d
       valid_lft forever preferred_lft forever
[root@iZwz9cj1ytrolpgw50tiksZ /]# 

# 3、查看自定义的docker网络 mynet 的详情,到此为止我们自己的docker网络就配置好了
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker network inspect mynet
[
    {
        "Name": "mynet",
        "Id": "ec8a763caf1d574d289b39e096f282736c0ea37aa5bd2681a1505959805cb17e",
        "Created": "2022-08-12T12:08:25.279776938+08:00",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": {},
            "Config": [
                {
                    "Subnet": "192.168.0.0/16",
                    "Gateway": "192.168.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {},
        "Options": {},
        "Labels": {}
    }
]
[root@iZwz9cj1ytrolpgw50tiksZ /]# 

# 4、启动两个tomcat容器,都放到我们自定义的docker网络 mynet 下。
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker run -d -P --name tomcatmynet-01 --net mynet tomcat:7.0
adbf84d9b2be4a126d6fec594e41257b6e1c8aefc65d92205a2423be18eb947a
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker run -d -P --name tomcatmynet-02 --net mynet tomcat:7.0
c54de8029e2b31ac38698e962a9665873c5a0eaac0dbc48ba2f3aa157770331c
[root@iZwz9cj1ytrolpgw50tiksZ /]# 

# 5、再次查看自定义的docker网络 mynet 的详情
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker network inspect mynet
[
    {
        "Name": "mynet",
        "Id": "ec8a763caf1d574d289b39e096f282736c0ea37aa5bd2681a1505959805cb17e",
        "Created": "2022-08-12T12:08:25.279776938+08:00",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": {},
            "Config": [
                {
                    "Subnet": "192.168.0.0/16",
                    "Gateway": "192.168.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {
            "adbf84d9b2be4a126d6fec594e41257b6e1c8aefc65d92205a2423be18eb947a": {
                "Name": "tomcatmynet-01",
                "EndpointID": "a1a3a085bcfa1bd03058629f31170f481a89673ebecbae00758de3af6802f280",
                "MacAddress": "02:42:c0:a8:00:02",
                "IPv4Address": "192.168.0.2/16",
                "IPv6Address": ""
            },
            "c54de8029e2b31ac38698e962a9665873c5a0eaac0dbc48ba2f3aa157770331c": {
                "Name": "tomcatmynet-02",
                "EndpointID": "a948b0ac75e2b0df68b71548f6f38c7762e817500ff813cbc7cbb26e681f0abc",
                "MacAddress": "02:42:c0:a8:00:03",
                "IPv4Address": "192.168.0.3/16",
                "IPv6Address": ""
            }
        },
        "Options": {},
        "Labels": {}
    }
]
[root@iZwz9cj1ytrolpgw50tiksZ /]# 

# 6、tomcatmynet-01 通过 tomcatmynet-02的ip或者容器名字 都可以直接ping通 tomcatmynet-02
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker exec -it tomcatmynet-01 ping 192.168.0.3
PING 192.168.0.3 (192.168.0.3) 56(84) bytes of data.
64 bytes from 192.168.0.3: icmp_seq=1 ttl=64 time=0.126 ms
64 bytes from 192.168.0.3: icmp_seq=2 ttl=64 time=0.100 ms
64 bytes from 192.168.0.3: icmp_seq=3 ttl=64 time=0.107 ms
^C
--- 192.168.0.3 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 1000ms
rtt min/avg/max/mdev = 0.100/0.111/0.126/0.011 ms
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker exec -it tomcatmynet-01 ping tomcatmynet-02
PING tomcatmynet-02 (192.168.0.3) 56(84) bytes of data.
64 bytes from tomcatmynet-02.mynet (192.168.0.3): icmp_seq=1 ttl=64 time=0.081 ms
64 bytes from tomcatmynet-02.mynet (192.168.0.3): icmp_seq=2 ttl=64 time=0.119 ms
64 bytes from tomcatmynet-02.mynet (192.168.0.3): icmp_seq=3 ttl=64 time=0.125 ms
^C
--- tomcatmynet-02 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 0.081/0.108/0.125/0.021 ms
[root@iZwz9cj1ytrolpgw50tiksZ /]# 

推荐使用自定义网络

场景应用:redis的集群是一个网络,mysql的集群是一个网络,…等等,不同集群的网络不同,互相隔离,能够保证集群的安全

在这里插入图片描述

不同集群的网络虽然互相隔离,但也是有办法可以连通的。接下来我们就学习网络连通

网络连通

# 1、我们再启动两个容器tomcat,这两个容器默认属于docker0的网络
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker run -d -P --name tomcat01 tomcat:7.0
7230a851125258612ae33b8c65cae467f02a8c13b3c20cec42c47d092500a84e
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker run -d -P --name tomcat02 tomcat:7.0
b11b2df3ab733f5230b350b51e3a522411a281eb795c8d094c4151575282d768
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker ps
CONTAINER ID   IMAGE        COMMAND             CREATED          STATUS          PORTS                     NAMES
b11b2df3ab73   tomcat:7.0   "catalina.sh run"   8 seconds ago    Up 7 seconds    0.0.0.0:49162->8080/tcp   tomcat02
7230a8511252   tomcat:7.0   "catalina.sh run"   12 seconds ago   Up 10 seconds   0.0.0.0:49161->8080/tcp   tomcat01
c54de8029e2b   tomcat:7.0   "catalina.sh run"   2 hours ago      Up 2 hours      0.0.0.0:49160->8080/tcp   tomcatmynet-02
adbf84d9b2be   tomcat:7.0   "catalina.sh run"   2 hours ago      Up 2 hours      0.0.0.0:49159->8080/tcp   tomcatmynet-01
[root@iZwz9cj1ytrolpgw50tiksZ /]# 

# 2、tomcat01现在无法ping通tomcatmynet-01
# 	因为tomcat01属于docker0的网络,tomcatmynet-01属于自定义的mynet网络
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker exec -it tomcat01 ping tomcatmynet-01
ping: tomcatmynet-01: Name or service not known
[root@iZwz9cj1ytrolpgw50tiksZ /]# 


# 3、tomcat01需要ping通tomcatmynet-01的解决办法如下
# 	把tomcat01连接到mynet网络中即可
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker network connect mynet tomcat01

# 4、查看mynet网络的详情信息,发现tomcat01被放到了mynet网络下!
#	对于tomcat01容器来讲,就是一个容器拥有两个IP地址!
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker network inspect mynet
[
    {
        "Name": "mynet",
        "Id": "ec8a763caf1d574d289b39e096f282736c0ea37aa5bd2681a1505959805cb17e",
        "Created": "2022-08-12T12:08:25.279776938+08:00",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": {},
            "Config": [
                {
                    "Subnet": "192.168.0.0/16",
                    "Gateway": "192.168.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {
            "7230a851125258612ae33b8c65cae467f02a8c13b3c20cec42c47d092500a84e": {
                "Name": "tomcat01",
                "EndpointID": "03ed83630cffbf3e3043f42e6ea02279981dc3afbe4672641606a3df492e7adb",
                "MacAddress": "02:42:c0:a8:00:04",
                "IPv4Address": "192.168.0.4/16",
                "IPv6Address": ""
            },
            "adbf84d9b2be4a126d6fec594e41257b6e1c8aefc65d92205a2423be18eb947a": {
                "Name": "tomcatmynet-01",
                "EndpointID": "a1a3a085bcfa1bd03058629f31170f481a89673ebecbae00758de3af6802f280",
                "MacAddress": "02:42:c0:a8:00:02",
                "IPv4Address": "192.168.0.2/16",
                "IPv6Address": ""
            },
            "c54de8029e2b31ac38698e962a9665873c5a0eaac0dbc48ba2f3aa157770331c": {
                "Name": "tomcatmynet-02",
                "EndpointID": "a948b0ac75e2b0df68b71548f6f38c7762e817500ff813cbc7cbb26e681f0abc",
                "MacAddress": "02:42:c0:a8:00:03",
                "IPv4Address": "192.168.0.3/16",
                "IPv6Address": ""
            }
        },
        "Options": {},
        "Labels": {}
    }
]
[root@iZwz9cj1ytrolpgw50tiksZ /]# 


# 5、现在tomcat01即可ping通tomcatmynet-01
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker exec -it tomcat01 ping tomcatmynet-01
PING tomcatmynet-01 (192.168.0.2) 56(84) bytes of data.
64 bytes from tomcatmynet-01.mynet (192.168.0.2): icmp_seq=1 ttl=64 time=0.110 ms
64 bytes from tomcatmynet-01.mynet (192.168.0.2): icmp_seq=2 ttl=64 time=0.113 ms
^C
--- tomcatmynet-01 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1ms
rtt min/avg/max/mdev = 0.110/0.111/0.113/0.010 ms
[root@iZwz9cj1ytrolpgw50tiksZ /]# 

实战:部署Redis集群

在这里插入图片描述

我们要手动启动6个容器,耗费时间,我们编写shell脚本

1、我们先自定义Redis集群的网络

# 自定义Redis集群的网络
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker network create redis --subnet 172.38.0.0/16
6f79f0a21b1fa1b8135204a352c62bb2880b4b7c599e1e623029766c66402728
[root@iZwz9cj1ytrolpgw50tiksZ /]# docker network ls
NETWORK ID     NAME      DRIVER    SCOPE
2ae1b6cc0e45   bridge    bridge    local
70e167929bc6   host      host      local
ec8a763caf1d   mynet     bridge    local
6b2e507e4080   none      null      local
6f79f0a21b1f   redis     bridge    local
[root@iZwz9cj1ytrolpgw50tiksZ /]# 

2、通过脚本创建六个Redis配置

for port in $(seq 1 6); \
do \
mkdir -p /mydata/redis/node-${port}/conf
touch /mydata/redis/node-${port}/conf/redis.conf
cat << EOF >/mydata/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 172.38.0.1${port}
cluster-announce-port 6379
cluster-announce-bus-port 16379
appendonly yes
EOF
done

# 具体执行过程如下,把上面的脚本内容直接复制到终端执行即可
[root@iZwz9cj1ytrolpgw50tiksZ /]# for port in $(seq 1 6); \
> do \
> mkdir -p /mydata/redis/node-${port}/conf
> touch /mydata/redis/node-${port}/conf/redis.conf
> cat << EOF >/mydata/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 172.38.0.1${port}
> cluster-announce-port 6379
> cluster-announce-bus-port 16379
> appendonly yes
> EOF
> done
[root@iZwz9cj1ytrolpgw50tiksZ /]# cd /mydata/
[root@iZwz9cj1ytrolpgw50tiksZ mydata]# ls
redis
[root@iZwz9cj1ytrolpgw50tiksZ mydata]# cd redis/
[root@iZwz9cj1ytrolpgw50tiksZ redis]# ls
node-1  node-2  node-3  node-4  node-5  node-6
[root@iZwz9cj1ytrolpgw50tiksZ redis]# cd node-1/
[root@iZwz9cj1ytrolpgw50tiksZ node-1]# ls 
conf
[root@iZwz9cj1ytrolpgw50tiksZ node-1]# cd conf/
[root@iZwz9cj1ytrolpgw50tiksZ conf]# ls
redis.conf
[root@iZwz9cj1ytrolpgw50tiksZ conf]# cat redis.conf 
port 6379
bind 0.0.0.0
cluster-enabled yes
cluster-config-file nodes.conf
cluster-node-timeout 5000
cluster-announce-ip 172.38.0.11
cluster-announce-port 6379
cluster-announce-bus-port 16379
appendonly yes
[root@iZwz9cj1ytrolpgw50tiksZ conf]# 

3、分别把下面6个内容复制到终端执行,即可分别启动6个Redis容器

docker run -p 6371:6379 -p 16371:16379 --name redis-1 \
-v /mydata/redis/node-1/data:/data \
-v /mydata/redis/node-1/conf/redis.conf:/etc/redis/redis.conf \
-d --net redis --ip 172.38.0.11 redis:5.0.9-alpine3.11 redis-server /etc/redis/redis.conf

===========================================================================================

docker run -p 6372:6379 -p 16372:16379 --name redis-2 \
-v /mydata/redis/node-2/data:/data \
-v /mydata/redis/node-2/conf/redis.conf:/etc/redis/redis.conf \
-d --net redis --ip 172.38.0.12 redis:5.0.9-alpine3.11 redis-server /etc/redis/redis.conf

===========================================================================================

docker run -p 6373:6379 -p 16373:16379 --name redis-3 \
-v /mydata/redis/node-3/data:/data \
-v /mydata/redis/node-3/conf/redis.conf:/etc/redis/redis.conf \
-d --net redis --ip 172.38.0.13 redis:5.0.9-alpine3.11 redis-server /etc/redis/redis.conf

===========================================================================================

docker run -p 6374:6379 -p 16374:16379 --name redis-4 \
-v /mydata/redis/node-4/data:/data \
-v /mydata/redis/node-4/conf/redis.conf:/etc/redis/redis.conf \
-d --net redis --ip 172.38.0.14 redis:5.0.9-alpine3.11 redis-server /etc/redis/redis.conf

===========================================================================================

docker run -p 6375:6379 -p 16375:16379 --name redis-5 \
-v /mydata/redis/node-5/data:/data \
-v /mydata/redis/node-5/conf/redis.conf:/etc/redis/redis.conf \
-d --net redis --ip 172.38.0.15 redis:5.0.9-alpine3.11 redis-server /etc/redis/redis.conf

===========================================================================================

docker run -p 6376:6379 -p 16376:16379 --name redis-6 \
-v /mydata/redis/node-6/data:/data \
-v /mydata/redis/node-6/conf/redis.conf:/etc/redis/redis.conf \
-d --net redis --ip 172.38.0.16 redis:5.0.9-alpine3.11 redis-server /etc/redis/redis.conf

成功启动6个Redis容器

在这里插入图片描述

4、创建集群

[root@iZwz9cj1ytrolpgw50tiksZ conf]# docker exec -it redis-1 /bin/sh
/data # ls
appendonly.aof  nodes.conf
/data # redis-cli --cluster create 172.38.0.11:6379 172.38.0.12:6379 172.38.0.13:6379 172.38.0.14:6379 172.38.0.15:6379 172.38.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 172.38.0.15:6379 to 172.38.0.11:6379
Adding replica 172.38.0.16:6379 to 172.38.0.12:6379
Adding replica 172.38.0.14:6379 to 172.38.0.13:6379
M: 85af56a7b856323d5faff26d3a06ba4cf9afaf7c 172.38.0.11:6379
   slots:[0-5460] (5461 slots) master
M: 510567401523b85641a5cfc4fd7e1ae84d38b9cb 172.38.0.12:6379
   slots:[5461-10922] (5462 slots) master
M: ed82a717f014ccc2b9e3889bc4e948781eca8e25 172.38.0.13:6379
   slots:[10923-16383] (5461 slots) master
S: 2c544f142577ae62cbd094021ffb09f77da0a047 172.38.0.14:6379
   replicates ed82a717f014ccc2b9e3889bc4e948781eca8e25
S: 9a72f0e0b15c2ed52247a76d8d04db6777fa4faf 172.38.0.15:6379
   replicates 85af56a7b856323d5faff26d3a06ba4cf9afaf7c
S: 0d99e1a318d3e1667727f93335b04d7f5a9dc28e 172.38.0.16:6379
   replicates 510567401523b85641a5cfc4fd7e1ae84d38b9cb
Can I set the above configuration? (type 'yes' to accept): yes # 这里输入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 172.38.0.11:6379)
M: 85af56a7b856323d5faff26d3a06ba4cf9afaf7c 172.38.0.11:6379
   slots:[0-5460] (5461 slots) master
   1 additional replica(s)
M: ed82a717f014ccc2b9e3889bc4e948781eca8e25 172.38.0.13:6379
   slots:[10923-16383] (5461 slots) master
   1 additional replica(s)
S: 0d99e1a318d3e1667727f93335b04d7f5a9dc28e 172.38.0.16:6379
   slots: (0 slots) slave
   replicates 510567401523b85641a5cfc4fd7e1ae84d38b9cb
M: 510567401523b85641a5cfc4fd7e1ae84d38b9cb 172.38.0.12:6379
   slots:[5461-10922] (5462 slots) master
   1 additional replica(s)
S: 9a72f0e0b15c2ed52247a76d8d04db6777fa4faf 172.38.0.15:6379
   slots: (0 slots) slave
   replicates 85af56a7b856323d5faff26d3a06ba4cf9afaf7c
S: 2c544f142577ae62cbd094021ffb09f77da0a047 172.38.0.14:6379
   slots: (0 slots) slave
   replicates ed82a717f014ccc2b9e3889bc4e948781eca8e25
[OK] All nodes agree about slots configuration.
>>> Check for open slots...
>>> Check slots coverage...
[OK] All 16384 slots covered.
/data # 

5、查看集群情况

/data # redis-cli -c # 集群访问
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 # 当前集群的数量是3,还有另外3个是从机
cluster_current_epoch:6
cluster_my_epoch:1
cluster_stats_messages_ping_sent:233
cluster_stats_messages_pong_sent:229
cluster_stats_messages_sent:462
cluster_stats_messages_ping_received:224
cluster_stats_messages_pong_received:233
cluster_stats_messages_meet_received:5
cluster_stats_messages_received:462
127.0.0.1:6379> cluster nodes # 查看集群的节点信息,我们可以看到三个主机master,三个从机slave
ed82a717f014ccc2b9e3889bc4e948781eca8e25 172.38.0.13:6379@16379 master - 0 1660290400000 3 connected 10923-16383
85af56a7b856323d5faff26d3a06ba4cf9afaf7c 172.38.0.11:6379@16379 myself,master - 0 1660290399000 1 connected 0-5460
0d99e1a318d3e1667727f93335b04d7f5a9dc28e 172.38.0.16:6379@16379 slave 510567401523b85641a5cfc4fd7e1ae84d38b9cb 0 1660290399546 6 connected
510567401523b85641a5cfc4fd7e1ae84d38b9cb 172.38.0.12:6379@16379 master - 0 1660290400247 2 connected 5461-10922
9a72f0e0b15c2ed52247a76d8d04db6777fa4faf 172.38.0.15:6379@16379 slave 85af56a7b856323d5faff26d3a06ba4cf9afaf7c 0 1660290400549 5 connected
2c544f142577ae62cbd094021ffb09f77da0a047 172.38.0.14:6379@16379 slave ed82a717f014ccc2b9e3889bc4e948781eca8e25 0 1660290400000 4 connected
127.0.0.1:6379> set a b
-> Redirected to slot [15495] located at 172.38.0.13:6379
OK
172.38.0.13:6379> 

6、测试

在这里插入图片描述

SpringBoot微服务打包成Docker镜像

1、创建一个SpringBoot项目,勾选Spring Web依赖,写一个基本的helloworld即可!

2、打包应用

在这里插入图片描述

3、下载docker插件,编写Dockerfile文件

在这里插入图片描述

在这里插入图片描述

4、把jar包和Dockerfile文件上传到服务器

在这里插入图片描述

5、构建镜像

[root@iZwz9cj1ytrolpgw50tiksZ idea]# pwd
/home/idea
[root@iZwz9cj1ytrolpgw50tiksZ idea]# ls
docker-demo01-0.0.1-SNAPSHOT.jar  Dockerfile
[root@iZwz9cj1ytrolpgw50tiksZ idea]# docker build -t kuangshen666 . # 直接构建镜像即可
Sending build context to Docker daemon  17.63MB
Step 1/5 : FROM java:8
8: Pulling from library/java
5040bd298390: Pull complete 
fce5728aad85: Pull complete 
76610ec20bf5: Pull complete 
60170fec2151: Pull complete 
e98f73de8f0d: Pull complete 
11f7af24ed9c: Pull complete 
49e2d6393f32: Pull complete 
bb9cdec9c7f3: Pull complete 
Digest: sha256:c1ff613e8ba25833d2e1940da0940c3824f03f802c449f3d1815a66b7f8c0e9d
Status: Downloaded newer image for java:8
 ---> d23bdf5b1b1b
Step 2/5 : COPY *.jar /app.jar
 ---> 0b62e840b908
Step 3/5 : CMD ["--server.port=8080"]
 ---> Running in 086763fe4b37
Removing intermediate container 086763fe4b37
 ---> 2922de34e0a8
Step 4/5 : EXPOSE 8080
 ---> Running in 59836d37348d
Removing intermediate container 59836d37348d
 ---> dc24e5eae0d0
Step 5/5 : ENTRYPOINT ["java","-jar","/app.jar"]
 ---> Running in c812bacea6ea
Removing intermediate container c812bacea6ea
 ---> fee45d5e4148
Successfully built fee45d5e4148
Successfully tagged kuangshen666:latest
[root@iZwz9cj1ytrolpgw50tiksZ idea]# docker images
REPOSITORY     TAG                IMAGE ID       CREATED         SIZE
kuangshen666   latest             fee45d5e4148   2 minutes ago   661MB
tomcat         7.0                9dfd74e6bc2f   13 months ago   533MB
redis          5.0.9-alpine3.11   3661c84ee9d0   2 years ago     29.8MB
java           8                  d23bdf5b1b1b   5 years ago     643MB
[root@iZwz9cj1ytrolpgw50tiksZ idea]# 

6、运行测试即可

[root@iZwz9cj1ytrolpgw50tiksZ idea]# docker run -d -P --name kuangshen-springboot-web kuangshen666
efeda6ad3a303656b108f62b7db39ebe87d691fea6284d820a6c57f2c368f5e0
[root@iZwz9cj1ytrolpgw50tiksZ idea]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                  CREATED         STATUS         PORTS                     NAMES
efeda6ad3a30   kuangshen666   "java -jar /app.jar …"   5 seconds ago   Up 4 seconds   0.0.0.0:49164->8080/tcp   kuangshen-springboot-web
[root@iZwz9cj1ytrolpgw50tiksZ idea]# curl localhost:49164
{"timestamp":"2022-08-12T09:15:49.732+00:00","status":404,"error":"Not Found","path":"/"}
[root@iZwz9cj1ytrolpgw50tiksZ idea]# curl localhost:49164/hello # 访问成功
hello,kuangshen
[root@iZwz9cj1ytrolpgw50tiksZ idea]# 

我们使用了Docker之后,给别人交付的就是一个镜像即可!

=接下来是Docker进阶内容=

Docker Compose

什么是Docker Compose?

**我们之前:**写完一个微服务—>手动编写Dockerfile—>手动build构建镜像—>手动run运行镜像,创建容器

**问题出现:**假如我们的项目有一百个微服务,我们就要手动操作一百次这样的流程?这些微服务之间还有依赖关系需要处理,手动操作十分麻烦,并且容易出问题。

**问题解决:**使用Docker Compose来轻松高效地管理容器。

官方文档关于Docker Compose的介绍:

Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file to configure your application’s services. Then, with a single command, you create and start all the services from your configuration. To learn more about all the features of Compose, see the list of features.

Compose works in all environments: production, staging, development, testing, as well as CI workflows. You can learn more about each case in Common Use Cases.

Using Compose is basically a three-step process:

  1. Define your app’s environment with a Dockerfile so it can be reproduced anywhere.
  2. Define the services that make up your app in docker-compose.yml so they can be run together in an isolated environment.
  3. Run docker compose up and the Docker compose command starts and runs your entire app. You can alternatively run docker-compose up using Compose standalone(docker-compose binary).

总结一句话:Docker Compose的作用主要是进行批量容器编排。

学前须知

  • Compose 是Docker官方的开源项目,需要先安装!

  • 官方文档:

    A docker-compose.yml looks like this:

    version: "3.9"  # optional since v1.27.0
    services:
      web:
        build: .
        ports:
          - "8000:5000"
        volumes:
          - .:/code
          - logvolume01:/var/log
        depends_on:
          - redis
      redis:
        image: redis
    volumes:
      logvolume01: {}
    
  • Compose 有两个重要的概念

    • 服务services
    • 项目project(一个项目通常包括多个服务,web、redis、mysql、nginx、…等等。每个服务相当于容器)

安装Docker Compose

1、下载

[root@iZwz9cj1ytrolpgw50tiksZ home]# curl -L https://get.daocloud.io/docker/compose/releases/download/1.25.5/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   423  100   423    0     0    214      0  0:00:01  0:00:01 --:--:--   214
100 16.7M  100 16.7M    0     0  6374k      0  0:00:02  0:00:02 --:--:-- 6374k
[root@iZwz9cj1ytrolpgw50tiksZ home]# cd /usr/local/bin
[root@iZwz9cj1ytrolpgw50tiksZ bin]# ll
total 50260
-rw-r--r-- 1 root root    19536 Jul 28 17:52 6379.log
-rw-r--r-- 1 root root   123916 Jul 28 17:52 6380.log
-rw-r--r-- 1 root root    90455 Jul 28 17:53 6381.log
-rw-r--r-- 1 root root      139 Jul 27 17:23 appendonly.aof
-rwxr-xr-x 1 root root      388 Apr 26  2020 chardetect
-rwxr-xr-x 1 root root      396 Apr 26  2020 cloud-id
-rwxr-xr-x 1 root root      400 Apr 26  2020 cloud-init
-rwxr-xr-x 1 root root     2108 Apr 26  2020 cloud-init-per
-rw-r--r-- 1 root root 17586312 Aug 13 13:27 docker-compose # 这就是我们下载的 docker-compose 
-rw-r--r-- 1 root root      218 Jul 28 17:52 dump6379.rdb
-rw-r--r-- 1 root root      218 Jul 28 17:52 dump6380.rdb
-rw-r--r-- 1 root root      218 Jul 28 17:53 dump6381.rdb
-rw-r--r-- 1 root root      125 Jul 28 11:23 dump.rdb
-rwxr-xr-x 1 root root      404 Apr 26  2020 easy_install
-rwxr-xr-x 1 root root      234 Apr 26  2020 easy_install-3.6
-rwxr-xr-x 1 root root      412 Apr 26  2020 easy_install-3.8
-rwxr-xr-x 1 root root     1003 Apr 26  2020 jsondiff
-rwxr-xr-x 1 root root     3661 Apr 26  2020 jsonpatch
-rwxr-xr-x 1 root root     1837 Apr 26  2020 jsonpointer
-rwxr-xr-x 1 root root      397 Apr 26  2020 jsonschema
drwxr-xr-x 2 root root     4096 Jul 28 16:04 kconfig
-rwxr-xr-x 1 root root  4366816 Jul 23 22:37 redis-benchmark
-rwxr-xr-x 1 root root  8125232 Jul 23 22:37 redis-check-aof
-rwxr-xr-x 1 root root  8125232 Jul 23 22:37 redis-check-rdb
-rwxr-xr-x 1 root root  4807880 Jul 23 22:37 redis-cli
lrwxrwxrwx 1 root root       12 Jul 23 22:37 redis-sentinel -> redis-server
-rwxr-xr-x 1 root root  8125232 Jul 23 22:37 redis-server
[root@iZwz9cj1ytrolpgw50tiksZ bin]# 

2、授权

[root@iZwz9cj1ytrolpgw50tiksZ bin]# sudo chmod +x /usr/local/bin/docker-compose

3、查看是否安装成功

[root@iZwz9cj1ytrolpgw50tiksZ bin]# docker-compose version
docker-compose version 1.25.5, build 8a1c60f6
docker-py version: 4.1.0
CPython version: 3.7.5
OpenSSL version: OpenSSL 1.1.0l  10 Sep 2019
[root@iZwz9cj1ytrolpgw50tiksZ bin]# 

Docker Compose的快速入门体验

官方快速体验docker compose的文档:https://docs.docker.com/compose/gettingstarted/

主要为以下五个步骤:

1、编写app.py

2、编写requirements.txt

3、编写Dockerfile

4、编写docker-compose.yml,定义了整个服务需要的环境

5、执行命令:docker compose up

停止docker compose的两种方式

  • 在对应的目录下,执行命令:docker-compose down
  • 直接Ctrl+C
[root@iZwz9cj1ytrolpgw50tiksZ home]# pwd
/home
[root@iZwz9cj1ytrolpgw50tiksZ home]# mkdir composetest
[root@iZwz9cj1ytrolpgw50tiksZ home]# cd composetest
[root@iZwz9cj1ytrolpgw50tiksZ composetest]# pwd
/home/composetest
[root@iZwz9cj1ytrolpgw50tiksZ composetest]# ll
total 0
[root@iZwz9cj1ytrolpgw50tiksZ composetest]# vim app.py
[root@iZwz9cj1ytrolpgw50tiksZ composetest]# cat app.py 
import time

import redis
from flask import Flask

app = Flask(__name__)
cache = redis.Redis(host='redis', port=6379)

def get_hit_count():
    retries = 5
    while True:
        try:
            return cache.incr('hits')
        except redis.exceptions.ConnectionError as exc:
            if retries == 0:
                raise exc
            retries -= 1
            time.sleep(0.5)

@app.route('/')
def hello():
    count = get_hit_count()
    return 'Hello World! I have been seen {} times.\n'.format(count)

if __name__ == "__main__":
    app.run(host="0.0.0.0", debug=True)
[root@iZwz9cj1ytrolpgw50tiksZ composetest]# ll
total 4
-rw-r--r-- 1 root root 582 Aug 13 15:34 app.py
[root@iZwz9cj1ytrolpgw50tiksZ composetest]# vim requirements.txt
[root@iZwz9cj1ytrolpgw50tiksZ composetest]# cat requirements.txt 
flask
redis
[root@iZwz9cj1ytrolpgw50tiksZ composetest]# ll
total 8
-rw-r--r-- 1 root root 582 Aug 13 15:34 app.py
-rw-r--r-- 1 root root  12 Aug 13 15:36 requirements.txt
[root@iZwz9cj1ytrolpgw50tiksZ composetest]# vim Dockerfile
[root@iZwz9cj1ytrolpgw50tiksZ composetest]# cat Dockerfile 
FROM python:3.6-alpine
ADD . /code
WORKDIR /code
RUN pip install -r requirements.txt
CMD ["python","app.py"]
[root@iZwz9cj1ytrolpgw50tiksZ composetest]# ll
total 12
-rw-r--r-- 1 root root 582 Aug 13 15:34 app.py
-rw-r--r-- 1 root root 109 Aug 13 15:41 Dockerfile
-rw-r--r-- 1 root root  12 Aug 13 15:36 requirements.txt
[root@iZwz9cj1ytrolpgw50tiksZ composetest]# vim docker-compose.yml
[root@iZwz9cj1ytrolpgw50tiksZ composetest]# cat docker-compose.yml 
version: '3.8'
services:
  web:
    build: .
    ports:
      - "5000:5000"
    volumes:
      - .:/code
  redis:
    image: "redis:alpine"
[root@iZwz9cj1ytrolpgw50tiksZ composetest]# ll
total 16
-rw-r--r-- 1 root root 582 Aug 13 15:34 app.py
-rw-r--r-- 1 root root 140 Aug 13 15:45 docker-compose.yml
-rw-r--r-- 1 root root 109 Aug 13 15:41 Dockerfile
-rw-r--r-- 1 root root  12 Aug 13 15:36 requirements.txt
[root@iZwz9cj1ytrolpgw50tiksZ composetest]# 
[root@iZwz9cj1ytrolpgw50tiksZ composetest]# docker-compose up


正常启动成功的效果

在这里插入图片描述

测试一下:

[root@iZwz9cj1ytrolpgw50tiksZ composetest]# docker images # 查看一下镜像
REPOSITORY        TAG          IMAGE ID       CREATED         SIZE
composetest_web   latest       703de2c40555   5 minutes ago   55.5MB
redis             alpine       3900abf41552   8 months ago    32.4MB
python            3.6-alpine   3a9e80fa4606   8 months ago    40.7MB
[root@iZwz9cj1ytrolpgw50tiksZ composetest]# docker ps # 查看容器进程,服务启动正常
CONTAINER ID   IMAGE             COMMAND                  CREATED              STATUS              PORTS                    NAMES
038cd55370ae   composetest_web   "python app.py"          About a minute ago   Up About a minute   0.0.0.0:5000->5000/tcp   composetest_web_1
c0f6f3433fcb   redis:alpine      "docker-entrypoint.s…"   About a minute ago   Up About a minute   6379/tcp                 composetest_redis_1
[root@iZwz9cj1ytrolpgw50tiksZ composetest]# curl localhost:5000 # 访问测试一下
Hello World! I have been seen 1 times.
[root@iZwz9cj1ytrolpgw50tiksZ composetest]# curl localhost:5000
Hello World! I have been seen 2 times.
[root@iZwz9cj1ytrolpgw50tiksZ composetest]# curl localhost:5000
Hello World! I have been seen 3 times.
[root@iZwz9cj1ytrolpgw50tiksZ composetest]# curl localhost:5000
Hello World! I have been seen 4 times.
[root@iZwz9cj1ytrolpgw50tiksZ composetest]# curl localhost:5000
Hello World! I have been seen 5 times.
[root@iZwz9cj1ytrolpgw50tiksZ composetest]# docker network ls # 查看一下网络
NETWORK ID     NAME                  DRIVER    SCOPE
2ae1b6cc0e45   bridge                bridge    local
0867f70d356f   composetest_default   bridge    local # 项目中的服务都在同一个网络下面,可以通过容器名访问
70e167929bc6   host                  host      local
ec8a763caf1d   mynet                 bridge    local
6b2e507e4080   none                  null      local
6f79f0a21b1f   redis                 bridge    local
[root@iZwz9cj1ytrolpgw50tiksZ composetest]# docker inspect composetest_default
[
    {
        "Name": "composetest_default",
        "Id": "0867f70d356fada827641f4b79a8918c4ae86b6ca39f8bece1201a9388dea3e1",
        "Created": "2022-08-13T14:47:17.461863033+08:00",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": null,
            "Config": [
                {
                    "Subnet": "172.18.0.0/16",
                    "Gateway": "172.18.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {
            "038cd55370aea1487863d34ac12c70f53e4c0cd10200f551458ef1ece77b360d": {
                "Name": "composetest_web_1",
                "EndpointID": "fed2b05c798a875a45d20e61f12f85995e3afd89147854939a890239a1aa6093",
                "MacAddress": "02:42:ac:12:00:02",
                "IPv4Address": "172.18.0.2/16",
                "IPv6Address": ""
            },
            "c0f6f3433fcb42e03741b5cccfc6c11ec2c9af0c74ea872be0a978d14c89ea88": {
                "Name": "composetest_redis_1",
                "EndpointID": "e753d56cb1a42bf450fe4da65f645c1ff9fd7d84841919ba760d94286df024fa",
                "MacAddress": "02:42:ac:12:00:03",
                "IPv4Address": "172.18.0.3/16",
                "IPv6Address": ""
            }
        },
        "Options": {},
        "Labels": {
            "com.docker.compose.network": "default",
            "com.docker.compose.project": "composetest",
            "com.docker.compose.version": "2.6.0"
        }
    }
]
[root@iZwz9cj1ytrolpgw50tiksZ composetest]# 

以前我们都是逐个手动启动容器

现在我们通过Docker Compose同时启动或者停止多个服务(容器)。

docker-compose.yml的规则

官网文档参考:https://docs.docker.com/compose/compose-file/compose-file-v3/

# 版本
version: ''

# 服务
services:	
  服务1: web
  	# 服务配置
  	images
  	build
  	network
  	......
  服务2: redis
  	......
  服务3: mysql
  	......
  	
# 其它配置
......

使用Docker Compose一键部署启动WordPress

官方文档有一个WordPress:https://docs.docker.com/samples/wordpress/

[root@iZwz9cj1ytrolpgw50tiksZ my_wordpress]# pwd
/home/my_wordpress
[root@iZwz9cj1ytrolpgw50tiksZ my_wordpress]# vim docker-compose.yml
[root@iZwz9cj1ytrolpgw50tiksZ my_wordpress]# cat docker-compose.yml 
version: '3.3'

services:
   db:
     image: mysql:5.7
     volumes:
       - db_data:/var/lib/mysql
     restart: always
     environment:
       MYSQL_ROOT_PASSWORD: somewordpress
       MYSQL_DATABASE: wordpress
       MYSQL_USER: wordpress
       MYSQL_PASSWORD: wordpress

   wordpress:
     depends_on:
       - db
     image: wordpress:latest
     ports:
       - "8000:80"
     restart: always
     environment:
       WORDPRESS_DB_HOST: db:3306
       WORDPRESS_DB_USER: wordpress
       WORDPRESS_DB_PASSWORD: wordpress
       WORDPRESS_DB_NAME: wordpress
volumes:
    db_data: {}
[root@iZwz9cj1ytrolpgw50tiksZ my_wordpress]# docker-compose up # 如果需要后台启动加个 -d 即可!
............
............


=========================================================================
[root@iZwz9cj1ytrolpgw50tiksZ my_wordpress]# docker ps # 查看容器运行情况
CONTAINER ID   IMAGE              COMMAND                  CREATED          STATUS          PORTS                  NAMES
3cce5c880e59   wordpress:latest   "docker-entrypoint.s…"   51 seconds ago   Up 49 seconds   0.0.0.0:8000->80/tcp   my_wordpress_wordpress_1
c1da0400143a   mysql:5.7          "docker-entrypoint.s…"   52 seconds ago   Up 50 seconds   3306/tcp, 33060/tcp    my_wordpress_db_1
[root@iZwz9cj1ytrolpgw50tiksZ my_wordpress]# 

测试效果:现在就是分分钟部署开源项目!

在这里插入图片描述

实战:自己编写微服务上线

1、创建一个SpringBoot项目,勾选依赖

在这里插入图片描述

2、编写代码

在这里插入图片描述

3、编写SpringBoot的配置文件

在这里插入图片描述

4、编写Dockerfile

在这里插入图片描述

5、编写docker-compose.yml

在这里插入图片描述

6、在pom.xml中添加如下代码

在这里插入图片描述

7、打包项目

在这里插入图片描述

8、把docker-compose.yml、Dockerfile和jar包上传到服务器

在这里插入图片描述

9、启动

[root@iZwz9cj1ytrolpgw50tiksZ kuangapp]# pwd
/home/kuangapp
[root@iZwz9cj1ytrolpgw50tiksZ kuangapp]# ls -l
total 27128
-rw-r--r-- 1 root root      177 Aug 14 17:31 docker-compose.yml
-rw-r--r-- 1 root root 27767542 Aug 14 17:31 docker-demo02-0.0.1-SNAPSHOT.jar
-rw-r--r-- 1 root root      122 Aug 14 17:31 Dockerfile
[root@iZwz9cj1ytrolpgw50tiksZ kuangapp]# docker-compose up
......
......

10、测试一下

[root@iZwz9cj1ytrolpgw50tiksZ kuangapp]# docker ps
CONTAINER ID   IMAGE          COMMAND                  CREATED          STATUS          PORTS                    NAMES
5a2b54f4cb8c   kuangapp       "java -jar /app.jar …"   17 seconds ago   Up 16 seconds   0.0.0.0:8001->8001/tcp   kuangapp_kuangapp_1
4abb6aa32696   redis:alpine   "docker-entrypoint.s…"   17 seconds ago   Up 16 seconds   6379/tcp                 kuangapp_redis_1
[root@iZwz9cj1ytrolpgw50tiksZ kuangapp]# curl localhost:8001/hello
hello,kuangshen,thank you! views=1
[root@iZwz9cj1ytrolpgw50tiksZ kuangapp]# curl localhost:8001/hello
hello,kuangshen,thank you! views=2
[root@iZwz9cj1ytrolpgw50tiksZ kuangapp]# curl localhost:8001/hello
hello,kuangshen,thank you! views=3
[root@iZwz9cj1ytrolpgw50tiksZ kuangapp]# curl localhost:8001/hello
hello,kuangshen,thank you! views=4
[root@iZwz9cj1ytrolpgw50tiksZ kuangapp]# curl localhost:8001/hello
hello,kuangshen,thank you! views=5
[root@iZwz9cj1ytrolpgw50tiksZ kuangapp]# curl localhost:8001/hello
hello,kuangshen,thank you! views=6
[root@iZwz9cj1ytrolpgw50tiksZ kuangapp]# 

Docker Swarm

购买服务器

买4台1核2G的服务器即可

1、创建实例

在这里插入图片描述

2、基础配置

在这里插入图片描述

在这里插入图片描述

3、网络和安全组配置

在这里插入图片描述

4、系统配置

在这里插入图片描述

5、分组设置

在这里插入图片描述

6、确认完订单创建实例即可

在这里插入图片描述

在这里插入图片描述

到此服务器购买完毕!

服务器用完后,及时把实例释放。因为是按量付费的!

连接4台服务器,并且配置环境

在这里插入图片描述

  • 给四台服务器同时安装Docker

在这里插入图片描述

在这里插入图片描述

依次执行如下命令

# 1、
yum -y install gcc

# 2、
yum -y install gcc-c++

# 3、
 yum remove docker \
                  docker-client \
                  docker-client-latest \
                  docker-common \
                  docker-latest \
                  docker-latest-logrotate \
                  docker-logrotate \
                  docker-engine

# 4、
yum install -y yum-utils

# 5、
 yum-config-manager \
    --add-repo \
    http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
    
# 6、
yum makecache fast

# 7、
yum install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin # 加个 -y 代表全部询问默认选择yes

# 8、
systemctl start docker

# 9、
docker version

# 10、下面的命令可以分开4条命令依次执行,也可以一起全部执行
sudo mkdir -p /etc/docker

sudo tee /etc/docker/daemon.json <<-'EOF'
{
  "registry-mirrors": ["https://o7f5db09.mirror.aliyuncs.com"]
}
EOF

sudo systemctl daemon-reload

sudo systemctl restart docker

# 11、
docker ps

Swarm集群搭建

  • 工作模式

    在这里插入图片描述

    managers:管理节点(操作都在管理节点上)

    workers:工作节点

  • 搭建集群

在 按量付费-1 服务器上执行以下操作

[root@iZwz941m2ndomce3fyumz6Z ~]# docker network ls # 查看docker网络
NETWORK ID     NAME      DRIVER    SCOPE
728766ac208d   bridge    bridge    local
2590cbc80b83   host      host      local
7152e025ab76   none      null      local
[root@iZwz941m2ndomce3fyumz6Z ~]# docker swarm --help # 查看帮助命令

Usage:  docker swarm COMMAND

Manage Swarm

Commands:
  ca          Display and rotate the root CA
  init        Initialize a swarm
  join        Join a swarm as a node and/or manager
  join-token  Manage join tokens
  leave       Leave the swarm
  unlock      Unlock swarm
  unlock-key  Manage the unlock key
  update      Update the swarm

Run 'docker swarm COMMAND --help' for more information on a command.
[root@iZwz941m2ndomce3fyumz6Z ~]# ip addr # 查看服务器网卡
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 00:16:3e:08:94:78 brd ff:ff:ff:ff:ff:ff
    inet 172.22.201.60/20 brd 172.22.207.255 scope global dynamic eth0
       valid_lft 315355590sec preferred_lft 315355590sec
3: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default 
    link/ether 02:42:ba:78:f9:4e brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
       valid_lft forever preferred_lft forever
[root@iZwz941m2ndomce3fyumz6Z ~]# docker swarm init --advertise-addr 172.22.201.60 # 初始化节点
Swarm initialized: current node (rfn3z37jsiil0p6brn52d3q4c) is now a manager.

To add a worker to this swarm, run the following command:

    docker swarm join --token SWMTKN-1-4j14ia3pjm0na5cftnlejzs1adxjdp24kk79qrkxiclj0r1fs8-3e1730k8goe8gqbl7wlvh91wy 172.22.201.60:2377

To add a manager to this swarm, run 'docker swarm join-token manager' and follow the instructions.

[root@iZwz941m2ndomce3fyumz6Z ~]# 

在 按量付费-2 服务器上执行以下操作

[root@iZwz941m2ndomce3fyumz9Z ~]# docker swarm join --token SWMTKN-1-4j14ia3pjm0na5cftnlejzs1adxjdp24kk79qrkxiclj0r1fs8-3e1730k8goe8gqbl7wlvh91wy 172.22.201.60:2377
This node joined a swarm as a worker.
[root@iZwz941m2ndomce3fyumz9Z ~]# 

在 按量付费-1 服务器上执行以下操作

[root@iZwz941m2ndomce3fyumz6Z ~]# docker node ls
ID                            HOSTNAME                  STATUS    AVAILABILITY   MANAGER STATUS   ENGINE VERSION
rfn3z37jsiil0p6brn52d3q4c *   iZwz941m2ndomce3fyumz6Z   Ready     Active         Leader           20.10.17
k4vzizjoh507a659voykyjisi     iZwz941m2ndomce3fyumz9Z   Ready     Active                          20.10.17
[root@iZwz941m2ndomce3fyumz6Z ~]# 

在 按量付费-3 服务器上执行以下操作

[root@iZwz941m2ndomce3fyumz7Z ~]# docker swarm join --token SWMTKN-1-4j14ia3pjm0na5cftnlejzs1adxjdp24kk79qrkxiclj0r1fs8-3e1730k8goe8gqbl7wlvh91wy 172.22.201.60:2377
This node joined a swarm as a worker.
[root@iZwz941m2ndomce3fyumz7Z ~]# 

在 按量付费-1 服务器上执行以下操作

[root@iZwz941m2ndomce3fyumz6Z ~]# docker node ls
ID                            HOSTNAME                  STATUS    AVAILABILITY   MANAGER STATUS   ENGINE VERSION
rfn3z37jsiil0p6brn52d3q4c *   iZwz941m2ndomce3fyumz6Z   Ready     Active         Leader           20.10.17
cij9f3oy5h5eck50mte3veg59     iZwz941m2ndomce3fyumz7Z   Ready     Active                          20.10.17
k4vzizjoh507a659voykyjisi     iZwz941m2ndomce3fyumz9Z   Ready     Active                          20.10.17
[root@iZwz941m2ndomce3fyumz6Z ~]# docker swarm join-token manager
To add a manager to this swarm, run the following command:

    docker swarm join --token SWMTKN-1-4j14ia3pjm0na5cftnlejzs1adxjdp24kk79qrkxiclj0r1fs8-3r9x8v2kn4gayfigtgkqhay3u 172.22.201.60:2377

[root@iZwz941m2ndomce3fyumz6Z ~]# 


在 按量付费-4 服务器上执行以下操作

[root@iZwz941m2ndomce3fyumz8Z ~]# docker swarm join --token SWMTKN-1-4j14ia3pjm0na5cftnlejzs1adxjdp24kk79qrkxiclj0r1fs8-3r9x8v2kn4gayfigtgkqhay3u 172.22.201.60:2377
This node joined a swarm as a manager.
[root@iZwz941m2ndomce3fyumz8Z ~]# 

在 按量付费-1 服务器上执行以下操作

[root@iZwz941m2ndomce3fyumz6Z ~]# docker node ls
ID                            HOSTNAME                  STATUS    AVAILABILITY   MANAGER STATUS   ENGINE VERSION
rfn3z37jsiil0p6brn52d3q4c *   iZwz941m2ndomce3fyumz6Z   Ready     Active         Leader           20.10.17
cij9f3oy5h5eck50mte3veg59     iZwz941m2ndomce3fyumz7Z   Ready     Active                          20.10.17
r21copdfevyb915q4i92084ud     iZwz941m2ndomce3fyumz8Z   Ready     Active         Reachable        20.10.17
k4vzizjoh507a659voykyjisi     iZwz941m2ndomce3fyumz9Z   Ready     Active                          20.10.17
[root@iZwz941m2ndomce3fyumz6Z ~]# 

至此集群搭建成功!

以上搭建的是:两个主节点,两个从节点。

以上操作主要为以下两步:

1、生成主节点

2、其它节点(管理节点,工作节点)加入到主节点

了解Raft一致性协议

Raft一致性协议:保证大多数节点存活才可以用。(集群的情况下,至少要三个主节点存活)

执行以下步骤:

  • **将 按量付费-1 服务器的docker服务停止,**执行命令systemctl stop docker即可。我们会发现 按量付费-4 服务器也不能用了。把 按量付费-1 服务器的docker服务重新开启后,查看节点信息,会发现 按量付费-1 服务器已经不是Leader了,而是变成了Reachable。 按量付费-4 服务器变成Leader
  • **将 按量付费-3 服务器离开集群,**执行命令docker swarm leave即可。查看节点信息,会发现 按量付费-3 服务器的状态变成Down
  • **将 按量付费-3 服务器以管理节点的身份加入集群。**先在管理节点的服务器上执行命令docker swarm join-token manager,得到新的命令,将得到的命令在 按量付费-3 服务器上执行即可!

查看节点信息,目前我们就将三台机器设置为了管理节点。

[root@iZwz941m2ndomce3fyumz6Z ~]# docker node ls
ID                            HOSTNAME                  STATUS    AVAILABILITY   MANAGER STATUS   ENGINE VERSION
rfn3z37jsiil0p6brn52d3q4c *   iZwz941m2ndomce3fyumz6Z   Ready     Active         Reachable        20.10.17
cij9f3oy5h5eck50mte3veg59     iZwz941m2ndomce3fyumz7Z   Down      Active                          20.10.17
k8mvy8umxvs6159r4wpy4lt49     iZwz941m2ndomce3fyumz7Z   Ready     Active         Reachable        20.10.17
r21copdfevyb915q4i92084ud     iZwz941m2ndomce3fyumz8Z   Ready     Active         Leader           20.10.17
k4vzizjoh507a659voykyjisi     iZwz941m2ndomce3fyumz9Z   Ready     Active                          20.10.17
[root@iZwz941m2ndomce3fyumz6Z ~]# 

现在将 按量付费-1 服务器的docker服务停止,发现 按量付费-3 服务器和 按量付费-4 服务器依然能够使用。再把 按量付费-3 服务器的docker服务停止,那么按量付费-4 服务器也不能使用了,因为只剩下一个主节点,无法保证高可用。

再来理解一下这幅图:

在这里插入图片描述

要保证集群的高可用,至少要保证3个主节点存活

Swarm集群弹性创建Service(服务)

在 按量付费-1 服务器上执行以下操作

[root@iZwz941m2ndomce3fyumz6Z ~]# docker service create -p 8888:80 --name my-nginx nginx
y3mz4jmpg3lbe8mzvhdqx1gzn
overall progress: 1 out of 1 tasks 
1/1: running   [==================================================>] 
verify: Service converged 
[root@iZwz941m2ndomce3fyumz6Z ~]# docker service ps my-nginx
ID             NAME         IMAGE          NODE                      DESIRED STATE   CURRENT STATE           ERROR     PORTS
0kb0maff44t1   my-nginx.1   nginx:latest   iZwz941m2ndomce3fyumz9Z   Running         Running 3 minutes ago             
[root@iZwz941m2ndomce3fyumz6Z ~]# docker service ls
ID             NAME       MODE         REPLICAS   IMAGE          PORTS
y3mz4jmpg3lb   my-nginx   replicated   1/1        nginx:latest   *:8888->80/tcp
[root@iZwz941m2ndomce3fyumz6Z ~]# 

# docker run 容器启动,不具有扩缩容器

# docker service 服务启动,具有扩缩容器,还可以滚动更新!

在 按量付费-2 服务器上执行以下操作

# 发现 my-nginx.1.0kb0maff44t15joggbk5pq6em 容器启动在 按量付费-2 服务器上!
[root@iZwz941m2ndomce3fyumz9Z ~]# docker ps 
CONTAINER ID   IMAGE          COMMAND                  CREATED         STATUS         PORTS     NAMES
8c3729d66fb4   nginx:latest   "/docker-entrypoint.…"   5 minutes ago   Up 5 minutes   80/tcp    my-nginx.1.0kb0maff44t15joggbk5pq6em
[root@iZwz941m2ndomce3fyumz9Z ~]# 

在 按量付费-1 服务器上执行以下操作

[root@iZwz941m2ndomce3fyumz6Z ~]# docker service update --replicas 3 my-nginx # 更新服务的副本数,相当于动态扩缩容
my-nginx
overall progress: 3 out of 3 tasks 
1/3: running   [==================================================>] 
2/3: running   [==================================================>] 
3/3: running   [==================================================>] 
verify: Service converged 
[root@iZwz941m2ndomce3fyumz6Z ~]# 

在 按量付费-1 服务器上执行以下操作

[root@iZwz941m2ndomce3fyumz6Z ~]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@iZwz941m2ndomce3fyumz6Z ~]# 

在 按量付费-2 服务器上执行以下操作

[root@iZwz941m2ndomce3fyumz9Z ~]# docker ps
CONTAINER ID   IMAGE          COMMAND                  CREATED          STATUS          PORTS     NAMES
8c3729d66fb4   nginx:latest   "/docker-entrypoint.…"   10 minutes ago   Up 10 minutes   80/tcp    my-nginx.1.0kb0maff44t15joggbk5pq6em
[root@iZwz941m2ndomce3fyumz9Z ~]# 

在 按量付费-3 服务器上执行以下操作

[root@iZwz941m2ndomce3fyumz7Z ~]# docker ps
CONTAINER ID   IMAGE          COMMAND                  CREATED          STATUS          PORTS     NAMES
ee95e7f4dbe2   nginx:latest   "/docker-entrypoint.…"   43 seconds ago   Up 42 seconds   80/tcp    my-nginx.3.ky6fmtymolgb3lqssmf9htkw4
[root@iZwz941m2ndomce3fyumz7Z ~]# 

在 按量付费-4 服务器上执行以下操作

[root@iZwz941m2ndomce3fyumz8Z ~]# docker ps
CONTAINER ID   IMAGE          COMMAND                  CREATED          STATUS          PORTS     NAMES
33bbb89f490d   nginx:latest   "/docker-entrypoint.…"   47 seconds ago   Up 45 seconds   80/tcp    my-nginx.2.p09fomfmb7d84le3xve0e77hk
[root@iZwz941m2ndomce3fyumz8Z ~]# 

虽然在 按量付费-1 服务器上没有看到容器进程,但是我们依然可以使用 按量付费-1 服务器的IP加端口访问Nginx!!!因为集群是一个整体(实现原理跟ingress网络有关,ingress网络是特殊的Overlay网络)

在这里插入图片描述

服务,集群中的任意节点都可以访问。服务可以有多个副本来实现动态扩缩容,实现高可用!

在 按量付费-1 服务器上执行以下操作

[root@iZwz941m2ndomce3fyumz6Z ~]# docker service ls
ID             NAME       MODE         REPLICAS   IMAGE          PORTS
y3mz4jmpg3lb   my-nginx   replicated   1/1        nginx:latest   *:8888->80/tcp
[root@iZwz941m2ndomce3fyumz6Z ~]# docker service rm my-nginx # 移除服务
my-nginx
[root@iZwz941m2ndomce3fyumz6Z ~]# docker service ls
ID        NAME      MODE      REPLICAS   IMAGE     PORTS
[root@iZwz941m2ndomce3fyumz6Z ~]# 

docker swarm其实并不难,只要会搭建集群、会启动服务、动态管理容器就可以了

Swarm是简单版的K8S,以后我们学习K8S会更加复杂,学习Swarm能够为学习K8S打基础

Swarm的重要概念

  • Service:任务,可以在管理节点和工作节点来运行。用户访问的其实就是它。

  • Node:就是一个docker节点(管理节点、工作节点),多个节点就组成了一个网路集群。这个集群需要一个管理者,这个管理者就是Swarm

  • Swarm:说白了就是集群的管理和编排,docker可以初始化一个swarm集群,其它节点(管理节点、工作节点)可以加入集群

  • Task:相当于一个Service所创建的多个副本,这些副本就是一个个的Task

    在这里插入图片描述

Docker Stack

docker-compose 是单机部署项目!

docker stack 是集群部署!

[root@iZwz941m2ndomce3fyumz6Z ~]# docker stack --help

Usage:  docker stack [OPTIONS] COMMAND

Manage Docker stacks

Options:
      --orchestrator string   Orchestrator to use (swarm|kubernetes|all)

Commands:
  deploy      Deploy a new stack or update an existing stack
  ls          List stacks
  ps          List the tasks in the stack
  rm          Remove one or more stacks
  services    List the services in the stack

Run 'docker stack COMMAND --help' for more information on a command.
[root@iZwz941m2ndomce3fyumz6Z ~]# 

学习方式:

  • 百度搜索 docker stack 案例
  • 官方文档

Docker Secret

Docker Secret 主要用于安全。配置密码,证书!

[root@iZwz941m2ndomce3fyumz6Z ~]# docker secret --help

Usage:  docker secret COMMAND

Manage Docker secrets

Commands:
  create      Create a secret from a file or STDIN as content
  inspect     Display detailed information on one or more secrets
  ls          List secrets
  rm          Remove one or more secrets

Run 'docker secret COMMAND --help' for more information on a command.
[root@iZwz941m2ndomce3fyumz6Z ~]# 

学习方式:

  • 百度
  • 官方文档

Docker Config

配置相关

[root@iZwz941m2ndomce3fyumz6Z ~]# docker config --help

Usage:  docker config COMMAND

Manage Docker configs

Commands:
  create      Create a config from a file or STDIN
  inspect     Display detailed information on one or more configs
  ls          List configs
  rm          Remove one or more configs

Run 'docker config COMMAND --help' for more information on a command.
[root@iZwz941m2ndomce3fyumz6Z ~]# 

学习方式:

  • 百度
  • 官方文档

Docker完结及展望

云原生时代

云应用

这是大趋势!需要学习精通K8S!

Go语言!必须学习掌握!

  • Docker是Go开发的
  • K8S也是Go的项目
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐