3-Docker容器架构介绍
3-Docker容器架构介绍
Docker 核心组件
Docker 的核心组件包括:
-
Docker 客户端 - Client
-
Docker 服务器 - Docker daemon
-
Docker 镜像 - Image
-
Registry 仓库
-
Docker 容器 - Container
Docker 采用的是 Client/Server 架构 户端和服务器可以运行在同一个 Host 上,客户端也可以通过 socket 或 REST API 与远程的服务器通信
Docker客户端
最常用的 Docker 客户端是 docker 命令
#docker docker支持很多子命令
docker服务器
Docker daemon 是服务器组件,以 Linux 后台服务的方式运行。
Docker daemon 运行在 Docker host 上,负责创建、运行、监控容器,构建、存储镜像。
Docker daemon 默认只能响应来自本地 Host 的客户端请求。如果要允许远程客户端请求,需要在配置文件中打开 TCP 监听
vim /etc/systemd/system/multi-user.target.wants/docker.service
ExecStart=/usr/bin/dockerd -H fd:// -H tcp://0.0.0.0
添加 -H tcp://0.0.0.0,允许来自任意 IP 的客户端连接。
配置完成需要重启docker-daemon
systemctl daemon-reload
docker -H 192.168.47.20 info # 其他主机可以通过-H docker主机查看docker信息
docker镜像
可将 Docker 镜像看着只读模板,通过它可以创建 Docker 容器。镜像有多种生成方法:
-
可以从无到有开始创建镜像
-
也可以下载并使用别人创建好的现成的镜像
-
还可以在现有镜像上创建新的镜像
将镜像的内容和创建步骤描述在一个文本文件中,这个文件被称作 Dockerfile
通过执行 docker build
docker容器
Docker 容器就是 Docker 镜像的运行实例。
用户可以通过 CLI(docker)或是 API 启动、停止、移动或删除容器。
Registry 是存放 Docker 镜像的仓库,Registry 分私有和公有两种
Docker Hub(https://hub.docker.com/) 是默认的 Registry
用户也可以创建自己的私有 Registry
docker pull 命令可以从 Registry 下载镜像。
docker run 命令则是先下载镜像(如果本地没有),然后再启动容器。
容器的启动过程
Docker 客户端执行 docker run 命令。
Docker daemon 发现本地没有 httpd 镜像
daemon 从 Docker Hub 下载镜像。
下载完成,镜像 httpd 被保存到本地。
Docker daemon 启动容器。
docker images 可以查看到 httpd 已经下载到本地
docker ps 或者 docker container ls 显示容器正在运行。
docker常用命令
帮助命令
docker version # docker版本信息
docker info # 系统级别的信息,包括镜像和容器的数量 信息量全面
docker 命令 --help
https://docs.docker.com/engine/reference/commandline/docker/ #dockers帮助文档
镜像命令
docker images #查看当前所有镜像
[root@MyMachine ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
datapackted latest b83d5b8062b2 2 days ago 1.24MB
# 解释
REPOSITORY # 镜像的仓库
TAG # 镜像的标签
IMAGE ID # 镜像的ID
CREATED # 镜像的创建时间
SIZE # 镜像的大小
# 可选项
--all , -a # 列出所有镜像
--quiet , -q # 只显示镜像的id
docker search 查找镜像
docker search
# 可选项
--filter=STARS=3000 # 搜素出来的镜像就是STARS大于3000
[root@MyMachine ~]# docker search httpd --filter=STARS=3000
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
httpd The Apache HTTP Server Project 4001 [OK]
[root@localhost /]# docker search mysql
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
mysql MySQL is a widely used, open-source relation… 9604 [OK]
mariadb MariaDB is a community-developed fork of MyS… 3490 [OK]
#可选项,通过收藏来过滤
--filter=STARS=3000 #搜索出来的镜像就是STARS大于3000的
[root@localhost /]# docker search mysql --filter=STARS=3000
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
mysql MySQL is a widely used, open-source relation… 9604 [OK]
mariadb MariaDB is a community-developed fork of MyS… 3490 [OK]
docker pull 下拉镜像
[root@MyMachine ~]# docker pull mysql
Using default tag: latest # 如果不写tag,默认就是latest
latest: Pulling from library/mysql
c32ce6654453: Pull complete
415d08ee031a: Pull complete
7a38fec2542f: Pull complete
352881ee8fe9: Pull complete
b8e20da291b6: Pull complete
66c2a8cc1999: Pull complete
d3a3a8e49878: Pull complete
e33a48832bec: Pull complete
410b942b8b28: Pull complete
d5323c9dd265: Pull complete
3212737f31c0: Pull complete
d0032d4b0dc5: Pull complete #分层下拉
Digest: sha256:a0805d37d4d298bd61e0dfa61f0ddf6f4680b453fa25d7aad420485a62417eab
Status: Downloaded newer image for mysql:latest
docker.io/library/mysql:latest # 真实下拉地址
等价于
# docker pull docker.io/library/mysql:latest
# 指定版本下载
[root@localhost /]# docker pull mysql:5.7
5.7: Pulling from library/mysql
8559a31e96f4: Already exists # 联合文件系统的好处:上面下载过的MySQL与5.7版本的MySQL有相同的文件时不需要重复下载
d51ce1c2e575: Already exists
c2344adc4858: Already exists
fcf3ceff18fc: Already exists
16da0c38dc5b: Already exists
b905d1797e97: Already exists
4b50d1c6b05c: Already exists
d85174a87144: Pull complete
a4ad33703fa8: Pull complete
f7a5433ce20d: Pull complete
3dcd2a278b4a: Pull complete
Digest: sha256:32f9d9a069f7a735e28fd44ea944d53c61f990ba71460c5c183e610854ca4854
Status: Downloaded newer image for mysql:5.7
docker.io/library/mysql:5.7
https://hub.docker.com/ 官方查询支持的版本
docker rmi 删除镜像
# docker rmi -f IMAGE ID # 删除指定镜像
# docker rmi -f IMAGE ID1 IMAGE ID2 IMAGE ID3 # 删除多个镜像
# docker rmi -f $(docker images -aq) # 删除所有镜像 $()里面定义一个变量
[root@MyMachine ~]# docker images --help
Usage: docker images [OPTIONS] [REPOSITORY[:TAG]]
List images
Options:
-a, --all Show all images (default hides -a表示所有images
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 #只显示iamges ID
容器命令
docker run [可选参数] image
# 参数说明 run参数很多 下面写的是常用的参数
--name=“Name” 容器名字 tomcat01 tomcat02 用来区分容器
-d 后台方式运行
-it 使用交互方式运行,进入容器查看内容
-p 指定容器的端口 -p 8080:8080
-p ip:主机(即宿主机)端口:容器端口
-p 主机端口:容器端口 #这种方式常用
-p 容器端口 宿主机端口随机
容器端口
-p 随机指定端口 随机指定端口(大写P)
# 测试,启动并进入容器
[root@MyMachine ~]# docker run -it centos /bin/bash
[root@89c53adc6892 /]# exit # 从容器中退回主机
exit
列出所有容器
# docker ps 命令
# 列出当前正在运行的容器
-a # 列出正在运行的容器包括历史容器
-n=? # 显示最近创建的容器
-q # 只显示当前容器
[root@MyMachine ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
[root@MyMachine ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
89c53adc6892 centos "/bin/bash" 2 minutes ago Exited (127) 10 seconds ago
[root@MyMachine ~]# docker ps -qa
89c53adc6892
退出容器
exit # 直接退出容器并关闭
Ctrl + P + Q # 容器不关闭 退出容器命令交互窗口
删除容器
docker rm -f 容器id # 删除指定容器
docker rm -f $(docker ps -aq) # 删除所有容器
docker ps -a -q|xargs docker rm -f # 删除所有的容器
启动和停止容器的操作
docker start 容器id # 启动容器
docker restart 容器id # 重启容器
docker stop 容器id # 停止当前正在运行的容器
docker kill 容器id # 强制停止当前的容器
后台启动容器
# 命令 docker run -d 镜像名
[root@iZ2zeg4ytp0whqtmxbsqiiZ /]# docker run -d centos
# 常见的问题, docker 容器使用后台运行, 就必须要有一个前台进程,docker发现没有应用,就会自动停止
# nginx, 容器启动后,发现自己没有提供服务,就会立即停止,就是没有程序了
查看日志
docker logs -tf --tail $number 容器id
[root@iZ2zeg4ytp0whqtmxbsqiiZ /]# docker logs -tf --tail 1 8d1621e09bff
2020-08-11T10:53:15.987702897Z [root@8d1621e09bff /]# exit # 日志输出
-tf # 显示日志
--tail # 要显示的日志条数
# 自己编写一段shell脚本
[root@iZ2zeg4ytp0whqtmxbsqiiZ /]# docker run -d centos /bin/sh -c "while true;do echo xiaofan;sleep 1;done"
a0d580a21251da97bc050763cf2d5692a455c228fa2a711c3609872008e654c2
[root@iZ2zeg4ytp0whqtmxbsqiiZ /]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
a0d580a21251 centos "/bin/sh -c 'while t…" 3 seconds ago Up 1 second lucid_black
# 显示日志
-tf # 显示日志
--tail number # 显示日志条数
[root@MyMachine ~]# docker logs -tf --tail 1 dfd2dc8237a7
2022-05-12T03:22:45.729943251Z [Thu May 12 03:22:45.724895 2022] [core:notice] [pid 1:tid 140652547099968] AH00094: Command line: 'httpd -D FOREGROUND'
查看容器中进程信息ps
# 命令 docker top 容器id
[root@MyMachine ~]# docker top dfd2dc8237a7
UID PID PPID C STIME TTY TIME CMD
root 4481 4462 0 11:22 ?
查看镜像的元数据
# 命令
docker inspect 容器id
[root@MyMachine ~]# docker inspect dfd2dc8237a7
[
{
"Id": "dfd2dc8237a72ac6340f3007731573f9a570b2bdc26066641287d4474a56af83",
"Created": "2022-05-12T03:22:44.871395679Z",
"Path": "httpd-foreground",
"Args": [],
"State": {
"Status": "running",
"Running": true,
"Paused": false,
"Restarting": false,
"OOMKilled": false,
"Dead": false,
"Pid": 4481,
"ExitCode": 0,
"Error": "",
"StartedAt": "2022-05-12T03:22:45.681444547Z",
"FinishedAt": "0001-01-01T00:00:00Z"
},
"Image": "sha256:c30a467716957ab3adabf990785d220056949d80b3aa46d90de3ea44d532b03e",
"ResolvConfPath": "/var/lib/docker/containers/dfd2dc8237a72ac6340f3007731573f9a570b2bdc26066641287d4474a56af83/resolv.conf",
"HostnamePath": "/var/lib/docker/containers/dfd2dc8237a72ac6340f3007731573f9a570b2bdc26066641287d4474a56af83/hostname",
"HostsPath": "/var/lib/docker/containers/dfd2dc8237a72ac6340f3007731573f9a570b2bdc26066641287d4474a56af83/hosts",
"LogPath": "/var/lib/docker/containers/dfd2dc8237a72ac6340f3007731573f9a570b2bdc26066641287d4474a56af83/dfd2dc8237a72ac6340f3007731573f9a570b2bdc26066641287d4474a56af83-json.log",
"Name": "/blissful_newton",
"RestartCount": 0,
"Driver": "overlay2",
"Platform": "linux",
"MountLabel": "",
"ProcessLabel": "",
"AppArmorProfile": "",
"ExecIDs": null,
"HostConfig": {
"Binds": null,
"ContainerIDFile": "",
"LogConfig": {
"Type": "json-file",
"Config": {
"max-file": "1",
"max-size": "10m"
}
},
"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/0ca2828e2f66a2e06c4cd21d234163d5d71cd431fb4dd92a2267788119d5d8e8-init/diff:/var/lib/docker/overlay2/5f14cdd7919f27cd523d120051a17f460cb503e2e5ca9d01adca355defe8593b/diff:/var/lib/docker/overlay2/76311b75e2c46f961cd3bc19e826cdbd705e36444f219ba6a8b352cc1b2cabdf/diff:/var/lib/docker/overlay2/d87840bfa61f97dc0e7adf59b5d574e849587044d577c1e5dfaed8b8d3c0ecde/diff:/var/lib/docker/overlay2/c3afbe6e043ff9383a9b98a7efc76756ecf8c9d658f2805f5bc9680c8a89118d/diff:/var/lib/docker/overlay2/c6581d6a606875bacbada969da7b35575ddd99ca490a308e7cd922d76b6774ee/diff",
"MergedDir": "/var/lib/docker/overlay2/0ca2828e2f66a2e06c4cd21d234163d5d71cd431fb4dd92a2267788119d5d8e8/merged",
"UpperDir": "/var/lib/docker/overlay2/0ca2828e2f66a2e06c4cd21d234163d5d71cd431fb4dd92a2267788119d5d8e8/diff",
"WorkDir": "/var/lib/docker/overlay2/0ca2828e2f66a2e06c4cd21d234163d5d71cd431fb4dd92a2267788119d5d8e8/work"
},
"Name": "overlay2"
},
"Mounts": [],
"Config": {
"Hostname": "dfd2dc8237a7",
"Domainname": "",
"User": "",
"AttachStdin": false,
"AttachStdout": false,
"AttachStderr": false,
"ExposedPorts": {
"80/tcp": {}
},
"Tty": false,
"OpenStdin": false,
"StdinOnce": false,
"Env": [
"PATH=/usr/local/apache2/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"HTTPD_PREFIX=/usr/local/apache2",
"HTTPD_VERSION=2.4.53",
"HTTPD_SHA256=d0bbd1121a57b5f2a6ff92d7b96f8050c5a45d3f14db118f64979d525858db63",
"HTTPD_PATCHES="
],
"Cmd": [
"httpd-foreground"
],
"Image": "httpd",
"Volumes": null,
"WorkingDir": "/usr/local/apache2",
"Entrypoint": null,
"OnBuild": null,
"Labels": {},
"StopSignal": "SIGWINCH"
},
"NetworkSettings": {
"Bridge": "",
"SandboxID": "227d93f28711e5e028f48011787f7d8508771c89aefc51e48876f3a998e7b16a",
"HairpinMode": false,
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"Ports": {
"80/tcp": null
},
"SandboxKey": "/var/run/docker/netns/227d93f28711",
"SecondaryIPAddresses": null,
"SecondaryIPv6Addresses": null,
"EndpointID": "574075e03ad6c90abaede332d2789d84153dc9bb03353f10a7bfb8ef4d074552",
"Gateway": "172.17.0.1",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"IPAddress": "172.17.0.3",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"MacAddress": "02:42:ac:11:00:03",
"Networks": {
"bridge": {
"IPAMConfig": null,
"Links": null,
"Aliases": null,
"NetworkID": "1ffb77a7dee5a0521cda71d577c5f56f011ff8f4984493380f5348a29d36cfc8",
"EndpointID": "574075e03ad6c90abaede332d2789d84153dc9bb03353f10a7bfb8ef4d074552",
"Gateway": "172.17.0.1",
"IPAddress": "172.17.0.3",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"MacAddress": "02:42:ac:11:00:03",
"DriverOpts": null
}
}
}
}
]
[root@MyMachine ~]#
进入当前正在运行的容器
# 我们通常容器使用后台方式运行的, 需要进入容器,修改一些配置
# 命令
docker exec -it 容器id /bin/bash
# 测试
[root@MyMachine ~]# docker exec -it dfd2dc8237a7 /bin/bash
root@dfd2dc8237a7:/usr/local/apache2# ls
bin build cgi-bin conf error htdocs icons include logs modules
root@dfd2dc8237a7:/usr/local/apache2#
# 方式二
docker attach 容器id
# docker exec # 进入容器后开启一个新的终端,可以在里面操作
# docker attach # 进入容器正在执行的终端,不会启动新的进程 如果终端没有执行的进程进去是没有东西的
[root@MyMachine ~]# docker run -d --name topdemo ubuntu /usr/bin/top -b
99ef4cd5083a2f6a88a933aed70f908a9fdb62b3d6a03007e4fe9c84d8755df9
[root@MyMachine ~]# docker attach topdemo #进入容器正在执行的终端
显示的就是top -b的界面
top - 06:27:58 up 5:41, 0 users, load average: 0.27, 0.09, 0.07
Tasks: 1 total, 1 running, 0 sleeping, 0 stopped, 0 zombie
%Cpu(s): 1.3 us, 1.0 sy, 0.0 ni, 97.7 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
MiB Mem : 1819.3 total, 264.3 free, 321.5 used, 1233.5 buff/cache
MiB Swap: 3968.0 total, 3968.0 free, 0.0 used. 1327.9 avail Mem
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
1 root 20 0 7164 1720 1268 R 0.0 0.1 0:00.07 to
从容器中拷贝文件到主机
docker cp 容器id:容器内路径 目的地主机路径
[root@MyMachine ~]# docker run -d --name copydemo ubuntu /usr/bin/touch test
550cd1904f715e78460251cd176aa195d3daf6cca157f668d1692c944a17a731
[root@MyMachine ~]# docker cp copydemo:/test /home#把容器内的test拷贝到宿主机/home下
[root@MyMachine ~]# ls /home
test user
[root@MyMachine ~]#
attach Attach to a running container # 当前shell下attach连接指定运行的镜像
build Build an image from a Dockerfile # 通过Dockerfile定制镜像
commit Create a new image from a container 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 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 # 杀死指定的docker容器
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 registry退出
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 # 给docker容器重新命名
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 # 更新一个或多个容器配置
version Show the Docker version information # 查看docker版本号
wait Block until one or more containers stop, then print their exit codes # 截取容器停止时的退出状态值