🎯Docker容器运行流程
🎯底层原理
Docker是怎么工作的
- Docker是一个Client-Server结构的系统,Docker的守护进程运行在主机上,通过Socket从客户端访问!
- Docker Server接收到Docker-Client的指令,就会执行这个指令!
Docker 为什么比VM快?
- Docker有着比虚拟机更少的抽象层
- docker利用的是宿主主机的内核,vm需要的是Guest OS。(搭建自己内核)
所以说,新建一个容器的时候,docker不需要像虚拟机一样重新加载一个操作系统内核,避免引导。虚拟机是加载Guest OS,分钟级别的,而docker是利用宿主主机的操作系统,省略了这个复杂的过程,妙计秒级
🎯Docker的常用命令
🎨帮助文档
docker version #查看docker的版本信息
docker info #查看docker的系统信息,包括镜像和容器的数量
docker 命令 --help #帮助命令(可查看可选的参数)
docker COMMAND --help
帮助文档的地址:https://docs.docker.com/engine/reference/commandline/
🎨镜像命令
docker images 查看所有本地主机上的镜像
[root@VM-16-15-centos ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
halohub/halo 1.5.2 064b1d04aeff 2 months ago 346MB
hello-world latest feb5d9fea6a5 8 months ago 13.3kB
#解释
REPOSITORY 镜像的仓库源
TAG 镜像的标签
IMAGE ID 镜像id
CREATED 镜像创建的时间
SIZE 镜像大小
#可选项
Options:
-a, --all #列出所有的镜像
-q, --quiet #只显示镜像的id
docker search 搜索镜像
[root@VM-16-15-centos ~]# docker search mysql
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
mysql MySQL is a widely used, open-source relation… 12714 [OK]
mariadb MariaDB Server is a high performing open sou… 4882 [OK]
percona Percona Server is a fork of the MySQL relati… 579 [OK]
#可选项
--filter=STARS=3000 #搜索出来的镜像就是STARS大于3000的
[root@VM-16-15-centos ~]# docker search mysql --filter=STARS=3000
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
mysql MySQL is a widely used, open-source relation… 12714 [OK]
mariadb MariaDB Server is a high performing open sou… 4882 [OK]
[root@VM-16-15-centos ~]# docker search mysql --filter=STARS=5000
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
mysql MySQL is a widely used, open-source relation… 12714 [OK]
docker pull下载镜像
#下载镜像 docker pull 镜像名 [:tag]
[root@VM-16-15-centos ~]# docker pull mysql
Using default tag: latest #如果不写 tag.默认就是 latest
latest: Pulling from library/mysql
72a69066d2fe: Pull complete #分层下载,docker images的核心,联合文件系统
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@VM-16-15-centos ~]# docker pull 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
docker rmi删除镜像
#1.删除指定的容器
[root@VM-16-15-centos ~]# docker rmi -f c20987f18b13(容器id)
#2.删除多个容器
[root@VM-16-15-centos ~]# docker rmi -f 容器id 容器id 容器id
#3.删除全部的容器
[root@VM-16-15-centos ~]# docker rmi -f $(docker images -aq)
🎨容器命令
说明:我们有了镜像才可以创建容器,Linux,下载一个centos镜像来测试学习
docker pull centos
新建容器并启动
docker run [可选参数] image
#参数说明
--name="名字" 指定容器名字
-d 后台方式运行
-it 使用交互方式运行,进入容器查看内容
-p 指定容器的端口
(
-p ip:主机端口:容器端口 配置主机端口映射到容器端口
-p 主机端口:容器端口
-p 容器端口
)
-P 随机指定端口(大写的P)
#测试,启动进入容器
[root@VM-16-15-centos ~]# docker run -it centos /bin/bash
[root@5fb5b6532790 /]# ls #查看容器内的centos发现和外部的一样,但是这俩个没关系(容器内部的centos是基础版本,很多命令都是不完善的)
bin dev etc home lib lib64 lost+found media mnt opt proc root run sbin srv sys tmp usr var
#从容器中退回到主机
[root@5fb5b6532790 /]# exit
exit
[root@VM-16-15-centos /]# ls
bin boot data dev etc home lib lib64 lost+found media mnt opt patch proc root run sbin srv sys tmp usr var www
列出所有运行的容器
#docker ps 命令
#列出当前正在运行的容器
-a #列出当前正在运行的容器+带出历史运行的容器
-n=? #显示最近创建的容器
-q #只显示容器的编号
[root@VM-16-15-centos /]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
73e2b5c8fc98 halohub/halo:1.5.2 "/bin/sh -c 'java -X…" 5 weeks ago Up 2 hours 0.0.0.0:8090->8090/tcp, :::8090->8090/tcp halo
[root@VM-16-15-centos /]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
5fb5b6532790 centos "/bin/bash" 4 minutes ago Exited (130) 3 minutes ago determined_bohr
8e66cb3423bd hello-world "/hello" 2 hours ago Exited (0) 2 hours ago thirsty_shamir
2a3dc17e5aaa hello-world "/hello" 13 hours ago Exited (0) 13 hours ago elegant_swartz
73e2b5c8fc98 halohub/halo:1.5.2 "/bin/sh -c 'java -X…" 5 weeks ago Up 2 hours 0.0.0.0:8090->8090/tcp, :::8090->8090/tcp halo
退出容器
exit #直接容器停止退出
Ctrl + P + Q #容器不停止退出
删除容器
docker rm 容器id #删除指定的容器,不能删除正在运行的容器,如果要强制删除 rm -f
docker rm -f $(docker ps -aq) #删除所有的容器
docker ps -a -q | xargs docker rm #删除所有的容器
启动和停止容器的操作
docker start 容器id #启动容器
docker restart 容器id #重启容器
docker stop 容器id #停止当前正在运行的容器
docker kill 容器id #强制停止当前的容器
🎨常用其他命令
后台启动容器
# 命令 docker run -d 镜像名!
[root@VM-16-15-centos /]# docker run -d centos
#问题docker ps,发现 centos停止了
# 常见的坑,docker 容器使用后台运行,就必须要有一个前台进程,docker发现没有应用,就会自定停止
# nginx,容器启动后,发现自己没有提供服务,就会立刻停止,就是没有程序了
查看日志
[root@VM-16-15-centos /]# docker logs --help
Usage: docker logs [OPTIONS] CONTAINER
Fetch the logs of a container
Options:
--details Show extra details provided to logs
-f, --follow Follow log output
--since string Show logs since timestamp (e.g. 2013-01-02T13:23:37Z) or relative (e.g. 42m for 42 minutes)
-n, --tail string Number of lines to show from the end of the logs (default "all")
-t, --timestamps Show timestamps
--until string Show logs before a timestamp (e.g. 2013-01-02T13:23:37Z) or relative (e.g. 42m for 42 minutes)
#自己写一段shell脚本
[root@VM-16-15-centos /]# docker run -d centos /bin/sh -c "while true;do echo dainaiao;sleep 5;done"
[root@VM-16-15-centos /]# docker ps
CONTAINER ID IMAGE
0572cf30f11a centos
# 显示日志
docker logs -tf 容器id #全部日志
docker logs --tail number 容器id #num为要显示的日志条数
[root@VM-16-15-centos /]# docker logs -ft --tail 10 0572cf30f11a
2022-06-12T03:20:58.021575099Z dainaiao
2022-06-12T03:21:03.023374038Z dainaiao
2022-06-12T03:21:08.025159460Z dainaiao
2022-06-12T03:21:13.026943187Z dainaiao
2022-06-12T03:21:18.028730554Z dainaiao
2022-06-12T03:21:23.030516778Z dainaiao
2022-06-12T03:21:28.032287142Z dainaiao
2022-06-12T03:21:33.034048941Z dainaiao
2022-06-12T03:21:38.035825824Z dainaiao
2022-06-12T03:21:43.037605728Z dainaiao
2022-06-12T03:21:48.039459087Z dainaiao
查看容器中进程信息
#命令 docker top 容器id
[root@VM-16-15-centos /]# docker top 0572cf30f11a
UID PID PPID C STIME TTY TIME CMD
root 2187347 2187328 0
root 2189996 2187347 0
查看镜像的元数据
#命令
docker inspect 容器id
#测试
[root@VM-16-15-centos /]# docker inspect 0572cf30f11a
[
{
"Id": "0572cf30f11adb69a119461d014f581401e1b98cac4f8ca742745d040fa4943a",
"Created": "2022-06-12T03:14:07.52903823Z",
"Path": "/bin/sh",
"Args": [
"-c",
"while true;do echo dainaiao;sleep 5;done"
],
"State": {
"Status": "running",
"Running": true,
"Paused": false,
"Restarting": false,
"OOMKilled": false,
"Dead": false,
"Pid": 2187347,
"ExitCode": 0,
"Error": "",
"StartedAt": "2022-06-12T03:14:07.873248642Z",
"FinishedAt": "0001-01-01T00:00:00Z"
},
"Image": "sha256:5d0da3dc976460b72c77d94c8a1ad043720b0416bfc16c52c45d4847e53fadb6",
"ResolvConfPath": "/www/server/docker/containers/0572cf30f11adb69a119461d014f581401e1b98cac4f8ca742745d040fa4943a/resolv.conf",
"HostnamePath": "/www/server/docker/containers/0572cf30f11adb69a119461d014f581401e1b98cac4f8ca742745d040fa4943a/hostname",
"HostsPath": "/www/server/docker/containers/0572cf30f11adb69a119461d014f581401e1b98cac4f8ca742745d040fa4943a/hosts",
"LogPath": "/www/server/docker/containers/0572cf30f11adb69a119461d014f581401e1b98cac4f8ca742745d040fa4943a/0572cf30f11adb69a119461d014f581401e1b98cac4f8ca742745d040fa4943a-json.log",
"Name": "/zen_heisenberg",
"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": "/www/server/docker/overlay2/524be4a9c5c2cd87829a2badde52d66b4e6db3da085da2a641f2413d64b7ce80-init/diff:/www/server/docker/overlay2/f7c85e20f350b421fc13648e756c65211468b872c65dc5798f543117776603be/diff",
"MergedDir": "/www/server/docker/overlay2/524be4a9c5c2cd87829a2badde52d66b4e6db3da085da2a641f2413d64b7ce80/merged",
"UpperDir": "/www/server/docker/overlay2/524be4a9c5c2cd87829a2badde52d66b4e6db3da085da2a641f2413d64b7ce80/diff",
"WorkDir": "/www/server/docker/overlay2/524be4a9c5c2cd87829a2badde52d66b4e6db3da085da2a641f2413d64b7ce80/work"
},
"Name": "overlay2"
},
"Mounts": [],
"Config": {
"Hostname": "0572cf30f11a",
"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 dainaiao;sleep 5;done"
],
"Image": "centos",
"Volumes": null,
"WorkingDir": "",
"Entrypoint": null,
"OnBuild": null,
"Labels": {
"org.label-schema.build-date": "20210915",
"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": "33bc49cef421574a5280bbb5ab869edd9034ce5ed53eb28d3b12bac200fb40a8",
"HairpinMode": false,
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"Ports": {},
"SandboxKey": "/var/run/docker/netns/33bc49cef421",
"SecondaryIPAddresses": null,
"SecondaryIPv6Addresses": null,
"EndpointID": "f3505927d7a924a9aa7e00d4958a902786630c50b4e1b8e8ead7355865ed078a",
"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": "107cf7cbdfd63636e0c5f2d611b945c9d45e5a5ab48363afa591a41228571913",
"EndpointID": "f3505927d7a924a9aa7e00d4958a902786630c50b4e1b8e8ead7355865ed078a",
"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
}
}
}
}
]
进入当前正在运行的容器
因为通常我们的容器都是使用后台方式来运行的,有时需要进入容器修改配置
- 方式1
#命令
docker exec -it 容器id bashshell
#测试
[root@VM-16-15-centos ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
0572cf30f11a centos "/bin/sh -c 'while t…" 4 hours ago Up 4 hours zen_heisenberg
[root@VM-16-15-centos ~]# docker exec -it 0572cf30f11a /bin/bash
[root@0572cf30f11a /]# ls
bin dev etc home lib lib64 lost+found media mnt opt proc root run sbin srv sys tmp usr var
[root@0572cf30f11a /]# ps -ef
UID PID PPID C STIME TTY TIME CMD
root 1 0 0 03:14 ? 00:00:00 /bin/sh -c while true;do echo dainaiao;sleep 5;done
root 2715 0 0 06:59 pts/0 00:00:00 /bin/bash
root 2731 1 0 06:59 ? 00:00:00 /usr/bin/coreutils --coreutils-prog-shebang=sleep /usr/bin/sleep 5
root 2732 2715 0 06:59 pts/0 00:00:00 ps -ef
- 方式2
docker attach 容器id
#测试
[root@VM-16-15-centos ~]# docker attach 0572cf30f11a
正在执行当前的代码...
# docker exec #进入容器后开启一个新的容器,可以在里面操作(常用)
# docker attach #进入容器正在执行的终端,不会启动新的进程!
拷贝操作
#拷贝容器的文件到主机中
docker cp 容器id:容器内路径 目的主机路径
#拷贝宿主机的文件到容器中
docker cp 目的主机路径 容器id:容器内路径
#查看当前主机目录下
[root@VM-16-15-centos home]# ls
dainiao.java lighthouse www
#进入docker容器内部
[root@VM-16-15-centos home]# docker attach 89a99696cd86
[root@89a99696cd86 /]# cd /home
#在容器内创创建一个文件
[root@89a99696cd86 home]# touch test.java
#退出容器
[root@89a99696cd86 home]# exit
exit
[root@VM-16-15-centos home]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
[root@VM-16-15-centos home]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
89a99696cd86 centos "/bin/bash" 2 minutes ago Exited (0) 10 seconds ago cranky_aryabhata
#将文件从容器中拷贝到主机上
[root@VM-16-15-centos home]# docker cp 89a99696cd86:/home/test.java /home
[root@VM-16-15-centos home]# ls
dainiao.java lighthouse test.java www
#拷贝是一个手动过程,未来我们使用 -v 卷的技术,可以实现自动同步(将主机的home和容器的home联系在一起)
🎯小结
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 from the containers filesystem to the host path #从容器中拷贝指定文件或者目录到宿主机中
create Create a new container # 创建一个新的容器,同 run,但不启动容器
diff Inspect changes on a container's filesystem # 查看 docker 容器变化
events Get real time events from the server # 从 docker 服务获取容器实时事件
exec Run a command in an existing container # 在已存在的容器上运行命令
export Stream the contents of a container as a tar archive # 导出容器的内容流作为一个 tar 归档文件[对应 import ]
history Show the history of an image # 展示一个镜像形成历史
images List images # 列出系统当前镜像
import Create a new filesystem image from the contents of a tarball # 从tar包中的内容创建一个新的文件系统映像[对应export]
info Display system-wide information # 显示系统相关信息
inspect Return low-level information on a container # 查看容器详细信息
kill Kill a running container # kill 指定 docker 容器
load Load an image from a tar archive # 从一个 tar 包中加载一个镜像[对应 save]
login Register or Login to the docker registry server # 注册或者登陆一个 docker 源服务器
logout Log out from a Docker registry server # 从当前 Docker registry 退出
logs Fetch the logs of a container # 输出当前容器日志信息
port Lookup the public-facing port which is NAT-ed to PRIVATE_PORT # 查看映射端口对应的容器内部源端口
pause Pause all processes within a container # 暂停容器
ps List containers # 列出容器列表
pull Pull an image or a repository from the docker registry server # 从docker镜像源服务器拉取指定镜像或者库镜像
push Push an image or a repository to the docker registry server # 推送指定镜像或者库镜像至docker源服务器
restart Restart a running container # 重启运行的容器
rm Remove one or more containers # 移除一个或者多个容器
rmi Remove one or more images # 移除一个或多个镜像[无容器使用该镜像才可删除,否则需删除相关容器才可继续或 -f 强制删除]
run Run a command in a new container # 创建一个新的容器并运行一个命令
save Save an image to a tar archive # 保存一个镜像为一个 tar 包[对应 load]
search Search for an image on the Docker Hub # 在 docker hub 中搜索镜像
start Start a stopped containers # 启动容器
stop Stop a running containers # 停止容器
tag Tag an image into a repository # 给源中镜像打标签
top Lookup the running processes of a container # 查看容器中运行的进程信息
unpause Unpause a paused container # 取消暂停容器
version Show the docker version information # 查看 docker 版本号
wait Block until a container stops, then print its exit code # 截取容器停止时的退出状态值