Docker入门

Docker基本组成

Docker基本组成

镜像 -》run -》容器

容器 = 镜像 + 可读层

安装Docker

环境查看

# 系统内核是3.10以上的
[root@mengxt ~]# uname -r
3.10.0-1062.18.1.el7.x86_64
# 系统版本
[root@mengxt ~]# 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"

安装

帮助文档

#1、卸载旧的docker版本
yum remove docker \
                docker-client \
                docker-client-latest \
                docker-common \
                docker-latest \
                docker-latest-logrotate \
                docker-logrotate \
                docker-engine
#2、需要的安装包
yum install -y yum-utils
#3、设置镜像仓库
yum-config-manager \
   --add-repo \
  https://download.docker.com/linux/centos/docker-ce.repo #默认是从国外的,速度非常慢
   
yum-config-manager \
   --add-repo \
  http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo #使用阿里云的镜像仓库
#4、更新yum软件包索引
yum makecache fast
#5、安装docker相关 docker -ce 社区版 docker -ee 企业版
yum install docker-ce docker-ce-cli containerd.io
#6、启动docker
systemctl start docker
#7、使用docker version查看是否安装成功
Client: Docker Engine - Community
Version:           20.10.5
API version:       1.41
Go version:       go1.13.15
Git commit:       55c4c88
Built:             Tue Mar  2 20:33:55 2021
OS/Arch:           linux/amd64
Context:           default
Experimental:      true

Server: Docker Engine - Community
Engine:
Version:          20.10.5
API version:      1.41 (minimum version 1.12)
Go version:       go1.13.15
Git commit:       363e9a8
Built:           Tue Mar  2 20:32:17 2021
OS/Arch:         linux/amd64
Experimental:     false
containerd:
Version:          1.4.4
GitCommit:       05f951a3781f4f2c1911b05e61c160e9c30eaa8e
runc:
Version:          1.0.0-rc93
GitCommit:       12644e614e25b05da6fd08a38ffa0cfe1903fdec
docker-init:
Version:          0.19.0
GitCommit:       de40ad0
#8、测试
[root@mengxt ~]#docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
b8dfde127a29: Pull complete
Digest: sha256:308866a43596e83578c7dfa15e27a73011bdd402185a84c5cd7f32a88b501a24
Status: Downloaded newer image for hello-world:latest

Hello from Docker!
This message shows that your installation appears to be working correctly.

To generate this message, Docker took the following steps:
1. The Docker client contacted the Docker daemon.
2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
  (amd64)
3. The Docker daemon created a new container from that image which runs the
  executable that produces the output you are currently reading.
4. The Docker daemon streamed that output to the Docker client, which sent it
  to your terminal.

To try something more ambitious, you can run an Ubuntu container with:
$ docker run -it ubuntu bash

Share images, automate workflows, and more with a free Docker ID:
https://hub.docker.com/

For more examples and ideas, visit:
https://docs.docker.com/get-started/
#9、查看镜像
[root@mengxt ~]# docker images
REPOSITORY   TAG       IMAGE ID       CREATED       SIZE
hello-world   latest   d1165f221234   2 weeks ago   13.3kB

卸载docker

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

阿里云镜像加速

到阿里云官网找的容器镜像服务-》镜像加速器-》查看centos的操作文档。内容如下:

sudo mkdir -p /etc/docker

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

sudo systemctl daemon-reload

sudo systemctl restart docker

HelloWorld流程

docker run *** -> docker在本机寻找镜像 -> 找到则运行,否则会在镜像仓库中(docker hub)下载镜像 -> 仓库是否可以找到,找不到返回错误,找到则下载到本地 -> 运行

底层原理

Docker是怎样工作的

Docker是怎样工作的

Docker为什么比VM快

  1. Docker有着比虚拟机更少的抽象层
  2. Docker利用的是宿主机的内核,vm则是需要是Guest OS
Docker为什么比VM快

Docker的常用命令

帮助命令

docker version # 显示docker的版本信息
docker info # 显示docker的系统信息,包括镜像和容器的数量
docker <命令> --help # 显示命令的帮助信息

帮助文档

https://docs.docker.com/reference/

镜像命令

docker images 查看所有本机上的镜像

[root@mengxt ~]# docker images
REPOSITORY   TAG       IMAGE ID       CREATED       SIZE
hello-world   latest   d1165f221234   2 weeks ago   13.3kB

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

# 可选项
Options:
 -a, --all             Show all images (default hides intermediate images) # 列出所有镜像(含中间映像层,默认情况下,过滤掉中间映像层)
 -q, --quiet           Only show image IDs #只显示镜像的ID
可以使用-aq显示所有镜像的ID

docker search 搜索镜像

[root@mengxt ~]# docker search mysql
NAME                             DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
mysql                             MySQL is a widely used, open-source relation…   10634     [OK]      
mariadb                           MariaDB Server is a high performing open sou…   3990     [OK]      
mysql/mysql-server               Optimized MySQL Server Docker images. Create…   779       [OK]

# 可选项
--filter=stars=3000 # 搜索出来的镜像就是stars大于3000的
[root@mengxt ~]# docker search mysql --filter=stars=3000
NAME     DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
mysql     MySQL is a widely used, open-source relation…   10634     [OK]      
mariadb   MariaDB Server is a high performing open sou…   3990     [OK]      
[root@mengxt ~]# docker search mysql --filter=stars=5000
NAME     DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
mysql     MySQL is a widely used, open-source relation…   10634     [OK]      

docker pull 下载镜像

# 下载镜像 docker pull 镜像名[:TAG](版本)
[root@mengxt ~]# docker pull mysql
Using default tag: latest # 如果不指定tag,默认latest
latest: Pulling from library/mysql
a076a628af6f: Pull complete # 分层下载 docker image 的核心 联合文件系统(不同版本间可以共用,已经有的分层不需要再下载)
f6c208f3f991: Pull complete
88a9455a9165: Pull complete
406c9b8427c6: Pull complete
7c88599c0b25: Pull complete
25b5c6debdaf: Pull complete
43a5816f1617: Pull complete
1a8c919e89bf: Pull complete
9f3cf4bd1a07: Pull complete
80539cea118d: Pull complete
201b3cad54ce: Pull complete
944ba37e1c06: Pull complete
Digest: sha256:feada149cb8ff54eade1336da7c1d080c4a1c7ed82b5e320efb5beebed85ae8c # 签名
Status: Downloaded newer image for mysql:latest
docker.io/library/mysql:latest # 真实地址

# 二者等价
docker pull mysql
docker pull docker.io/library/mysql:latest

# 指定版本下载
[root@mengxt ~]# docker pull mysql:5.7
5.7: Pulling from library/mysql
a076a628af6f: Already exists
f6c208f3f991: Already exists
88a9455a9165: Already exists
406c9b8427c6: Already exists
7c88599c0b25: Already exists
25b5c6debdaf: Already exists
43a5816f1617: Already exists
1831ac1245f4: Pull complete
37677b8c1f79: Pull complete
27e4ac3b0f6e: Pull complete
7227baa8c445: Pull complete
Digest: sha256:b3d1eff023f698cd433695c9506171f0d08a8f92a0c8063c1a4d9db9a55808df
Status: Downloaded newer image for mysql:5.7
docker.io/library/mysql:5.7

[root@mengxt ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
hello-world latest d1165f221234 2 weeks ago 13.3kB
mysql 5.7 a70d36bc331a 2 months ago 449MB
mysql latest c8562eaf9d81 2 months ago 546MB

docker rmi 删除镜像

解释:

docker rmi 命令会移除构成镜像的一个只读层。你只能够使用docker rmi来移除最顶层(top level layer)(也可以说是镜像),你也可以使用-f参数来强制删除中间的只读层

[root@mengxt ~]# docker rmi -f 镜像id # 删除指定的镜像;docker rmi -f 镜像id 镜像id 镜像id 删除多个镜像
Untagged: mysql:latest
Untagged: mysql@sha256:feada149cb8ff54eade1336da7c1d080c4a1c7ed82b5e320efb5beebed85ae8c
Deleted: sha256:c8562eaf9d81c779cbfc318d6e01b8e6f86907f1d41233268a2ed83b2f34e748
Deleted: sha256:1b649b85960473808c6b812fc30c3f6a3ff1c0ffdcba5c9435daf01cf7d5373a
Deleted: sha256:19cc889447050c16c797fd209fa114ee219de23facb37c00d4137a4ed4aad922
Deleted: sha256:3c793c06a026d276cf56a6a6a75527026ed9eafa7a7d21a438f7d5ed2314148e
Deleted: sha256:1e1cd89a2bc183a7fea3dab0b543e9924278321ad0921c22cc088adbf3c2e77b
Deleted: sha256:83b2015dfd000588c7c947b2d89b3be7a8e5a3abc6ab562668c358033aa779ec
[root@mengxt ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
hello-world latest d1165f221234 2 weeks ago 13.3kB
mysql 5.7 a70d36bc331a 2 months ago 449MB
[root@mengxt ~]# docker rmi -f $(docker images -aq) # 删除全部的镜像
Untagged: hello-world:latest
Untagged: hello-world@sha256:308866a43596e83578c7dfa15e27a73011bdd402185a84c5cd7f32a88b501a24
Deleted: sha256:d1165f2212346b2bab48cb01c1e39ee8ad1be46b87873d9ca7a4e434980a7726
Untagged: mysql:5.7
Untagged: mysql@sha256:b3d1eff023f698cd433695c9506171f0d08a8f92a0c8063c1a4d9db9a55808df
Deleted: sha256:a70d36bc331a13d297f882d3d63137d24b804f29fa67158c40ad91d5050c39c5
Deleted: sha256:50c77bf7bcddd1f1d97789d80ac2404eec22c860c104e858620d2a2e321f0ef7
Deleted: sha256:14244329b83dfc8982398ee4104a548385652d2bffb957798ff86a419013efd6
Deleted: sha256:6d990477f90af28473eb601a9bca22253f6381e053c5a8edda0a4f027e124a3c
Deleted: sha256:ee0449796df204071589162fc16f8d65586312a40c68d1ba156c93c56f5e5ce8
Deleted: sha256:d08533f1e2acc40ad561a46fc6a76b54c739e6b24f077c183c5709e0a6885312
Deleted: sha256:4f9d91a4728e833d1062fb65a792f06e22e425f63824f260c8b5a64b776ddc38
Deleted: sha256:20bf4c759d1b0d0e6286d2145453af4e0e1b7ba3d4efa3b8bce46817ad4109de
Deleted: sha256:a9371bbdf16ac95cc72555c6ad42f79b9f03a82d964fe89d52bdc5f335a5f42a
Deleted: sha256:5b02130e449d94f51e8ff6e5f7d24802246198749ed9eb064631e63833cd8f1d
Deleted: sha256:ab74465b38bc1acb16c23091df32c5b7033ed55783386cb57acae8efff9f4b37
Deleted: sha256:cb42413394c4059335228c137fe884ff3ab8946a014014309676c25e3ac86864
[root@mengxt ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE

容器命令

说明:有了镜像才能创建容器,下载一个centos镜像来测试学习

docker pull centos

新建容器并启动

docker run [可选参数] image

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

# 测试,启动并进入容器
[root@mengxt ~]# docker run -it centos /bin/bash
[root@62bfefe5e9b6 /]#
[root@62bfefe5e9b6 /]# ls # 查看容器内的centos,基础版本,很多命令都是不完善的
bin dev etc home lib lib64 lost+found media mnt opt proc root run sbin srv sys tmp usr var

# 从容器中退回主机
[root@62bfefe5e9b6 /]# exit
exit
[root@mengxt ~]# ls
baota.txt install.sh
[root@mengxt ~]# cd /
[root@mengxt /]# ls
bin boot data dev etc home lib lib64 lost+found media mnt opt proc root run sbin srv sys tmp usr var www

# 如果想要以后台的方式运行容器,并保持容器运行状态,不能只使用-d参数,建议使用后台模式和tty选项
[root@mengxt /]# docker run -it -d centos
5e2eb0bb98ac81591c8f85a42de858dbfe9e97a7644b67d59a9f3caf4b1c305f
[root@mengxt /]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
5e2eb0bb98ac centos "/bin/bash" 7 seconds ago Up 6 seconds busy_hoover

列出所有运行的容器

# docker ps命令
# 列出当前正在运行的容器
-a # 列出当前正在运行的容器+非运行态容器
-n=? # 显示最近创建的容器,n表示个数
-q # 只显示容器的ID
[root@mengxt /]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
[root@mengxt /]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
62bfefe5e9b6 centos "/bin/bash" 4 minutes ago Exited (0) About a minute ago amazing_stonebraker
2922afcef884 d1165f221234 "/hello" 12 hours ago Exited (0) 12 hours ago tender_jemison
[root@mengxt /]# docker ps -n=1
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
62bfefe5e9b6 centos "/bin/bash" 7 minutes ago Exited (0) 4 minutes ago amazing_stonebraker
[root@mengxt /]# docker ps -aq
62bfefe5e9b6
2922afcef884

退出容器

exit # 容器直接停止并退出
Ctrl + P + Q # 容器不停止并退出

删除容器

docker rm 容器ID # 删除指定的容器,不能删除正在运行的容器,强制删除需要使用-f
docker rm -f $(docker ps -aq) # 删除所有的容器
docker ps -aq | xargs docker rm # 删除所有的容器

[root@mengxt /]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
0593722b86bc centos "/bin/bash" 21 seconds ago Up 20 seconds laughing_johnson
c931a0c1495c centos "/bin/bash" 3 minutes ago Up 3 minutes nifty_dhawan
a151bed04cb2 centos "/bin/bash" 3 minutes ago Up 3 minutes trusting_lalande
a09ad5bdfef1 centos "/bin/bash" 4 minutes ago Up 4 minutes confident_grothendieck
62bfefe5e9b6 centos "/bin/bash" 15 minutes ago Exited (0) 13 minutes ago amazing_stonebraker
2922afcef884 d1165f221234 "/hello" 12 hours ago Exited (0) 12 hours ago tender_jemison
[root@mengxt /]# docker rm 62bfefe5e9b6
62bfefe5e9b6
[root@mengxt /]# docker rm a09ad5bdfef1
Error response from daemon: You cannot remove a running container a09ad5bdfef14dab90beb925a80024deea760c7ab2cb17cff93caf429817130b. Stop the container before attempting removal or force remove
[root@mengxt /]# docker ps -aq
0593722b86bc
c931a0c1495c
a151bed04cb2
a09ad5bdfef1
2922afcef884
[root@mengxt /]# docker rm -f $(docker ps -aq)
0593722b86bc
c931a0c1495c
a151bed04cb2
a09ad5bdfef1
2922afcef884
[root@mengxt /]# docker ps -aq
[root@mengxt /]#

启动和停止容器的操作

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

[root@mengxt /]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
05ba9ecae113 centos "/bin/bash" 9 seconds ago Exited (0) 8 seconds ago clever_wilson
5e2eb0bb98ac centos "/bin/bash" 7 minutes ago Up 7 minutes busy_hoover
[root@mengxt /]# docker start 05ba9ecae113
05ba9ecae113
[root@mengxt /]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
05ba9ecae113 centos "/bin/bash" 31 seconds ago Up 4 seconds clever_wilson
5e2eb0bb98ac centos "/bin/bash" 7 minutes ago Up 7 minutes busy_hoover
[root@mengxt /]# docker stop 05ba9ecae113
05ba9ecae113
[root@mengxt /]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
05ba9ecae113 centos "/bin/bash" About a minute ago Exited (0) 8 seconds ago clever_wilson
5e2eb0bb98ac centos "/bin/bash" 8 minutes ago Up 8 minutes busy_hoover

# 注意事项
# 使用 dokcer run image 命令启动的容器无法使用 docker start 容器ID 命令来启动容器(原因?)
[root@mengxt /]# docker run centos
[root@mengxt /]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
ca5621508f11 centos "/bin/bash" 5 seconds ago Exited (0) 4 seconds ago inspiring_brown
[root@mengxt /]# docker start ca5621508f11
ca5621508f11
[root@mengxt /]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
ca5621508f11 centos "/bin/bash" 25 seconds ago Exited (0) 6 seconds ago inspiring_brown

常用其他命令

后台启动容器

# 通过docker run -d 镜像名
[root@mengxt /]# docker run -d centos
301a55209bf8f028cc4592b65cb9cf2dc28bfdfaa81543ce1806b2ddcbce7643
[root@mengxt /]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
301a55209bf8 centos "/bin/bash" 13 seconds ago Exited (0) 12 seconds ago strange_goldstine

# 问题docker ps,发现容器停止了
# docker容器使用后台运行,就必须要有一个前台进程,docker发现没有应用,就会自动停止
# 比如nginx,容器启动后,发现自己没有提供服务,就会立刻停止,就是没有程序了

查看日志

docker logs -f -t --tail 10 容器ID

# 自己编写一段shell脚本
[root@mengxt /]# docker run -d centos /bin/sh -c "while true;do echo hello,docker;sleep 1;done"
c0e6f215e60c1d7c7176976f4edb170719125c3d301c862c6e5a6e4766a35fd7
[root@mengxt /]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
c0e6f215e60c centos "/bin/sh -c 'while t…" 2 seconds ago Up 2 seconds nervous_wescoff

# 显示日志
-tf # 显示全部日志
--tail number # 要显示的日志条数
[root@mengxt /]# docker logs -f -t --tail 10 c0e6f215e60c
2021-03-22T12:47:48.831844079Z hello,docker
2021-03-22T12:47:49.833551514Z hello,docker
2021-03-22T12:47:50.835297285Z hello,docker
2021-03-22T12:47:51.837028339Z hello,docker

查看容器中进程信息

# 命令 docker top 容器ID
[root@mengxt /]# docker top c0e6f215e60c
UID PID PPID C STIME TTY TIME CMD
root 7648 7628 0 20:46 ? 00:00:00 /bin/sh -c while true;do echo hello,docker;sleep 1;done
root 8514 7648 0 20:51 ? 00:00:00 /usr/bin/coreutils --coreutils-prog-shebang=sleep /usr/bin/sleep 1

查看镜像的元数据

# 命令 docker inspect 容器ID

# 测试
[root@mengxt /]# docker inspect c0e6f215e60c
[
{
"Id": "c0e6f215e60c1d7c7176976f4edb170719125c3d301c862c6e5a6e4766a35fd7",
"Created": "2021-03-22T12:46:43.400451227Z",
"Path": "/bin/sh",
"Args": [
"-c",
"while true;do echo hello,docker;sleep 1;done"
],
"State": {
"Status": "running",
"Running": true,
"Paused": false,
"Restarting": false,
"OOMKilled": false,
"Dead": false,
"Pid": 7648,
"ExitCode": 0,
"Error": "",
"StartedAt": "2021-03-22T12:46:43.709486109Z",
"FinishedAt": "0001-01-01T00:00:00Z"
},
"Image": "sha256:300e315adb2f96afe5f0b2780b87f28ae95231fe3bdd1e16b9ba606307728f55",
"ResolvConfPath": "/var/lib/docker/containers/c0e6f215e60c1d7c7176976f4edb170719125c3d301c862c6e5a6e4766a35fd7/resolv.conf",
"HostnamePath": "/var/lib/docker/containers/c0e6f215e60c1d7c7176976f4edb170719125c3d301c862c6e5a6e4766a35fd7/hostname",
"HostsPath": "/var/lib/docker/containers/c0e6f215e60c1d7c7176976f4edb170719125c3d301c862c6e5a6e4766a35fd7/hosts",
"LogPath": "/var/lib/docker/containers/c0e6f215e60c1d7c7176976f4edb170719125c3d301c862c6e5a6e4766a35fd7/c0e6f215e60c1d7c7176976f4edb170719125c3d301c862c6e5a6e4766a35fd7-json.log",
"Name": "/nervous_wescoff",
"RestartCount": 0,
"Driver": "overlay2",
"Platform": "linux",
"MountLabel": "",
"ProcessLabel": "",
"AppArmorProfile": "",
"ExecIDs": null,
"HostConfig": {
"Binds": null,
"ContainerIDFile": "",
"LogConfig": {
"Type": "json-file",
"Config": {}
},
"NetworkMode": "default",
"PortBindings": {},
"RestartPolicy": {
"Name": "no",
"MaximumRetryCount": 0
},
"AutoRemove": false,
"VolumeDriver": "",
"VolumesFrom": null,
"CapAdd": null,
"CapDrop": null,
"CgroupnsMode": "host",
"Dns": [],
"DnsOptions": [],
"DnsSearch": [],
"ExtraHosts": null,
"GroupAdd": null,
"IpcMode": "private",
"Cgroup": "",
"Links": null,
"OomScoreAdj": 0,
"PidMode": "",
"Privileged": false,
"PublishAllPorts": false,
"ReadonlyRootfs": false,
"SecurityOpt": null,
"UTSMode": "",
"UsernsMode": "",
"ShmSize": 67108864,
"Runtime": "runc",
"ConsoleSize": [
0,
0
],
"Isolation": "",
"CpuShares": 0,
"Memory": 0,
"NanoCpus": 0,
"CgroupParent": "",
"BlkioWeight": 0,
"BlkioWeightDevice": [],
"BlkioDeviceReadBps": null,
"BlkioDeviceWriteBps": null,
"BlkioDeviceReadIOps": null,
"BlkioDeviceWriteIOps": null,
"CpuPeriod": 0,
"CpuQuota": 0,
"CpuRealtimePeriod": 0,
"CpuRealtimeRuntime": 0,
"CpusetCpus": "",
"CpusetMems": "",
"Devices": [],
"DeviceCgroupRules": null,
"DeviceRequests": null,
"KernelMemory": 0,
"KernelMemoryTCP": 0,
"MemoryReservation": 0,
"MemorySwap": 0,
"MemorySwappiness": null,
"OomKillDisable": false,
"PidsLimit": null,
"Ulimits": null,
"CpuCount": 0,
"CpuPercent": 0,
"IOMaximumIOps": 0,
"IOMaximumBandwidth": 0,
"MaskedPaths": [
"/proc/asound",
"/proc/acpi",
"/proc/kcore",
"/proc/keys",
"/proc/latency_stats",
"/proc/timer_list",
"/proc/timer_stats",
"/proc/sched_debug",
"/proc/scsi",
"/sys/firmware"
],
"ReadonlyPaths": [
"/proc/bus",
"/proc/fs",
"/proc/irq",
"/proc/sys",
"/proc/sysrq-trigger"
]
},
"GraphDriver": {
"Data": {
"LowerDir": "/var/lib/docker/overlay2/e7c7c45def63404bb4fa98874fe66d0d84840f807e81f67a12c484fd1e247b8b-init/diff:/var/lib/docker/overlay2/6c90b9a154ec746f65a4671b98d090c24dce0b1e737c264e8ce564ac82ad5dfe/diff",
"MergedDir": "/var/lib/docker/overlay2/e7c7c45def63404bb4fa98874fe66d0d84840f807e81f67a12c484fd1e247b8b/merged",
"UpperDir": "/var/lib/docker/overlay2/e7c7c45def63404bb4fa98874fe66d0d84840f807e81f67a12c484fd1e247b8b/diff",
"WorkDir": "/var/lib/docker/overlay2/e7c7c45def63404bb4fa98874fe66d0d84840f807e81f67a12c484fd1e247b8b/work"
},
"Name": "overlay2"
},
"Mounts": [],
"Config": {
"Hostname": "c0e6f215e60c",
"Domainname": "",
"User": "",
"AttachStdin": false,
"AttachStdout": false,
"AttachStderr": false,
"Tty": false,
"OpenStdin": false,
"StdinOnce": false,
"Env": [
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
],
"Cmd": [
"/bin/sh",
"-c",
"while true;do echo hello,docker;sleep 1;done"
],
"Image": "centos",
"Volumes": null,
"WorkingDir": "",
"Entrypoint": null,
"OnBuild": null,
"Labels": {
"org.label-schema.build-date": "20201204",
"org.label-schema.license": "GPLv2",
"org.label-schema.name": "CentOS Base Image",
"org.label-schema.schema-version": "1.0",
"org.label-schema.vendor": "CentOS"
}
},
"NetworkSettings": {
"Bridge": "",
"SandboxID": "2892c48627f23564b0a076a84c40c634b74ab94c091beb914f4f090e4ce9576e",
"HairpinMode": false,
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"Ports": {},
"SandboxKey": "/var/run/docker/netns/2892c48627f2",
"SecondaryIPAddresses": null,
"SecondaryIPv6Addresses": null,
"EndpointID": "83f2c40aad0c5fc6eef9207edf408e3da16b3204add62a9375ea267312aed987",
"Gateway": "172.17.0.1",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"IPAddress": "172.17.0.2",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"MacAddress": "02:42:ac:11:00:02",
"Networks": {
"bridge": {
"IPAMConfig": null,
"Links": null,
"Aliases": null,
"NetworkID": "06d798af96d7cb94c3f41233c0f8eba76e6b9c21c2c656ebf5013c2fda970796",
"EndpointID": "83f2c40aad0c5fc6eef9207edf408e3da16b3204add62a9375ea267312aed987",
"Gateway": "172.17.0.1",
"IPAddress": "172.17.0.2",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"MacAddress": "02:42:ac:11:00:02",
"DriverOpts": null
}
}
}
}
]
[root@mengxt /]#

进入当前正在运行的容器

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

# 方式一
docker exec -it 容器ID /bin/bash

# 测试
[root@mengxt /]# docker exec -it c0e6f215e60c /bin/bash
[root@c0e6f215e60c /]# ls
bin dev etc home lib lib64 lost+found media mnt opt proc root run sbin srv sys tmp usr var
[root@c0e6f215e60c /]# ps -ef
UID PID PPID C STIME TTY TIME CMD
root 1 0 0 12:46 ? 00:00:00 /bin/sh -c while true;do echo hello,docker;sleep 1;done
root 786 0 0 12:59 pts/0 00:00:00 /bin/bash
root 818 1 0 13:00 ? 00:00:00 /usr/bin/coreutils --coreutils-prog-shebang=sleep /usr/bin/sleep 1
root 819 786 0 13:00 pts/0 00:00:00 ps -ef

# 方式二
docker attach 容器ID

# 测试
[root@mengxt /]# docker attach c0e6f215e60c
hello,docker
hello,docker
hello,docker
hello,docker

# docker exec # 进入容器后开启一个新的终端,可以在里面操作(常用)
# docker attach # 进入容器正在执行的终端,不会启动新的进程

从容器内拷贝文件到主机上

docker cp 容器ID:容器内路径 目的的主机路径

# 进入docker容器内部,在容器内新建一个文件
[root@mengxt home]# docker attach d92bf17ccadb
[root@d92bf17ccadb /]# cd /home/
[root@d92bf17ccadb home]# ls
[root@d92bf17ccadb home]# touch hello.txt
[root@d92bf17ccadb home]# exit
exit
[root@mengxt home]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
[root@mengxt home]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
d92bf17ccadb centos "/bin/bash" About a minute ago Exited (0) 11 seconds ago nervous_carver
# 将文件拷贝到主机上
[root@mengxt home]# docker cp d92bf17ccadb:/home/hello.txt /home
[root@mengxt home]# ls
hello.txt
# 拷贝是一个手动过程,未来我们使用 -v 卷的技术,可以实现自动同步

小结

Docker-Command-Diagram

命令字典

attach      Attach local standard input, output, and error streams to a running container
# 当前shell下连接指定运行镜像
build Build an image from a Dockerfile
# 通过Dockerfile构建镜像
commit Create a new image from a container's changes
# 提交当前镜像为新的镜像
cp Copy files/folders between a container and the local filesystem
# 在容器和本地间拷贝文件或目录
create Create a new container
# 创建一个新的容器,同run,但不启动容器
diff Inspect changes to files or directories on a container's filesystem
# 查看docker容器变化
events Get real time events from the server
# 从docker服务获取容器实时事件
exec Run a command in a running container
# 在已存在的容器上运行命令
export Export a container's filesystem as a tar archive
# 导出容器内的内容流作为一个tar归档文件[对应import]
history Show the history of an image
# 显示一个镜像的形成历史
images List images
# 列出系统当前镜像(最顶层)
import Import the contents from a tarball to create a filesystem image
# 从tar包中的内容创建一个新的文件系统镜像[对应export]
info Display system-wide information
# 显示系统相关信息
inspect Return low-level information on Docker objects
# 查看容器详细信息
kill Kill one or more running containers
# kill指定运行容器
load Load an image from a tar archive or STDIN
# 从一个tar包中加载一个镜像[对应save]
login Log in to a Docker registry
# 注册或者登录一个docker镜像源服务器
logout Log out from a Docker registry
# 从当前docker镜像源服务器退出
logs Fetch the logs of a container
# 输出当前容器日志信息
pause Pause all processes within one or more containers
# 暂停容器
port List port mappings or a specific mapping for the container
# 查看映射端口对应的容器内部源端口
ps List containers
# 列出容器列表
pull Pull an image or a repository from a registry
# 从docker镜像源服务器拉取指定镜像或者库镜像
push Push an image or a repository to a registry
# 推送指定镜像或者库镜像至docker镜像源服务器
rename Rename a container
# 重命名一个容器
restart Restart one or more containers
# 重启运行的容器
rm Remove one or more containers
# 移除容器
rmi Remove one or more images
# 移除镜像[无容器使用该镜像才可删除,否则需删除相关容器才可继续或 -f 强制删除]
run Run a command in a new container
# 创建一个新的容器并运行一个命令
save Save one or more images to a tar archive (streamed to STDOUT by default)
# 保存一个镜像为一个tar包[对应load]
search Search the Docker Hub for images
# 在docker hub上搜索镜像
start Start one or more stopped containers
# 启动容器
stats Display a live stream of container(s) resource usage statistics
# 实时显示容器资源使用情况
stop Stop one or more running containers
# 停止容器
tag Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE
# 使用镜像源创建一个指定镜像的标签
top Display the running processes of a container
# 查看容器内运行的进程信息
unpause Unpause all processes within one or more containers
# 取消暂停容器
update Update configuration of one or more containers
# 更新容器的配置(如cpu、内存)
version Show the Docker version information
# 查看docker版本信息
wait Block until one or more containers stop, then print their exit codes
# 截取容器停止时的退出状态值

作业练习

Nginx

Dokcer安装Nginx

# 1、搜索镜像 docker search nginx, docker hub上搜索,可以看到帮助文档
# 2、下载镜像到本地 docker pull nginx
# 3、运行测试

# -d 后台运行
# --name 指定容器名称
# -p 宿主机端口:容器内部端口 端口暴露(端口映射)
[root@mengxt ~]# docker run -d --name nginx01 -p 3344:80 nginx
2386c6e5282cbbf2852d1118db9cd274ac45be08b9c2930cf4cdbea25afe222b
[root@mengxt ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
2386c6e5282c nginx "/docker-entrypoint.…" 6 seconds ago Up 5 seconds 0.0.0.0:3344->80/tcp nginx01
[root@mengxt ~]# curl localhost:3344
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
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@mengxt ~]#
# 进入容器
[root@mengxt ~]# docker exec -it nginx01 /bin/bash
root@2386c6e5282c:/# whereis nginx
nginx: /usr/sbin/nginx /usr/lib/nginx /etc/nginx /usr/share/nginx
root@2386c6e5282c:/# cd /etc/nginx/
root@2386c6e5282c:/etc/nginx# ls
conf.d fastcgi_params koi-utf koi-win mime.types modules nginx.conf scgi_params uwsgi_params win-utf
root@2386c6e5282c:/etc/nginx#

端口暴露的概念

端口暴露的概念

思考问题:我们每次改动nginx配置文件,都需要进入容器内部?十分的麻烦,我要是可以在容器外部提供一个映射路径,达到在容器外修改,容器内部就可以自动修改? -v 数据卷技术

Tomcat

作业:docker来装一个tomcat

# 官方的使用
docker run -it --rm tomcat:9.0

# 我们之前的启动都是后台,停止了容器之后,容器还是可以查到。 docker run -it --rm 一般用来测试,用完即删除(容器),镜像不会删

# 下载
docker pull tomcat:9.0

# 启动运行
[root@mengxt ~]# docker run -d -p 3355:8080 --name tomcat01 tomcat:9.0
4e4aa634d65893a52f78fd178c7fdab0f7292ddd4eb7c36ee6e71d388022120e
[root@mengxt ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
4e4aa634d658 tomcat:9.0 "catalina.sh run" 4 seconds ago Up 3 seconds 0.0.0.0:3355->8080/tcp tomcat01
2386c6e5282c nginx "/docker-entrypoint.…" 25 hours ago Up 29 minutes 0.0.0.0:3344->80/tcp nginx01

# 进入容器
[root@mengxt ~]# docker exec -it 4e4aa634d658 /bin/bash
root@4e4aa634d658:/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

# 发现问题:1、linux命令少了,2、没有webapps。 阿里云镜像的原因。默认时最小的镜像,所有不必要的都剔除掉。
# 保证最小可运行的环境
# 从webapps.dist中拷贝一份到webapps下
root@4e4aa634d658:/usr/local/tomcat# cd webapps.dist/
root@4e4aa634d658:/usr/local/tomcat/webapps.dist# ls
ROOT docs examples host-manager manager
root@4e4aa634d658:/usr/local/tomcat/webapps.dist# cd ..
root@4e4aa634d658:/usr/local/tomcat# cp -r webapps.dist/* webapps
root@4e4aa634d658:/usr/local/tomcat# cd webapps
root@4e4aa634d658:/usr/local/tomcat/webapps# ls
ROOT docs examples host-manager manager

思考问题:我们以后要部署项目,如果每次都要进入容器是不是十分麻烦?我要是可以在容器外部提供一个映射路径,webapps,我们在外部放置项目,就自动同步到内部就好了!

ES+Kibana

作业:部署es+kibana

# es 暴露的端口很多
# es 十分的耗内存
# es 的数据一般需要放置到安全目录!挂载

# 启动elasticsearch
# --net somenetwork ? 网络配置
docker run -d --name elasticsearch -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" elasticsearch:7.6.2

# 启动后 linux就卡住了 docker stats 查看cpu的状态
# es 是十分耗内存的
# 查看docker stats
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
fa99599e425c elasticsearch 0.30% 1.2GiB / 1.715GiB 69.94% 524B / 942B 8.57GB / 1.94MB 43
2386c6e5282c nginx01 0.00% 1.391MiB / 1.715GiB 0.08% 3.99kB / 3.2kB 0B / 0B 2
# 测试一下es是否成功了
[root@mengxt ~]# curl localhost:9200
{
"name" : "fa99599e425c",
"cluster_name" : "docker-cluster",
"cluster_uuid" : "BPiEGs_RRDGxqFdirBX9cw",
"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"
}

# 赶紧关闭es,增加内存的限制,修改配置文件 -e 环境配置修改
docker run -d --name elasticsearch02 -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" -e ES_JAVA_OPTS="-Xms64m -Xmx512m" elasticsearch:7.6.2

# 再次查看 docker stats
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
61efb7a34fb9 elasticsearch02 0.35% 385MiB / 1.715GiB 21.92% 0B / 0B 84.2MB / 700kB 43
2386c6e5282c nginx01 0.00% 1.391MiB / 1.715GiB 0.08% 3.99kB / 3.2kB 0B / 0B 2

# 测试es
[root@mengxt ~]# curl localhost:9200
{
"name" : "61efb7a34fb9",
"cluster_name" : "docker-cluster",
"cluster_uuid" : "QikXOVBLQc2Q7U2SOY0_eA",
"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"
}

作业:使用kibana连接es

思考网络如何才能连接过去?(使用evth-pair技术,也就是桥接模式)

使用kibana连接es

可视化

portainer(先用这个)

docker run -d -p 8088:9000 \
--restart=always -v /var/run/docker.sock:/var/run/docker.sock --privileged=true portainer/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.94.221.101:8088/

第一次访问比较久

portainer创建用户

选择本地的

portainer选择local

进入之后的面板

portainer首页

可视化面板我们平时不会使用,用来测试玩玩即可。

Docker镜像讲解

镜像是什么

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

所有的应用,直接打包docker镜像,就可以直接跑起来。

如何得到镜像:

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

Dokcer镜像加载原理

UnionFS(联合文件系统)

UnionFS(联合文件系统):Union文件系统(UnionFS)是一种分层、轻量级并且高性能的文件系统,它支持对文件系统的修改作为一次次提交来一层层叠加,同时可以将不同的目录挂载到同一个虚拟文件系统下(unite serveral directories into a single virtual filesystem)。UnionFS是Docker镜像的基础,镜像可以通过分层来进行继承,基于基础镜像(没有父镜像),可以制作各种具体的应用镜像。

特性:一次加载多个文件系统,但从外面来看,只能看到一个文件系统,联合加载会把各层文件系统叠加起来,这样最终的文件系统会包含所有底层的文件和目录。

Docker镜像加载原理

Docker的镜像实际上是由一层一层的文件系统组成,这种层级的文件系统称作UnionFS。

bootfs(boot file system)主要包含bootloader(加载器)和kernel(内核),bootloader主要是引导加载kernel,linux刚启动时会加载bootfs文件系统,在Docker镜像的最底层是bootfs。这一层和我们典型的linux/unix系统是一样的,包含boot加载器和内核。当boot加载完成之后整个内核就都在内存中了,此时内存的使用权已由bootfs转交给内核,此时系统也会卸载bootfs。

rootfs(root file system),在bootf之上。包含的就是典型linux系统中的/dev,/proc,/etc,/bin等标准目录和文件。rootfs就是各种不同的操作系统发行版,比如Ubuntu,Centos等等。

Docker镜像加载原理1 Docker镜像加载原理2 Docker镜像加载原理3
  • 平时我们安装在虚拟机的Centos都是好几个G,为什么Docker这里才200M?
docker容量1

centos 的 iso 镜像文件包含 bootfs 和 rootfs,而 docker 的 centos 镜像复用操作系统的 bootfs,只有 rootfs 和其他镜像层。

对于一个精简的OS,rootfs可以很小,只需要包含最基本的命令,工具和程序库就可以了,因为底层直接用Host的kernel,自己只需要提供rootfs就可以了。由此可见对于不同的linux发行版,bootfs基本是一致的,rootfs会有差别,因此不同的发行版可以公用bootfs。

  • Docker中一个tomcat镜像为什么有600多M,而一个tomcat安装包才不到100M?
docker容量2

由于docker中的镜像是分层的,所以tomcat虽然只不到100M,但是它需要依赖父镜像和基础镜像,所以整个对外暴露的tomcat镜像大小有600多M。

注:多个镜像间基础镜像(rootfs)是可以复用的

分层理解

分层的镜像

我们可以去下载一个镜像,观察下载的日志输出,可以看到镜像是一层一层的下载!

分层的镜像

思考:为什么Docker镜像要采用这种分层的结构呢?

最大的好处,莫过于是资源共享了!比如有多个镜像都从相同的Base镜像构建而来,那么宿主机只需要在磁盘上保留一份base镜像,同时内存中也只需要加载一份base镜像,这样就可以为所有的容器服务了,而且镜像的每一层都可以被共享。

查看镜像分层的方式可以通过 docker image inspect 镜像:tag 命令!

[root@mengxt ~]# docker image inspect redis
[
{
"Id": "sha256:621ceef7494adfcbe0e523593639f6625795cc0dc91a750629367a8c7b3ccebb",
"RepoTags": [
"redis:latest"
],
"RepoDigests": [
"redis@sha256:0f97c1c9daf5b69b93390ccbe8d3e2971617ec4801fd0882c72bf7cad3a13494"
],
"Parent": "",
"Comment": "",
"Created": "2021-01-13T09:45:41.527587343Z",
"Container": "16535cfaf84a4049b6c02840219e8473787d5610e29409049df3a41bbf77a333",
"ContainerConfig": {
"Hostname": "16535cfaf84a",
"Domainname": "",
"User": "",
"AttachStdin": false,
"AttachStdout": false,
"AttachStderr": false,
"ExposedPorts": {
"6379/tcp": {}
},
"Tty": false,
"OpenStdin": false,
"StdinOnce": false,
"Env": [
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"GOSU_VERSION=1.12",
"REDIS_VERSION=6.0.10",
"REDIS_DOWNLOAD_URL=http://download.redis.io/releases/redis-6.0.10.tar.gz",
"REDIS_DOWNLOAD_SHA=79bbb894f9dceb33ca699ee3ca4a4e1228be7fb5547aeb2f99d921e86c1285bd"
],
"Cmd": [
"/bin/sh",
"-c",
"#(nop) ",
"CMD [\"redis-server\"]"
],
"Image": "sha256:222c0cecc006d8c73a04a58b5fa15ebae171a6e82a8ee8650ae616f6f1798ef4",
"Volumes": {
"/data": {}
},
"WorkingDir": "/data",
"Entrypoint": [
"docker-entrypoint.sh"
],
"OnBuild": null,
"Labels": {}
},
"DockerVersion": "19.03.12",
"Author": "",
"Config": {
"Hostname": "",
"Domainname": "",
"User": "",
"AttachStdin": false,
"AttachStdout": false,
"AttachStderr": false,
"ExposedPorts": {
"6379/tcp": {}
},
"Tty": false,
"OpenStdin": false,
"StdinOnce": false,
"Env": [
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"GOSU_VERSION=1.12",
"REDIS_VERSION=6.0.10",
"REDIS_DOWNLOAD_URL=http://download.redis.io/releases/redis-6.0.10.tar.gz",
"REDIS_DOWNLOAD_SHA=79bbb894f9dceb33ca699ee3ca4a4e1228be7fb5547aeb2f99d921e86c1285bd"
],
"Cmd": [
"redis-server"
],
"Image": "sha256:222c0cecc006d8c73a04a58b5fa15ebae171a6e82a8ee8650ae616f6f1798ef4",
"Volumes": {
"/data": {}
},
"WorkingDir": "/data",
"Entrypoint": [
"docker-entrypoint.sh"
],
"OnBuild": null,
"Labels": null
},
"Architecture": "amd64",
"Os": "linux",
"Size": 104285909,
"VirtualSize": 104285909,
"GraphDriver": {
"Data": {
"LowerDir": "/var/lib/docker/overlay2/1c0a8076c0c0abf9b02a154c8fc1414018d7e81a07b525dd884ee0e4898b1a96/diff:/var/lib/docker/overlay2/aa39bb15db58ca12c44ffd0002dc687e607fceb255d32397392b9e87d08e5513/diff:/var/lib/docker/overlay2/384fc29f50d6d2d64d30c145a75156f165e4d31b83489e816eb83bd432737bc8/diff:/var/lib/docker/overlay2/cd8c81794a9e87764e90be83f8da103573e49f41b0c2c27af427c0205b0a5de2/diff:/var/lib/docker/overlay2/715ab9f38b16933895f38227733504c865ce577973644f2b1904513ffd2a426a/diff",
"MergedDir": "/var/lib/docker/overlay2/8ca92df701dcb80037d064354466bc7f64d6ff8872e1c11c2340b3870b0acb42/merged",
"UpperDir": "/var/lib/docker/overlay2/8ca92df701dcb80037d064354466bc7f64d6ff8872e1c11c2340b3870b0acb42/diff",
"WorkDir": "/var/lib/docker/overlay2/8ca92df701dcb80037d064354466bc7f64d6ff8872e1c11c2340b3870b0acb42/work"
},
"Name": "overlay2"
},
"RootFS": {
"Type": "layers",
"Layers": [
"sha256:cb42413394c4059335228c137fe884ff3ab8946a014014309676c25e3ac86864",
"sha256:8e14cb7841faede6e42ab797f915c329c22f3b39026f8338c4c75de26e5d4e82",
"sha256:1450b8f0019c829e638ab5c1f3c2674d117517669e41dd2d0409a668e0807e96",
"sha256:f927192cc30cb53065dc266f78ff12dc06651d6eb84088e82be2d98ac47d42a0",
"sha256:a24a292d018421783c491bc72f6601908cb844b17427bac92f0a22f5fd809665",
"sha256:3480f9cdd491225670e9899786128ffe47054b0a5d54c48f6b10623d2f340632"
]
},
"Metadata": {
"LastTagTime": "0001-01-01T00:00:00Z"
}
}
]
[root@mengxt ~]#

理解:

所有的Docker镜像都起始于一个基础镜像,当进行修改或者增加新的内容时,就会在当前镜像层之上,创建新的镜像层。

举一个简单的例子,例如基于Ubuntu Linux 16.04创建一个新的镜像,这就是新镜像的第一层;如果在该镜像中添加Python包,就会在基础镜像层之上创建第二个镜像层;如果继续添加一个安全补丁,就会创建第三个镜像层。

该镜像当前已经包含了3个镜像层。

3个镜像层

在添加额外的镜像层的同时,镜像始终保持时当前所有镜像层的组合,理解这一点非常重要。举了一个简单的例子,每个镜像层包含3个文件,而镜像包含了来自两个镜像层的6个文件。

如果上层镜像层中的文件覆盖了底层镜像层的文件。这样就会使得文件的更新版本作为一个新镜像层添加到镜像当中。

Docker通过存储引擎(新版本采用快照机制)的方式来实现镜像层堆栈,并保证多个镜像层对外展示为统一的文件系统。

Linux上可用的存储引擎有AUFS、Overlay2、Device Mapper、Btrfs以及ZFS。顾名思义,每种存储引擎都基于Linux中对应的文件系统,并且每种存储引擎都有其独有的特点。

Docker在windows上仅支持windowfilter一种存储引擎,该引擎基于NTFS文件系统之上实现了分层和CoW。

特点

Docker镜像都是只读的,当容器启动时,一个新的可写层被加载到镜像的顶部!

这一层就是我们通常说的容器层,容器之下的都叫镜像层!

Docker镜像与容器的概念

如何提交一个自己的镜像?

commit镜像

方式一:(还可以使用DockerFile来构建镜像)

docker commit 提交容器成为一个新的副本
docker commit -m="提交的描述信息" -a="作者" 容器ID 目标镜像名:[TAG]

实战测试

# 启动一个默认的tomcat

# 发现这个默认的tomcat是没有webapps应用的,是镜像的原因,官方的镜像默认webapps下面是没有东西的!

# 我们自己拷贝进去了基本的文件

# 将我们操作过的容器通过commit命令提交为一个新的镜像!我们以后就使用这个新镜像就可以了!

说明:如果你想要保持当前容器的状态,就可以通过commit来提交,获得一个镜像。就好比我们以前学习VM时所使用的快照。

容器数据卷

什么是容器数据卷

docker的理念回顾

将应用和环境打包成一个镜像!

数据?如果数据都在容器中,那么我们删除容器,数据就会丢失!需求:数据可以持久化

MySQL,容器删除,删库跑路!需求:MySQL数据可以存储在本地!

需要有一个数据共享的技术!Docker容器中产生的数据,同步到本地!

这就是卷技术!目录的挂载,将我们容器中的目录,挂载到Linux上面!

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

使用数据卷

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

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

# 测试
[root@mengxt ~]# docker run -it -v /home/ceshi:/home centos /bin/bash
[root@4a362f36cbec /]#

# 启动后可以通过 docker inspect 容器ID 来查看详细内容

"Mounts": [
{
"Type": "bind",
"Source": "/home/ceshi", # 主机内地址
"Destination": "/home", # docker容器内的地址
"Mode": "",
"RW": true,
"Propagation": "rprivate"
}
],

测试文件的同步

再次测试

1、停止容器

2、宿主机上修改文件

3、容器内的数据依旧是同步的

好处:我们以后修改只需要在本地修改即可,容器内会自动同步

实战:安装MySQL

# 下载镜像
[root@mengxt ~]# docker pull mysql:5.7

# 运行容器,需要做数据挂载
# 安装启动mysql,需要配置密码的,这是要注意的!
# 官方测试,docker run --name some-mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:tag

# 启动mysql
# -d 后台运行
# -p 端口映射
# -v 数据卷挂载
# -e 环境配置
# --name 容器名称
[root@mengxt ~]# 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

# 启动成功之后,我们在本地使用 sqlyog 来测试一下
# sqlyog---连接到服务器的3310---3310和容器内的3306映射
# 在本地测试创建一个数据库,查看一下我们映射的路径是否ok!

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

具名和匿名挂载

# 匿名挂载
-v 容器内路径
docker run -d -P --name nginx01 -v /etc/nginx nginx
# 通过docker inspect 容器ID查看
"Mounts": [
{
"Type": "volume",
"Name": "94f0fe15cdbd5d8f8a8a2b97ed1dfae60177019bd1ac0d22ed6b8310a56aeed0",
"Source": "/var/lib/docker/volumes/94f0fe15cdbd5d8f8a8a2b97ed1dfae60177019bd1ac0d22ed6b8310a56aeed0/_data",
"Destination": "/etc/nginx",
"Driver": "local",
"Mode": "",
"RW": true,
"Propagation": ""
}
],
# 我们发现容器中的/etc/nginx被挂载到了/var/lib/docker/volumes/94f0fe15cdbd5d8f8a8a2b97ed1dfae60177019bd1ac0d22ed6b8310a56aeed0/_data

# 我们还可以通过 docker volume 来查看和操作卷
# docker volume ls 查看所有的卷
[root@mengxt ~]# docker volume ls
DRIVER VOLUME NAME
local 9d15e3fb47f10587a161bdc98bf4a68627d8c754f9e1c7f8579d5d29da5ed479
local 94f0fe15cdbd5d8f8a8a2b97ed1dfae60177019bd1ac0d22ed6b8310a56aeed0
[root@mengxt ~]#

# 这种就是匿名挂载

# 具名挂载
[root@mengxt ~]# docker run -d -P --name nginx03 -v juming-nginx:/etc/nginx nginx
2a051817efe2812d02a86b8284ccf6ef84a1a2a667d84ca3c17bc7af1224cdea
[root@mengxt ~]# docker volume ls
DRIVER VOLUME NAME
local 9d15e3fb47f10587a161bdc98bf4a68627d8c754f9e1c7f8579d5d29da5ed479
local 94f0fe15cdbd5d8f8a8a2b97ed1dfae60177019bd1ac0d22ed6b8310a56aeed0
local juming-nginx
[root@mengxt ~]#

# 通过 -v 卷名:容器内路径
# 查看一下这个卷
[root@mengxt ~]# docker volume inspect juming-nginx
[
{
"CreatedAt": "2021-03-28T09:48:36+08:00",
"Driver": "local",
"Labels": null,
"Mountpoint": "/var/lib/docker/volumes/juming-nginx/_data",
"Name": "juming-nginx",
"Options": null,
"Scope": "local"
}
]

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

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

# 如何确定是具名还是匿名挂载,还是指定路径挂载
-v 容器内路径 # 匿名挂载
-v 卷名:容器内路径 # 具名挂载
-v 宿主机路径:容器内路径 # 指定路径挂载

拓展:

# 通过 -v 容器内路径:ro / rw 改变读写权限
ro readonly # 只读,这个就只能通过宿主机来操作,容器内无法操作!
rw readwrite # 可读可写

# 一旦设置了容器权限,容器对我们挂载出来的内容就有限定了!
docker run -d -P --name nginx03 -v juming-nginx:/etc/nginx:ro nginx
docker run -d -P --name nginx03 -v juming-nginx:/etc/nginx:rw nginx

初识DockerFile

DockerFile就是用来构建docker镜像的构建文件!命令脚本!

通过这个脚本可以生成镜像,镜像是一层一层的,脚本是一个一个命令,每个命令都是一层!

方式二:

# 创建一个dockerfile文件,名字可以随意,建议 dockerfile
# 文件中的内容 指令(大写)参数

FROM centos

VOLUME ["volume01","volume02"] # 匿名挂载

CMD echo "---end---"

CMD /bin/bash

# 这里每一个命令就是镜像的一层

# 构建镜像
dokcer build -f dockerfile文件 -t 镜像名称[:TAG] path路径
# 使用我们自己构建的镜像来启动一个容器
[root@mengxt docker-test-volume]# docker run -it mycentos /bin/bash
[root@34a47a09cc04 /]# ls -l
total 56
lrwxrwxrwx 1 root root 7 Nov 3 15:22 bin -> usr/bin
drwxr-xr-x 5 root root 360 Mar 28 02:20 dev
drwxr-xr-x 1 root root 4096 Mar 28 02:20 etc
drwxr-xr-x 2 root root 4096 Nov 3 15:22 home
lrwxrwxrwx 1 root root 7 Nov 3 15:22 lib -> usr/lib
lrwxrwxrwx 1 root root 9 Nov 3 15:22 lib64 -> usr/lib64
drwx------ 2 root root 4096 Dec 4 17:37 lost+found
drwxr-xr-x 2 root root 4096 Nov 3 15:22 media
drwxr-xr-x 2 root root 4096 Nov 3 15:22 mnt
drwxr-xr-x 2 root root 4096 Nov 3 15:22 opt
dr-xr-xr-x 100 root root 0 Mar 28 02:20 proc
dr-xr-x--- 2 root root 4096 Dec 4 17:37 root
drwxr-xr-x 11 root root 4096 Dec 4 17:37 run
lrwxrwxrwx 1 root root 8 Nov 3 15:22 sbin -> usr/sbin
drwxr-xr-x 2 root root 4096 Nov 3 15:22 srv
dr-xr-xr-x 13 root root 0 Mar 28 02:20 sys
drwxrwxrwt 7 root root 4096 Dec 4 17:37 tmp
drwxr-xr-x 12 root root 4096 Dec 4 17:37 usr
drwxr-xr-x 20 root root 4096 Dec 4 17:37 var
drwxr-xr-x 2 root root 4096 Mar 28 02:20 volume01 # 这个目录就是我们生成镜像的时候自动挂载的,数据卷目录
drwxr-xr-x 2 root root 4096 Mar 28 02:20 volume02 # 这个目录就是我们生成镜像的时候自动挂载的,数据卷目录
[root@34a47a09cc04 /]#

# 这个卷和外部一定有一个同步的目录!
"Mounts": [
{
"Type": "volume",
"Name": "a4c44ef0c6cd261a28aefe3e20177c80587bceee2da2fe7c43f5ab54573b3070",
"Source": "/var/lib/docker/volumes/a4c44ef0c6cd261a28aefe3e20177c80587bceee2da2fe7c43f5ab54573b3070/_data",
"Destination": "volume02",
"Driver": "local",
"Mode": "",
"RW": true,
"Propagation": ""
},
{
"Type": "volume",
"Name": "8c5a0e0fd0ced0fdec19cd00f419142c1ac439a4d91b4f96a77f5d342d2fd114",
"Source": "/var/lib/docker/volumes/8c5a0e0fd0ced0fdec19cd00f419142c1ac439a4d91b4f96a77f5d342d2fd114/_data",
"Destination": "volume01",
"Driver": "local",
"Mode": "",
"RW": true,
"Propagation": ""
}
],

测试一下刚才的文件是否同步出去了

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

假设构建镜像时候没有挂载卷,那么在启动容器的时候要手动镜像挂载,-v 卷名:容器内路径

数据卷容器

多个容器同步数据!

# 启动3个容器,通过我们自己构建的镜像启动
# 测试,删除docker01,查看一下docker02是否还有这个文件
# 测试依旧还有

多个mysql实现数据共享

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

docker run -d -p 3311:3306 -e MYSQL_ROOT_PASSWORD=123456 --name mysql02 --volumes-from mysql01 mysql:5.7

# 这个时候可以实现两个mysql数据同步!

结论:

容器之间配置信息的传递,数据卷容器的生命周期一直持续到没有容器使用为止。

但是一旦你持久化了本地,这个时候,本地的数据是不会删除的。(数据只有一份,多个容器间共享,不是复制!!!)

DockerFile

DockerFile介绍

dockerfile是用来构建docker镜像的文件!命令参数脚本!

构建步骤:

1、编写一个dockerfile文件

2、docker build 构建成为一个镜像

3、docker run 运行镜像

4、docker push 发布镜像(DockerHub、阿里云镜像仓库)

查看一下官方是怎么做的?

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

DockerFile构建过程

基础知识:

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

dockerfile是面向开发的,我们以后要发布项目,做镜像,就需要编写dockerfile文件。

步骤:

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

DockerFile的指令

FROM # 基础镜像,一切从这个开始构建 例如 centos
MAINTAINER # 镜像是谁写的,姓名+邮箱
RUN # 镜像构建的时候需要运行的命令
ADD # 步骤:例如tomcat镜像,这个tomcat压缩包!就是添加内容
WORKDIR # 镜像的工作目录
VOLUME # 挂载的目录
EXPOSE # 暴露端口配置
CMD # 指定这个容器启动的时候要运行的命令,只有最后一个会生效,可被替代
ENTRYPOINT # 指定这个容器启动的时候要运行的命令,可以追加命令
ONBUILD # 当构建一个被继承 DockerFile 这个时候就会运行 ONBUILD 的指令。触发指令
COPY # 类似ADD,将我们的文件拷贝到镜像中
ENV # 构建的时候设置环境变量

实战测试:

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

创建一个自己的centos

# 1、编写dockerfile文件
[root@mengxt dockerfile]# cat mydockerfile-centos
FROM centos
MAINTAINER mumuxi<1923570155@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@mengxt dockerfile]#

# 2、通过这个文件构建镜像
[root@mengxt dockerfile]# docker build -f mydockerfile-centos -t mycentos:1.0 .
...
Successfully built e19d351b7e0b
Successfully tagged mycentos:1.0

# 3、测试运行

对比:之前的原生的centos

我们增加之后的镜像

我们可以列出本地进行的变更历史

我们平时拿到一个镜像,就可以研究一下它是怎么做的了

CMD 和 ENTRYPOINT 区别

CMD # 指定这个容器启动的时候要运行的命令,只有最后一个会生效,可被替代
ENTRYPOINT # 指定这个容器启动的时候要运行的命令,可以追加命令

测试cmd:

# 编写 dockerfile
[root@mengxt dockerfile]# vim dockerfile-cmd-test
FROM centos
CMD ["ls","-a"]

# 构建镜像
[root@mengxt dockerfile]# docker build -f dockerfile-cmd-test -t cmdtest .
Sending build context to Docker daemon 3.072kB
Step 1/2 : FROM centos
---> 300e315adb2f
Step 2/2 : CMD ["ls","-a"]
---> Running in 1f6c9242d57c
Removing intermediate container 1f6c9242d57c
---> fcadb1657fde
Successfully built fcadb1657fde
Successfully tagged cmdtest:latest

# run 运行,发现我们的ls -a命令生效了
[root@mengxt dockerfile]# docker run fcadb1657fde
.
..
.dockerenv
bin
dev
etc
home
lib
lib64
lost+found
media
mnt
opt
proc
root
run
sbin
srv
sys
tmp
usr
var
[root@mengxt dockerfile]#

# 想追加一个命令 -l 形成 ls -al
# 注意 命令 需要放在容器ID后面
[root@mengxt dockerfile]# docker run fcadb1657fde -l
docker: Error response from daemon: OCI runtime create failed: container_linux.go:367: starting container process caused: exec: "-l": executable file not found in $PATH: unknown.
# cmd的清理下 -l 替换了CMD ["ls","-a"] 命令,-l 不是命令所以报错

测试ENTRYPOINT:

[root@mengxt dockerfile]# vim dockerfile-cmd-entrypoint
FROM centos
ENTRYPOINT ["ls","-a"]

[root@mengxt dockerfile]# docker build -f dockerfile-cmd-entrypoint -t entorypoint-test .
Sending build context to Docker daemon 4.096kB
Step 1/2 : FROM centos
---> 300e315adb2f
Step 2/2 : ENTRYPOINT ["ls","-a"]
---> Running in 5fea29bbf325
Removing intermediate container 5fea29bbf325
---> 8c2553155ce7
Successfully built 8c2553155ce7
Successfully tagged entorypoint-test:latest
[root@mengxt dockerfile]# docker run 8c2553155ce7
.
..
.dockerenv
bin
dev
etc
home
lib
lib64
lost+found
media
mnt
opt
proc
root
run
sbin
srv
sys
tmp
usr
var

# 我们的追加命令,是直接拼接到我们的 ENTRYPOINT 命令的后面!
[root@mengxt dockerfile]# docker run 8c2553155ce7 -l
total 56
drwxr-xr-x 1 root root 4096 Mar 28 08:58 .
drwxr-xr-x 1 root root 4096 Mar 28 08:58 ..
-rwxr-xr-x 1 root root 0 Mar 28 08:58 .dockerenv
lrwxrwxrwx 1 root root 7 Nov 3 15:22 bin -> usr/bin
drwxr-xr-x 5 root root 340 Mar 28 08:58 dev
drwxr-xr-x 1 root root 4096 Mar 28 08:58 etc
drwxr-xr-x 2 root root 4096 Nov 3 15:22 home
lrwxrwxrwx 1 root root 7 Nov 3 15:22 lib -> usr/lib
lrwxrwxrwx 1 root root 9 Nov 3 15:22 lib64 -> usr/lib64
drwx------ 2 root root 4096 Dec 4 17:37 lost+found
drwxr-xr-x 2 root root 4096 Nov 3 15:22 media
drwxr-xr-x 2 root root 4096 Nov 3 15:22 mnt
drwxr-xr-x 2 root root 4096 Nov 3 15:22 opt
dr-xr-xr-x 95 root root 0 Mar 28 08:58 proc
dr-xr-x--- 2 root root 4096 Dec 4 17:37 root
drwxr-xr-x 11 root root 4096 Dec 4 17:37 run
lrwxrwxrwx 1 root root 8 Nov 3 15:22 sbin -> usr/sbin
drwxr-xr-x 2 root root 4096 Nov 3 15:22 srv
dr-xr-xr-x 13 root root 0 Mar 28 02:20 sys
drwxrwxrwt 7 root root 4096 Dec 4 17:37 tmp
drwxr-xr-x 12 root root 4096 Dec 4 17:37 usr
drwxr-xr-x 20 root root 4096 Dec 4 17:37 var
[root@mengxt dockerfile]#

DockerFile中很多的命令都十分相似,我们需要了解它们的区别。

实战:Tomcat镜像

  1. 准备镜像文件 tomcat 压缩包,jdk的压缩包
  1. 编写dockerfile文件官方命名Dockerfile,build会自动寻找这个文件,就不需要 -f 指定了FROM centos
    MAINTAINER mumuxi<1923570155@qq.com>

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

    ADD jdk-8u271-linux-x64.tar.gz /usr/local/
    ADD apache-tomcat-9.0.35.tar.gz /usr/local/

    RUN yum -y install vim

    ENV MYPATH /usr/local
    WORKDIR $MYPATH

    ENV JAVA_HOME /usr/local/jdk1.8.0_271
    ENV CLASSPATH $JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
    ENV CATALINA_HOME /usr/local/apache-tomcat-9.0.35
    ENV PATH $PATH:$JAVA_HOME/bin:$CATALINA_HOME/lib:$CATALINA_HOME/bin

    EXPOSE 8080

    CMD $CATALINA_HOME/bin/startup.sh && tail -F $CATALINA_HOME/bin/logs/catalina.out
  2. 构建镜像docker build -t diytomcat .
  3. 启动镜像docker run -d -p 9090:8080 –name diytomcat01 -v /home/tomcat/test:/usr/local/apache-tomcat-9.0.35/webapps/test -v /home/tomcat/tomcatlogs:/usr/local/apache-tomcat-9.0.35/logs diytomcat
  4. 访问测试
  1. 发布项目(由于做了卷挂载,我们直接在本地编写项目就可以发布了)<?xml version=”1.0″ encoding=”UTF-8″?>
    <web-app version=”2.5″
    xmlns=”http://java.sun.com/xml/ns/j2ee”
    xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
    xsi:schemaLocation=”http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd”>
    </web-app><%@ page contentType=”text/html;charset=UTF-8″ language=”java” %>
    <html>
    <body>
    <h2>Hello World!</h2>
    <%
    System.out.println(“—test web logs—“);
    %>
    </body>
    </html>
  2. 访问测试

发布自己的镜像

发布到DockerHub

1、地址https://registry.hub.docker.com/

2、确认这个账号可以登录

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

[root@mengxt dockerfile]# 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@mengxt dockerfile]#
[root@mengxt dockerfile]# docker login -u mengxuanting
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@mengxt dockerfile]#

4、登录完毕后就可以提交镜像了

# 直接 push 出现 拒绝:请求的对资源的访问被拒绝 的错误
[root@mengxt dockerfile]# docker push diytomcat
Using default tag: latest
The push refers to repository [docker.io/library/diytomcat]
524b131a8212: Preparing
2d97637a90f1: Preparing
9999f50893fd: Preparing
519781374c39: Preparing
2653d992f4ef: Preparing
denied: requested access to the resource is denied

# 使用 docker tag 对镜像进行重命名,命名为 docker hub的用户名/镜像名[:TAG]。
[root@mengxt dockerfile]# docker tag diytomcat mengxuanting/diytomcat:1.0
[root@mengxt dockerfile]# docker push mengxuanting/diytomcat:1.0
The push refers to repository [docker.io/mengxuanting/diytomcat]
524b131a8212: Pushing [==================> ] 21.64MB/58.01MB
2d97637a90f1: Pushing [===========================> ] 8.457MB/15.59MB
9999f50893fd: Pushing [=> ] 12.53MB/355.3MB
519781374c39: Pushed
2653d992f4ef: Pushing [====> ] 19.66MB/209.3MB

发布的时候也是按照镜像的层级来进行提交的!

发布到阿里云镜像服务

1、登录阿里云

2、找到容器镜像服务

3、创建命名空间

4、创建镜像仓库

5、浏览阿里云

阿里云容器镜像的就参考官方文档。

小结

Docker网络

理解Docker0

测试

[root@mengxt ~]# 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:16:c5:32 brd ff:ff:ff:ff:ff:ff
inet 172.26.69.186/20 brd 172.26.79.255 scope global dynamic eth0 # 阿里云内网地址
valid_lft 314563855sec preferred_lft 314563855sec
3: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default
link/ether 02:42:dc:43:e5:97 brd ff:ff:ff:ff:ff:ff
inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0 # docker0地址
valid_lft forever preferred_lft forever

三个网络

# 问题:docker是如何处理容器网络访问的?

# docker run -d -P --name tomcat01 tomcat
# 使用 ip addr 查看容器的内部网络地址
# 发现容器启动的时候会得到一个 eth0@if175 ip地址,docker分配的!
[root@mengxt ~]# docker exec 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
174: eth0@if175: <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

# 思考:linux能不能ping通容器内部
[root@mengxt ~]# 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.067 ms
64 bytes from 172.17.0.2: icmp_seq=2 ttl=64 time=0.053 ms
64 bytes from 172.17.0.2: icmp_seq=3 ttl=64 time=0.058 ms

# linux 可以 ping 通 docker 容器内部

原理

1、我们每启动一个docker容器,docker就会给docker容器分配一个ip;我们只要安装了docker,就会有一个网卡 docker0。

桥接模式,使用的技术是evth-pair技术!

# 再次在宿主机上测试ip addr
[root@mengxt ~]# 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:16:c5:32 brd ff:ff:ff:ff:ff:ff
inet 172.26.69.186/20 brd 172.26.79.255 scope global dynamic eth0
valid_lft 314562801sec preferred_lft 314562801sec
3: docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
link/ether 02:42:dc:43:e5:97 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
175: veth961766b@if174: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master docker0 state UP group default
link/ether 56:c9:68:cd:86:61 brd ff:ff:ff:ff:ff:ff link-netnsid 0

2、再启动一个容器,发现又多了一对网卡

# 宿主机
[root@mengxt ~]# 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:16:c5:32 brd ff:ff:ff:ff:ff:ff
inet 172.26.69.186/20 brd 172.26.79.255 scope global dynamic eth0
valid_lft 314562573sec preferred_lft 314562573sec
3: docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
link/ether 02:42:dc:43:e5:97 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
175: veth961766b@if174: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master docker0 state UP group default
link/ether 56:c9:68:cd:86:61 brd ff:ff:ff:ff:ff:ff link-netnsid 0
177: vetha0a6139@if176: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master docker0 state UP group default
link/ether 12:b9:8d:65:9c:55 brd ff:ff:ff:ff:ff:ff link-netnsid 1

# 容器
[root@mengxt ~]# 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
176: eth0@if177: <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
# 我们发现这个容器带来网卡,都是一对对的
# evth-pair 就是一对的虚拟设备接口,他们都是成对出现的,一端连着网络协议,一端彼此相连
# 正因为有这个特性,evth-pair 充当一个桥梁,连接各种虚拟网络设备

3、我们来测试下 tomcat01 和 tomcat02 是否可以ping通!

[root@mengxt ~]# 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.095 ms
64 bytes from 172.17.0.2: icmp_seq=2 ttl=64 time=0.071 ms
64 bytes from 172.17.0.2: icmp_seq=3 ttl=64 time=0.092 ms

# 结论,容器间是可以ping通的!

网络模型图:

结论:tomcat01 和 tomcat02 是共用的一个路由器,docker0。

所有的容器在不指定网络的情况下,都是 docker0 路由器的,docker会给我们的容器分配一个可用的IP

小结

Docker使用的是linux的桥接,在宿主机中是一个Docker容器的网桥 docker0

Docker中的所有的网络接口都是虚拟的,虚拟的转发效率高!

只有容器删除,对应一对网桥就没了

–link

思考一个场景,我们编写了一个微服务,database url=ip:port,项目不重启,数据库ip换掉了,我们希望可以处理这个问题,可以使用名称来进行访问容器?

# 直接ping不通
[root@mengxt ~]# docker exec tomcat02 ping tomcat01
ping: tomcat01: Name or service not known

# 如何解决,通过 --link
[root@mengxt ~]# docker run -d -P --name tomcat03 --link tomcat01 tomcat
7cf72e0f2af2ab452d9784108860817c029b0c6b76b9ceaa4dff9fb0eb2e48f2

# 发现可以ping通了
[root@mengxt ~]# docker exec tomcat03 ping tomcat01
PING tomcat01 (172.17.0.2) 56(84) bytes of data.
64 bytes from tomcat01 (172.17.0.2): icmp_seq=1 ttl=64 time=0.094 ms
64 bytes from tomcat01 (172.17.0.2): icmp_seq=2 ttl=64 time=0.067 ms
64 bytes from tomcat01 (172.17.0.2): icmp_seq=3 ttl=64 time=0.067 ms
64 bytes from tomcat01 (172.17.0.2): icmp_seq=4 ttl=64 time=0.068 ms

# 那么tomcat01可以ping通tomcat03吗?测试发现并不能
[root@mengxt ~]# docker exec tomcat01 ping tomcat03
ping: tomcat03: Name or service not known

# 我们可以通过 docker network inspect 命令查看docker的网络信息

[root@mengxt ~]# docker network inspect bridge
[
{
"Name": "bridge",
"Id": "06d798af96d7cb94c3f41233c0f8eba76e6b9c21c2c656ebf5013c2fda970796",
"Created": "2021-03-21T10:39:54.943232641+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" # docker0
}
]
},
"Internal": false,
"Attachable": false,
"Ingress": false,
"ConfigFrom": {
"Network": ""
},
"ConfigOnly": false,
"Containers": {
"10763f99bcd9280fa3531fb668a180539948bb47c39c825b776f6ad93ea543f6": {
"Name": "tomcat02",
"EndpointID": "3f86d62e2e5172e958a20d4cc32109e8730fdf66f4109b8c647b066360b73f87",
"MacAddress": "02:42:ac:11:00:03",
"IPv4Address": "172.17.0.3/16", # 容器运行时,docker默认分配的地址
"IPv6Address": ""
},
"7cf72e0f2af2ab452d9784108860817c029b0c6b76b9ceaa4dff9fb0eb2e48f2": {
"Name": "tomcat03",
"EndpointID": "4eb95b337ca8ba0d84b8f1694ed86d609c1e96e7317fa180e2cd17d3eee2d6bc",
"MacAddress": "02:42:ac:11:00:04",
"IPv4Address": "172.17.0.4/16",
"IPv6Address": ""
},
"f69b56887788455881e30e0a688e61e00abe6b759703eb55202ddc808063e9d7": {
"Name": "tomcat01",
"EndpointID": "6940fe6fc726a402d31c673ff07f1d72b95280fb1a091332bff323ab62eebfc7",
"MacAddress": "02:42:ac:11:00:02",
"IPv4Address": "172.17.0.2/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": {}
}
]

# 我们来看一下 tomcat03 和 tomcat01 的绑定关系
# 1、通过 inspect 容器
[root@mengxt ~]# docker inspect tomcat03
"Links": [
"/tomcat01:/tomcat03/tomcat01" # 注意这个配置
],
# 2、通过 tomcat03 容器的 hosts文件配置
[root@mengxt ~]# docker exec 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.2 tomcat01 f69b56887788
172.17.0.4 7cf72e0f2af2

–link 就是我们在相应容器的hosts配置中增加了一个 172.17.0.2 tomcat01 f69b56887788

不建议使用 –link

自定义网络!不适用于docker0!

docker0问题:他不支持容器名连接访问

自定义网络

查看所有的docker网络

网络模式

bridge:桥接。docker默认(自己自定义网络也使用 bridge 模式)

none:不配置网络

host:和宿主机共享网络

container:容器间网络联通(用的少,局限很大)

测试

# 我们直接启动的命令,会有一个默认的参数 --net bridge,而这个就是我们的docker0
docker run -d -P --name tomcat01 tomcat
docker run -d -P --name tomcat01 --net bridge tomcat

# docker0的特点:默认的,域名不能访问,--link可以打通连接!

# 自定义网络
# -d bridge # 网络模式
# --subnet 192.168.0.0/16 # 子网
# --gateway 192.168.0.1 # 网关
[root@mengxt ~]# docker network create -d bridge --subnet 192.168.0.0/16 --gateway 192.168.0.1 mynet
d8a69ce39223fc381fd5d620cdfb8673acc6a47ce0c4e3e02f4a0c662d8b913e
[root@mengxt ~]# docker network ls
NETWORK ID NAME DRIVER SCOPE
06d798af96d7 bridge bridge local
cf427638b8cb host host local
d8a69ce39223 mynet bridge local
7cf16a76b8eb none null local
[root@mengxt ~]#

我们自己的网络就创建好了

[root@mengxt ~]# docker run -d -P --name tomcat-net-01 --net mynet tomcat
5d2473613fb932b958680e8d3cdfd7e6c4b25aed0cab6418974b6d17f8d757cb
[root@mengxt ~]# docker run -d -P --name tomcat-net-02 --net mynet tomcat
d9d4668328a3459158a801af933480759f2a4587c8d3362c19a932022452b925
[root@mengxt ~]# docker network inspect mynet
[
{
"Name": "mynet",
"Id": "d8a69ce39223fc381fd5d620cdfb8673acc6a47ce0c4e3e02f4a0c662d8b913e",
"Created": "2021-03-31T21:11:58.456476421+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": {
"5d2473613fb932b958680e8d3cdfd7e6c4b25aed0cab6418974b6d17f8d757cb": {
"Name": "tomcat-net-01",
"EndpointID": "94f3f273472ec037ce4240f2c74ecf9e1fd767de91713a2339616da386a6f1f1",
"MacAddress": "02:42:c0:a8:00:02",
"IPv4Address": "192.168.0.2/16",
"IPv6Address": ""
},
"d9d4668328a3459158a801af933480759f2a4587c8d3362c19a932022452b925": {
"Name": "tomcat-net-02",
"EndpointID": "98c58a1439b22d1fffe47002b65ece927c57ba55e15086861b80b920f1d2d5b0",
"MacAddress": "02:42:c0:a8:00:03",
"IPv4Address": "192.168.0.3/16",
"IPv6Address": ""
}
},
"Options": {},
"Labels": {}
}
]
[root@mengxt ~]#

再次测试容器间的网络连通性,发现我们不需要再使用 –link 就能通过容器名称 ping 通

[root@mengxt ~]# docker exec tomcat-net-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.093 ms
64 bytes from 192.168.0.3: icmp_seq=2 ttl=64 time=0.072 ms

[root@mengxt ~]# docker exec tomcat-net-01 ping tomcat-net-02
PING tomcat-net-02 (192.168.0.3) 56(84) bytes of data.
64 bytes from tomcat-net-02.mynet (192.168.0.3): icmp_seq=1 ttl=64 time=0.056 ms
64 bytes from tomcat-net-02.mynet (192.168.0.3): icmp_seq=2 ttl=64 time=0.071 ms
64 bytes from tomcat-net-02.mynet (192.168.0.3): icmp_seq=3 ttl=64 time=0.071 ms

思考一个问题,现在 tomcat-net-01 可以 ping 通 tomcat-net-02,那么反过来可以吗?

我们测试一下,发现是可以的!

[root@mengxt ~]# docker exec tomcat-net-02 ping tomcat-net-01
PING tomcat-net-01 (192.168.0.2) 56(84) bytes of data.
64 bytes from tomcat-net-01.mynet (192.168.0.2): icmp_seq=1 ttl=64 time=0.055 ms
64 bytes from tomcat-net-01.mynet (192.168.0.2): icmp_seq=2 ttl=64 time=0.068 ms

我们看下各自的hosts文件是怎样的?并不需要增加额外的配置

[root@mengxt ~]# docker exec tomcat-net-01 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
192.168.0.2 5d2473613fb9
[root@mengxt ~]# docker exec tomcat-net-02 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
192.168.0.3 d9d4668328a3
[root@mengxt ~]#

我们使用 ip addr 来查看一下宿主机上的网络

[root@mengxt ~]# 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:16:c5:32 brd ff:ff:ff:ff:ff:ff
inet 172.26.69.186/20 brd 172.26.79.255 scope global dynamic eth0
valid_lft 314389614sec preferred_lft 314389614sec
3: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default
link/ether 02:42:dc:43:e5:97 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
180: br-d8a69ce39223: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
link/ether 02:42:0e:78:b5:cb brd ff:ff:ff:ff:ff:ff
inet 192.168.0.1/16 brd 192.168.255.255 scope global br-d8a69ce39223
valid_lft forever preferred_lft forever
182: veth8f8b8e8@if181: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master br-d8a69ce39223 state UP group default
link/ether ce:78:12:20:cc:5c brd ff:ff:ff:ff:ff:ff link-netnsid 0
184: veth97fd744@if183: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master br-d8a69ce39223 state UP group default
link/ether 06:d4:6c:39:21:43 brd ff:ff:ff:ff:ff:ff link-netnsid 1

结论:我们自定义的网络docker都已经帮我们维护好了对应的关系,我们不需要做额外的操作,推荐我们平时这样使用网络!

好处:不同的集群使用不同的网络,保证我们的集群是安全和健康的!

思考:那么不同的集群间的隔离能否打通呢?

网络连通

docker network connect [OPTIONS] NETWORK CONTAINER

# 测试打通 tomcat01 <-> mynet
[root@mengxt ~]# docker network connect mynet tomcat01

# 连通之后就是将 tomcat01 放到 mynet 网络下
# 一个容器两个IP地址
[root@mengxt ~]# docker exec tomcat01 ping tomcat-net-01
PING tomcat-net-01 (192.168.0.2) 56(84) bytes of data.
64 bytes from tomcat-net-01.mynet (192.168.0.2): icmp_seq=1 ttl=64 time=0.073 ms
64 bytes from tomcat-net-01.mynet (192.168.0.2): icmp_seq=2 ttl=64 time=0.071 ms
[root@mengxt ~]# docker exec tomcat-net-01 ping tomcat01
PING tomcat01 (192.168.0.4) 56(84) bytes of data.
64 bytes from tomcat01.mynet (192.168.0.4): icmp_seq=1 ttl=64 time=0.055 ms
64 bytes from tomcat01.mynet (192.168.0.4): icmp_seq=2 ttl=64 time=0.067 ms
64 bytes from tomcat01.mynet (192.168.0.4): icmp_seq=3 ttl=64 time=0.078 ms

# tomcat02 是依旧打不通的
[root@mengxt ~]# docker exec tomcat02 ping tomcat-net-01
ping: tomcat-net-01: Name or service not known

结论:假设要跨网络操作别人,就需要使用 docker network connect 来连通

实战:部署Redis集群

# 自定义 redis 集群的网络
[root@mengxt ~]# docker network create redis --subnet 172.38.0.0/16
9f93e6c6b628aa5e348a595287026ece39047d758455d3deb9e6c2d6d3ae1743
[root@mengxt ~]# docker network ls
NETWORK ID     NAME     DRIVER   SCOPE
06d798af96d7   bridge   bridge   local
cf427638b8cb   host     host     local
d8a69ce39223   mynet     bridge   local
7cf16a76b8eb   none     null     local
9f93e6c6b628   redis     bridge   local

# 通过脚本创建六个redis配置
for n in $(seq 1 6); do
mkdir -p /mydata/redis/node-${n}/conf
touch /mydata/redis/node-${n}/conf/redis.conf
cat << EOF > /mydata/redis/node-${n}/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${n}
cluster-announce-port 6379
cluster-announce-bus-port 16379
appendonly yes
EOF
done

docker run -p 637${n}:6379 -p 1637${n}:16379 --name redis-${n} \
-v /mydata/redis/node-${n}/data:/data \
-v /mydata/redis/node-${n}/conf/redis.conf:/etc/redis/redis.conf \
-d --net redis --ip 172.38.0.1${n} redis:5.0.9-alpine3.11 redis-server /etc/redis/redis.conf

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

# 创建完毕
[root@mengxt ~]# docker ps -a
CONTAINER ID   IMAGE                   COMMAND                 CREATED             STATUS             PORTS                                             NAMES
5a93260eb054   redis:5.0.9-alpine3.11   "docker-entrypoint.s…"   3 seconds ago       Up 2 seconds        0.0.0.0:6376->6379/tcp, 0.0.0.0:16376->16379/tcp   redis-6
f720dd893d73   redis:5.0.9-alpine3.11   "docker-entrypoint.s…"   40 seconds ago       Up 39 seconds       0.0.0.0:6375->6379/tcp, 0.0.0.0:16375->16379/tcp   redis-5
06cf60d940ad   redis:5.0.9-alpine3.11   "docker-entrypoint.s…"   About a minute ago   Up 59 seconds       0.0.0.0:6374->6379/tcp, 0.0.0.0:16374->16379/tcp   redis-4
5d7d1a379bdc   redis:5.0.9-alpine3.11   "docker-entrypoint.s…"   About a minute ago   Up About a minute   0.0.0.0:6373->6379/tcp, 0.0.0.0:16373->16379/tcp   redis-3
2b642fe563c8   redis:5.0.9-alpine3.11   "docker-entrypoint.s…"   2 minutes ago       Up 2 minutes        0.0.0.0:6372->6379/tcp, 0.0.0.0:16372->16379/tcp   redis-2
10ad91bb005f   redis:5.0.9-alpine3.11   "docker-entrypoint.s…"   2 minutes ago       Up 2 minutes        0.0.0.0:6371->6379/tcp, 0.0.0.0:16371->16379/tcp   redis-1
[root@mengxt ~]#

# 进入redis容器
[root@mengxt ~]# docker exec -it redis-1 /bin/sh

# 创建集群
/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: 25d8d704cb0e821671486827cca758ff5bc4be61 172.38.0.11:6379
  slots:[0-5460] (5461 slots) master
M: cdcbb5e3c8cf4b0e927f00133d389453b64eba13 172.38.0.12:6379
  slots:[5461-10922] (5462 slots) master
M: b1a71dd5e44e1d69581be20ff35898bdf5d8e947 172.38.0.13:6379
  slots:[10923-16383] (5461 slots) master
S: 439fad3316ecb9444c8ef8dbf03a71aee730db8e 172.38.0.14:6379
  replicates b1a71dd5e44e1d69581be20ff35898bdf5d8e947
S: 5b64cfad480b38a692a4b63c483c1cd992a113ce 172.38.0.15:6379
  replicates 25d8d704cb0e821671486827cca758ff5bc4be61
S: 3aba24a41180f06a3cd84052932cd23243a09fb4 172.38.0.16:6379
  replicates cdcbb5e3c8cf4b0e927f00133d389453b64eba13
Can I set the above configuration? (type 'yes' to accept):

docker搭建redis集群完毕!

IDEA整合Docker

1、创建springboot项目

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

   public static void main(String[] args) {
       SpringApplication.run(DemoApplication.class, args);
  }

}

2、打包应用

3、编写dockerfile

FROM java:8

COPY *.jar /app.jar

CMD ["--server.port=8080"]

EXPOSE 8080

ENTRYPOINT ["java","-jar","/app.jar"]

4、构建镜像

[root@mengxt idea]# docker build -t springboot-demo .
Sending build context to Docker daemon  17.07MB
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
---> d854f4725a55
Step 3/5 : CMD ["--server.port=8080"]
---> Running in 713207b409e7
Removing intermediate container 713207b409e7
---> d207b0305bd5
Step 4/5 : EXPOSE 8080
---> Running in 8353ff648a62
Removing intermediate container 8353ff648a62
---> fbe238c02a0a
Step 5/5 : ENTRYPOINT ["java","-jar","/app.jar"]
---> Running in 0b8c9bded080
Removing intermediate container 0b8c9bded080
---> 712662caae31
Successfully built 712662caae31
Successfully tagged springboot-demo:latest
[root@mengxt idea]# docker images
REPOSITORY       TAG               IMAGE ID       CREATED         SIZE
springboot-demo   latest             712662caae31   8 seconds ago   660MB
tomcat           latest             040bdb29ab37   2 months ago   649MB
redis             5.0.9-alpine3.11   3661c84ee9d0   11 months ago   29.8MB
java              8                 d23bdf5b1b1b   4 years ago     643MB

5、发布运行

[root@mengxt idea]# docker run -d -P --name springboot01 springboot-demo
c10e5380964c341067e4b9511bad7d4fa15ebb5501cd4220b1f727f15fae348b
[root@mengxt idea]# docker ps
CONTAINER ID   IMAGE                   COMMAND                 CREATED             STATUS             PORTS                                             NAMES
c10e5380964c   springboot-demo          "java -jar /app.jar …"   5 seconds ago       Up 3 seconds       0.0.0.0:49153->8080/tcp                           springboot01

# 测试访问
[root@mengxt idea]# curl localhost:49153/hello
Hello,Mxt
posted @ 2021-08-26 14:04  梦玄庭  阅读(904)  评论(0编辑  收藏  举报