Docker的RUN流程和Docker原理
Run流程
我们在上一篇博客用到了Docker run命令,那么Docker的run流程是怎么样的呢?我们看下面这张图:
底层原理
Docker是怎么工作的
Docker是一个CS结构,Docker的守护进程运行在主机上,通过Socket从客户端进行访问!
DockerServer接收到DockerClient的指令,就会执行这个命令
我们看图,我们的linux服务器上面可以有一个后台守护进程,客户端访问服务器通过守护进程进行访问,然后通过命令来找到对应的Docker容器,这些容器可以看出是独立的简单Linux系统,有单独的端口号,互相隔离、互不影响。
Docker为什么比VM快
- Docker比虚拟机有更少的抽象层
- Docker利用的是宿主机的内核,而VM需要Guest OS,所以新建一个容器的时候,docker不需要像虚拟机一样重新加载一个操作系统的内核。虚拟机是加载Guest OS,分钟级别的,而docker是利用宿主机的操作系统,省略了复杂过程,是一个秒级别
Docker的常用命令
帮助命令
docker version 显示docker的版本信息
docker info 显示docker更加详细的信息,包括镜像信息
docker 命令 --help 帮助命令
帮助文档的地址:https://docs.docker.com/reference/
镜像命令
查看镜像
docker images
查看所有本地主机上的镜像
(仓库源) (版本标签信息) (镜像ID) (镜像创建时间)
REPOSITORY TAG IMAGE ID CREATED SIZE(镜像大小)
hello-world latest feb5d9fea6a5 7 months ago 13.3kB
其次你可以在后面带后缀
Options: (列出所有镜像)
-a, --all Show all images (default hides intermediate images)
--digests Show digests
-f, --filter filter Filter output based on conditions provided
--format string Pretty-print images using a Go template
--no-trunc Don't truncate output
-q, --quiet Only show image IDs
-a, --all #列出所有镜像
-q, --quiet #只显示镜像的id
搜索镜像
docker search #搜索镜像
比如说你要搜索mysql
你就可以使用命令docker search mysql
追加参数
--filter=STARS=3000 #搜索出来的镜像就是收藏大于3000的
下载镜像
docker pull 镜像名字
加上版本号:
docker pull 镜像名字[: tag]
例子:
root@taobotics:~# docker pull mysql
Using default tag: latest #如果不写版本号,默认是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
指定版本下载
前提:必须是Docker Hub上有的版本才可以下载
docker pull mysql:5.7
一旦有相同的文件它就会自动跳过,只下载没有的文件
删除镜像
docker rmi 镜像名字
docker rmi id #根据id删除
docker rmi -f $(docker images -aq) #删除所有镜像
也可以通过空格删除多个容器。
容器命令
注意:我们只有下载了镜像之后才可以创建容器。
我们下载一个centos镜像来进行测试学习,使用如下命令:
docker pull centos
新建容器并启动
docker run [可选参数] image
参数说明:
--name=“Name” # 容器名字 tomcat01 tomcat02 用来区分容器
-d # 后台方式运行
-it #使用交互方式运行,进入容器查看内容
-p #指定容器端口 -p 8080:8080
-p主机端口:容器端口
-p容器端口
-P #随机指定端口
我们使用命令启动并进入容器:
我们使用交互方式运行,用bash来进行交互
docker run -it centos /bin/bash
这里的主机名就是我们的镜像ID,我们查看容器内的东西
我们发现,它就是一个小型的服务器,它跟我们的服务器没有任何关系
退出容器,回到主机
exit #直接容器停止并退出
Ctrl+P+Q #容器不停止并退出
列出所有运行中的容器
docker ps
我们可以附加参数
-a # 列出当前正在运行的容器+曾经运行过的容器信息
-n=? # 显示最近创建的容器 问号后面加数字,表示显示的个数
-q #只显示容器的编号
删除容器
docker rm 容器id #根据容器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 镜像名
问题:使用docker ps
命令发现centos停止了
docker容器使用后台运行,就必须要有一个前台进程,容器发现没有应用了,没有提供服务,它就会自动停止。
所以你可以使用docker run -d -it 镜像名 /bin/bash
,我们使用bash来进入交互界面,这样就有一个前台进程了。
查看日志
docker logs -f -t --tail 容器id
我们发现容器中没有日志,那么我们自己手动编写一段日志
我们使用shell脚本
“while true;do echo caicai;sleep 1;done”
我们使用命令:
docker run -d centos /bin/sh -c "while true;do echo caicai;sleep 1;done"
显示日志:
-tf #显示所有日志信息
--tail num #显示要显示的日志条数
查看容器中的进程信息
docker top
查看镜像的元数据(非常重要)
docker inspect 容器id
root@taobotics:~# docker inspect 5583e80d6f3c
[
{
"Id": "5583e80d6f3c454f3c819757d5b25af5e85abd233adcea8a95d680d485efaec6",
"Created": "2022-05-12T09:48:35.545930868Z",
"Path": "/bin/sh",
"Args": [
"-c",
"while true;do echo caicai;sleep 1;done"
],
"State": {
"Status": "running",
"Running": true,
"Paused": false,
"Restarting": false,
"OOMKilled": false,
"Dead": false,
"Pid": 12328,
"ExitCode": 0,
"Error": "",
"StartedAt": "2022-05-12T09:48:36.087437302Z",
"FinishedAt": "0001-01-01T00:00:00Z"
},
"Image": "sha256:5d0da3dc976460b72c77d94c8a1ad043720b0416bfc16c52c45d4847e53fadb6",
"ResolvConfPath": "/var/lib/docker/containers/5583e80d6f3c454f3c819757d5b25af5e85abd233adcea8a95d680d485efaec6/resolv.conf",
"HostnamePath": "/var/lib/docker/containers/5583e80d6f3c454f3c819757d5b25af5e85abd233adcea8a95d680d485efaec6/hostname",
"HostsPath": "/var/lib/docker/containers/5583e80d6f3c454f3c819757d5b25af5e85abd233adcea8a95d680d485efaec6/hosts",
"LogPath": "/var/lib/docker/containers/5583e80d6f3c454f3c819757d5b25af5e85abd233adcea8a95d680d485efaec6/5583e80d6f3c454f3c819757d5b25af5e85abd233adcea8a95d680d485efaec6-json.log",
"Name": "/upbeat_dewdney",
"RestartCount": 0,
"Driver": "overlay2",
"Platform": "linux",
"MountLabel": "",
"ProcessLabel": "",
"AppArmorProfile": "docker-default",
"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/7c01f9cce507abd1ae9b7a8ff60bbe7777c0249b6f1f16b58ca92274cba77135-init/diff:/var/lib/docker/overlay2/98ee8360e5cc47c22bbcd6d6795f9e1fd1282344b5668c1025113b0c75cd95a6/diff",
"MergedDir": "/var/lib/docker/overlay2/7c01f9cce507abd1ae9b7a8ff60bbe7777c0249b6f1f16b58ca92274cba77135/merged",
"UpperDir": "/var/lib/docker/overlay2/7c01f9cce507abd1ae9b7a8ff60bbe7777c0249b6f1f16b58ca92274cba77135/diff",
"WorkDir": "/var/lib/docker/overlay2/7c01f9cce507abd1ae9b7a8ff60bbe7777c0249b6f1f16b58ca92274cba77135/work"
},
"Name": "overlay2"
},
"Mounts": [],
"Config": {
"Hostname": "5583e80d6f3c",
"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 caicai;sleep 1;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": "3eba283d0f17f0dac6febbb9120a3969ccd299d9ce73bdae6a3b624ed9220551",
"HairpinMode": false,
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"Ports": {},
"SandboxKey": "/var/run/docker/netns/3eba283d0f17",
"SecondaryIPAddresses": null,
"SecondaryIPv6Addresses": null,
"EndpointID": "8aae807b8500930b88b75dc012e094cd39054ef33a98e8dbebc48a01091d26ab",
"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": "be628aa5c8f0cffefcb5fc66beeb9cbfa5e46fdccbfb18169e2e7b48366469f1",
"EndpointID": "8aae807b8500930b88b75dc012e094cd39054ef33a98e8dbebc48a01091d26ab",
"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
}
}
}
}
]
进入当前正在运行的容器
我们通常进入容器都是以后台的方式运行的,所以我们需要进入容器去修改一些配置
docker exec -it 容器id /bin/bash
root@taobotics:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
5583e80d6f3c centos "/bin/sh -c 'while t…" 13 minutes ago Up 13 minutes upbeat_dewdney
root@taobotics:~# docker exec -it 5583e80d6f3c /bin/bash
[root@5583e80d6f3c /]# ls
bin dev etc home lib lib64 lost+found media mnt opt proc root run sbin srv sys tmp usr var
方式二:
docker attach 容器id
这样会显示当前正在执行的代码
区别:
-
docker exec
进入容器之后开启一个新的终端,可以在里面操作
-
docker attach
进入容器正在执行的终端,不会启动新的进程
拷贝命令
从容器中拷贝文件到主机中
docker cp 容器id:容器内路径 目的主机路径
# 进入容器内部
root@taobotics:~# docker attach 079fd16cde45
[root@079fd16cde45 /]# cd /home
# 创建一个文件 叫test.java文件
[root@079fd16cde45 home]# touch test.java
[root@079fd16cde45 home]# ls
test.java
[root@079fd16cde45 home]# exit
exit
root@taobotics:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
root@taobotics:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
079fd16cde45 centos "/bin/bash" 2 minutes ago Exited (0) 17 seconds ago pedantic_satoshi
#使用命令将容器中的文件拷贝到主机
root@taobotics:~# docker cp 079fd16cde45:/home/test.java /home
root@taobotics:~# ls
cjh grape_id_code project
# 查看主机是否有拷贝的文件
root@taobotics:~# cd /home
root@taobotics:/home# ls
admin dist test.java
拷贝是一个手动的过程,在之后我们使用 -v 卷的技术,可以实现自动同步 容器的路径与主机的路径联通。
小结
Options:
--config string Location of client config files (default "/root/.docker")
-c, --context string Name of the context to use to connect to the daemon (overrides DOCKER_HOST env var and default context set with
"docker context use")
-D, --debug Enable debug mode
-H, --host list Daemon socket(s) to connect to
-l, --log-level string Set the logging level ("debug"|"info"|"warn"|"error"|"fatal") (default "info")
--tls Use TLS; implied by --tlsverify
--tlscacert string Trust certs signed only by this CA (default "/root/.docker/ca.pem")
--tlscert string Path to TLS certificate file (default "/root/.docker/cert.pem")
--tlskey string Path to TLS key file (default "/root/.docker/key.pem")
--tlsverify Use TLS and verify the remote
-v, --version Print version information and quit
Management Commands:
app* Docker App (Docker Inc., v0.9.1-beta3)
builder Manage builds
buildx* Docker Buildx (Docker Inc., v0.8.2-docker)
config Manage Docker configs
container Manage containers
context Manage contexts
image Manage images
manifest Manage Docker image manifests and manifest lists
network Manage networks
node Manage Swarm nodes
plugin Manage plugins
scan* Docker Scan (Docker Inc., v0.17.0)
secret Manage Docker secrets
service Manage services
stack Manage Docker stacks
swarm Manage Swarm
system Manage Docker
trust Manage trust on Docker images
volume Manage volumes
Commands:
attach Attach local standard input, output, and error streams to a running container
build Build an image from a 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
diff Inspect changes to files or directories on a container's filesystem
events Get real time events from the server
exec Run a command in a running container
export Export a container's filesystem as a tar archive
history Show the history of an image
images List images
import Import the contents from a tarball to create a filesystem image
info Display system-wide information
inspect Return low-level information on Docker objects
kill Kill one or more running containers
load Load an image from a tar archive or STDIN
login Log in to a Docker registry
logout Log out from a 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
push Push an image or a repository to a registry
rename Rename a container
restart Restart one or more containers
rm Remove one or more containers
rmi Remove one or more images
run Run a command in a new container
save Save one or more images to a tar archive (streamed to STDOUT by default)
search Search the Docker Hub for images
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
wait Block until one or more containers stop, then print their exit codes