文章目录
dokcer结构示意
Docker 包括三个基本概念:
- 镜像(Image):Docker 镜像(Image),就相当于是一个 root 文件系统。比如官方镜像 ubuntu:16.04 就包含了完整的一套 Ubuntu16.04 最小系统的 root 文件系统。
- 容器(Container):镜像(Image)和容器(Container)的关系,就像是面向对象程序设计中的类和实例一样,镜像是静态的定义,容器是镜像运行时的实体。容器可以被创建、启动、停止、删除、暂停等。
- 仓库(Repository):仓库可看成一个代码控制中心,用来保存镜像。
Docker 使用客户端-服务器 (C/S) 架构模式,使用远程API来管理和创建Docker容器。
Docker 容器通过 Docker 镜像来创建。
概念 | 说明 |
---|---|
Docker 镜像(Images) | Docker 镜像是用于创建 Docker 容器的模板,比如 Ubuntu 系统。 |
Docker 容器(Container) | 容器是独立运行的一个或一组应用,是镜像运行时的实体。 |
Docker 客户端(Client) | Docker 客户端通过命令行或者其他工具使用 Docker SDK (https://docs.docker.com/develop/sdk/) 与 Docker 的守护进程通信。 |
Docker 主机(Host) | 一个物理或者虚拟的机器用于执行 Docker 守护进程和容器。 |
Docker Registry | Docker 仓库用来保存镜像,可以理解为代码控制中的代码仓库。Docker Hub(https://hub.docker.com) 提供了庞大的镜像集合供使用。一个 Docker Registry 中可以包含多个仓库(Repository);每个仓库可以包含多个标签(Tag);每个标签对应一个镜像。通常,一个仓库会包含同一个软件不同版本的镜像,而标签就常用于对应该软件的各个版本。我们可以通过 <仓库名>:<标签> 的格式来指定具体是这个软件哪个版本的镜像。如果不给出标签,将以 latest 作为默认标签。 |
Docker Machine | Docker Machine是一个简化Docker安装的命令行工具,通过一个简单的命令行即可在相应的平台上安装Docker,比如VirtualBox、 Digital Ocean、Microsoft Azure。 |
docker安装
# 安装docker
yum install docker
# 启动 docker
systemctl start docker
# 停止 docker
systemctl stop docker
# 重启 docker
systemctl restart docker
# 设置开机启动
systemctl enable docker
# 查看 docker 状态
systemctl status docker
# 查看 docker 内容器的运行状态
docker stats
# 查看 docker 概要信息
docker info
#更多版本信息
docker version
docker命令
docker 帮助命令
image --help 镜像help
[root@iZ70eyv5ttqkcsZ /]# docker image --help
Usage: docker image COMMAND
Manage images
Commands:
build Build an image from a Dockerfile 构建镜像
history Show the history of an image 查看镜像构建历史
import Import the contents from a tarball to create a filesystem image 查看详情
inspect Display detailed information on one or more images
load Load an image from a tar archive or STDIN 导入镜像
ls List images 查看镜像列表
prune Remove unused images 删除未使用的镜像
pull Pull an image or a repository from a registry 从仓库拉取
push Push an image or a repository to a registry 从推到仓库
rm Remove one or more images 删除镜像
save Save one or more images to a tar archive (streamed to STDOUT by default) 导出镜像
tag Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE
Run 'docker image COMMAND --help' for more information on a command.
network --help网络管理
环境部署的三个时代:
-
同一个服务器,部署多个网站,如果一个被入侵,全体都挂
-
同一个服务器,安装多个虚拟机,虚拟机里部署网站
-
同一个服务器,多个容器(默认就是隔离)
如果要测试的话,打破隔离
[root@iZ70eyv5ttqkcsZ /]# docker network --help
Usage: docker network COMMAND
Manage networks
Commands:
connect Connect a container to a network 让容器加入一个网络
create Create a network 创建新的网络
disconnect Disconnect a container from a network 容器退出一个网络
inspect Display detailed information on one or more networks 查看网络参数
ls List networks 查看所有
prune Remove all unused networks 删除所有未使用网络
rm Remove one or more networks删除指定网络
Run 'docker network COMMAND --help' for more information on a command.
[root@iZ70eyv5ttqkcsZ /]# docker network create my_net
045a52589a4a65c533c6780cea1e02f59ff086ec931d1e5f5bd5677f7b5880fc
[root@iZ70eyv5ttqkcsZ /]# docker network ls
NETWORK ID NAME DRIVER SCOPE
925d76f09fd6 bridge bridge local
281118b78fa3 host host local
045a52589a4a my_net bridge local
55f475a6cc84 none null local
volume --help文件存储
docker的持久化工具将容器中的保存
[root@iZ70eyv5ttqkcsZ /]# docker volume --help
Usage: docker volume COMMAND
Manage volumes
Commands:
create Create a volume 创建
inspect Display detailed information on one or more volumes 查看参数
ls List volumes 查看列表
prune Remove all unused local volumes
rm Remove one or more volumes
Run 'docker volume COMMAND --help' for more information on a command.
docker --help
[root@iZ70eyv5ttqkcsZ /]# docker --help
Usage: docker [OPTIONS] COMMAND
A self-sufficient runtime for containers
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:
builder Manage builds
config Manage Docker configs
container Manage containers
context Manage contexts
engine Manage the docker engine
image Manage images
network Manage networks
node Manage Swarm nodes
plugin Manage plugins
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 docker版本
wait Block until one or more containers stop, then print their exit codes
Run 'docker COMMAND --help' for more information on a command.
docker container --help容器
[root@iZ70eyv5ttqkcsZ /]# docker container --help
Usage: docker container COMMAND
Manage containers
Commands:
attach Attach local standard input, output, and error streams to a running container
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
exec Run a command in a running container
export Export a container's filesystem as a tar archive
inspect Display detailed information on one or more containers
kill Kill one or more running containers
logs Fetch the logs of a container
ls List containers
pause Pause all processes within one or more containers
port List port mappings or a specific mapping for the container
prune Remove all stopped containers
rename Rename a container
restart Restart one or more containers
rm Remove one or more containers
run Run a command in a new container
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
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
wait Block until one or more containers stop, then print their exit codes
Run 'docker container COMMAND --help' for more information on a command.
- run 从镜像创建并启动容器
- stop 停止一个容器
- kill 强行结束镜像
- restart 重启容器
- logs查看容器日志
docker 镜像命令
docker images 显示本地库镜像
REPOSITORY TAG IMAGE ID CREATED SIZE
redis latest 7614ae9453d1 3 days ago 113MB
mysql 5.6 dd3b2a5dcb48 3 days ago 303MB
#解释
REPOSITORY 镜像的仓库源
TAG 镜像的标签
IMAGE ID 进行的id
CREATED 镜像创建时间
SIZE 镜像大小
#可选项
-a . --all #列出所有镜像
-q , --quiet #只显示镜像ID
docker serach 搜索镜像
可以通过docker serach 镜像名搜镜像 -f进行过滤
[root@iZ70eyv5ttqkcsZ ~]# docker search tomcat
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
tomcat Apache Tomcat is an open source implementati… 3202 [OK]
tomee Apache TomEE is an all-Apache Java EE certif… 95 [OK]
#可选项
--filter=STARS=3000
[root@iZ70eyv5ttqkcsZ ~]# docker search tomcat --filter=STARS=3000
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
tomcat Apache Tomcat is an open source implementati… 3202 [OK]
docker pull 下载镜像
[root@iZ70eyv5ttqkcsZ ~]# docker pull tomcat
# docker pull 镜像名[:tag]
Using default tag: latest 没写tag就会默认下载最新版本
latest: Pulling from library/tomcat #层级下载 docker iamge的核心 联合文件系统
0e29546d541c: Pull complete
9b829c73b52b: Pull complete
cb5b7ae36172: Pull complete
6494e4811622: Pull complete
668f6fcc5fa5: Pull complete
dc120c3e0290: Pull complete
8f7c0eebb7b1: Pull complete
77b694f83996: Pull complete
0f611256ec3a: Pull complete
4f25def12f23: Pull complete
Digest: sha256:9dee185c3b161cdfede1f5e35e8b56ebc9de88ed3a79526939701f3537a52324
Status: Downloaded newer image for tomcat:latest
docker.io/library/tomcat:latest
#因此docker tomcat 等价于 docker.io/library/tomcat:latest
[root@iZ70eyv5ttqkcsZ ~]# 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删除镜像
docker rmi -f 容器id #删除指定镜像
docker rmi -f 容器id 容器id 容器id #删除多个指定镜像
docker rmi -f $(docker images -ap) #删除全部镜像
docker 容器命令
docker run 运行容器
run命令参数
docker run[可选参数] image
--name #自定义容器名称
--rm #结束后自动删除
--net #指定容器加入的网络
--volume${PWD}:/tmp #把当前目录放在容器中
-it #交互方式进入到容器内部
-d #让容器在后台运行
-p #指定容器端口 -p 8080:8080
(-p ip:主机端口:容器端口
-p 主机端口:容器端口
-p 容器端口
容器端口
)
镜像名
bush #容器执行的命令
实例:
输入命令创建一个容器
[root@iZ70eyv5ttqkcsZ /]#docker run --name myubuntu --rm --net my_net -it --volume ${PWD}:/tmp ubuntu:15.10
从镜像ubuntu:15.10运行一个容器,
参数为–name myubuntu 自定义命名myubuntu
–rm 结束后删除容器
–net my_net 使用自定义网络network
–it 进入到容器内部
–volume${PWD}:/tmp 将当前目录和
创建之后
容器的tmp和创建时的目录temp成为了共享文件夹
docker ps 列出所有容器
docker ps 命令
参数
-a #列出当前正在运行的容器,带出历史运行过的容器
[root@iZ70eyv5ttqkcsZ ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
d6bff0002ff3 mysql:5.6 "docker-entrypoint.s…" 14 hours ago Exited (0) 11 hours ago qmm-mysql
ea28a8983188 redis "docker-entrypoint.s…" 14 hours ago Exited (0) 11 hours ago redis-test
502e81fcd6ef mysql "docker-entrypoint.s…" 14 hours ago Exited (137) 14 hours ago mysqltest
be5b402aa0ea ubuntu:15.10 "/bin/bash" 17 hours ago Exited (0) 14 hours ago myubuntu
-n=? #显示最近创建过的容器
[root@iZ70eyv5ttqkcsZ ~]# docker ps -n=2
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
d6bff0002ff3 mysql:5.6 "docker-entrypoint.s…" 14 hours ago Exited (0) 11 hours ago qmm-mysql
ea28a8983188 redis "docker-entrypoint.s…" 14 hours ago Exited (0) 11 hours ago redis-test
-q #只显示容器编号
[root@iZ70eyv5ttqkcsZ ~]# docker ps -aq
d6bff0002ff3
ea28a8983188
502e81fcd6ef
be5b402aa0ea
exit 退出容器
exit #容器停止并退出
Ctrl + P+ Q #容器不停止退出
rm 删除容器
docker rm 容器id #强制删除-f
docker rm -f$(docker ps -aq) #删除所有容器
docker rm -a -q | xargs docker rm #删除所有容器 通过linux管道符方式
-f :通过 SIGKILL 信号强制删除一个运行中的容器。
-l :移除容器间的网络连接,而非容器本身。
-v :删除与容器关联的卷。
启动容器停止容器
docker start 容器id #启动容器
docker restart 容器id #重启容器
docker stop 容器id #停止当前容器
docker kill 容器id #强行结束容器 -s (运行中)
后台启动的坑
[root@iZ70eyv5ttqkcsZ /]# docker image ls
REPOSITORY TAG IMAGE ID CREATED SIZE
tomcat latest fb5657adc892 2 days ago 680MB
redis latest 7614ae9453d1 3 days ago 113MB
mysql 5.6 dd3b2a5dcb48 4 days ago 303MB
mysql 5.7 c20987f18b13 4 days ago 448MB
mysql latest 3218b38490ce 4 days ago 516MB
hello-world latest feb5d9fea6a5 3 months ago 13.3kB
ubuntu 15.10 9b9cb95443b5 5 years ago 137MB
[root@iZ70eyv5ttqkcsZ /]# docker run -d ubuntu:15.10
88a5e2093d45b5c73fe387efec75435d06a105a4f90524c14f26458fd1a83ee6
[root@iZ70eyv5ttqkcsZ /]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
[root@iZ70eyv5ttqkcsZ /]#
#可以看出来通脱docker run -d 启动的ubuntu系统自动停止了
#docker容器在后台运行,就必须要有一个前台进程,dicker发现没有应用,就会自动停止
#nginx容器停止后,发现自己没提供服务就停止了
logs 查看日志
[root@iZwz99sm8v95sckz8bd2c4Z ~]# 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)
[root@iZ70eyv5ttqkcsZ /]# docker run -d ubuntu:15.10 /bin/sh -c "while true;do echo asdf;sleep 1;done"
通过启动ubyuntu运行shell脚本
然后查看日志
docker logs -tf --tail 10 9ea2db1ae202 查看容器日志10条
-t 时间戳
--tail number # 要显示日志条数
top 查看容器进程信息
[root@iZ70eyv5ttqkcsZ /]# docker top 9ea2db1ae202
UID PID PPID C STIME TTY TIME CMD
root 20319 20300 0 11:47 ? 00:00:00 /bin/sh -c while true;do echo asdf;sleep 1;done
root 20735 20319 0 11:53 ? 00:00:00 sleep 1
inspect 查看镜像元数据
#命令
docker inspect 容器id
[root@iZ70eyv5ttqkcsZ /]# docker inspect 9ea2db1ae202
[
{
"Id": "9ea2db1ae202fe5ed6daeaeea6b2f19008fe3431b854dc97234eb877262abbe4",
"Created": "2021-12-25T03:47:28.114441135Z", #创建时间
"Path": "/bin/sh",
"Args": [
"-c",
"while true;do echo asdf;sleep 1;done"
],
"State": {
"Status": "running",
"Running": true,
"Paused": false,
"Restarting": false,
"OOMKilled": false,
"Dead": false,
"Pid": 20319,
"ExitCode": 0,
"Error": "",
"StartedAt": "2021-12-25T03:47:28.408944652Z",
"FinishedAt": "0001-01-01T00:00:00Z"
},
"Image": "sha256:9b9cb95443b5f846cd3c8cfa3f64e63b6ba68de2618a08875a119c81a8f96698",
"ResolvConfPath": "/var/lib/docker/containers/9ea2db1ae202fe5ed6daeaeea6b2f19008fe3431b854dc97234eb877262abbe4/resolv.conf",
"HostnamePath": "/var/lib/docker/containers/9ea2db1ae202fe5ed6daeaeea6b2f19008fe3431b854dc97234eb877262abbe4/hostname",
"HostsPath": "/var/lib/docker/containers/9ea2db1ae202fe5ed6daeaeea6b2f19008fe3431b854dc97234eb877262abbe4/hosts",
"LogPath": "/var/lib/docker/containers/9ea2db1ae202fe5ed6daeaeea6b2f19008fe3431b854dc97234eb877262abbe4/9ea2db1ae202fe5ed6daeaeea6b2f19008fe3431b854dc97234eb877262abbe4-json.log",
"Name": "/reverent_mestorf",
"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/ff1a3f18a4ebfaa1917f590f9aef58944996e370a0920297a61b5a24789cc50e-init/diff:/var/lib/docker/overlay2/5374c6923f0c3e34a2063f69e740d22e5f0dc3c774a85daaea2243bde27f4e30/diff:/var/lib/docker/overlay2/c52b61b87d6f5b6d1db021f5bcefb0fc72244cf6ebd177ab4da31c3039484575/diff:/var/lib/docker/overlay2/89ec0b0a5bdbf0b16e52f600a2635d65bf853f49028600c29c0d9831a97c6b1c/diff:/var/lib/docker/overlay2/ac0af19b0239fea77aa851305752f6892e1e35b06d35eee2ce952d0a58165bd5/diff",
"MergedDir": "/var/lib/docker/overlay2/ff1a3f18a4ebfaa1917f590f9aef58944996e370a0920297a61b5a24789cc50e/merged",
"UpperDir": "/var/lib/docker/overlay2/ff1a3f18a4ebfaa1917f590f9aef58944996e370a0920297a61b5a24789cc50e/diff",
"WorkDir": "/var/lib/docker/overlay2/ff1a3f18a4ebfaa1917f590f9aef58944996e370a0920297a61b5a24789cc50e/work"
},
"Name": "overlay2"
},
"Mounts": [],
"Config": {
"Hostname": "9ea2db1ae202",
"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 asdf;sleep 1;done"
],
"Image": "ubuntu:15.10",
"Volumes": null,
"WorkingDir": "",
"Entrypoint": null,
"OnBuild": null,
"Labels": {}
},
"NetworkSettings": {
"Bridge": "",
"SandboxID": "1e4ab641ef66db61ed8d80ee86403f520e9fed30778bdea5ca90560f2d88aaff",
"HairpinMode": false,
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"Ports": {},
"SandboxKey": "/var/run/docker/netns/1e4ab641ef66",
"SecondaryIPAddresses": null,
"SecondaryIPv6Addresses": null,
"EndpointID": "582789bb827cf0be983a2c27b1ce81beb938d96bcc87819975699d6f8698f80e",
"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": "b7fadd350b116c439908c7d7e2118478ddaa91d355d090572584e6b5f58137b6",
"EndpointID": "582789bb827cf0be983a2c27b1ce81beb938d96bcc87819975699d6f8698f80e",
"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
}
}
}
}
]
exec / attach进入容器的命令
#容器大多为后台运行,可以通过exec命令进入容器修改配置
docker exec -it 容器id bashShell
#实例
#方式一
[root@iZ70eyv5ttqkcsZ /]# docker exec -it 9ea2db1ae202 /bin/bash
root@9ea2db1ae202:/# ls
bin dev home lib64 mnt proc run srv tmp var
boot etc lib media opt root sbin sys usr
#方式二
docker attach 9ea2db1ae202
#区别
#exec是开启一个新终端进行操作
#attach进入容器正在执行的终端
ps 从容器内拷贝文件到主机
docker cp 容器id:容器内路径 目的主机路径
#进入容器内部
[root@iZ70eyv5ttqkcsZ home]# docker exec -it 9ea2db1ae202 /bin/bash
root@9ea2db1ae202:/# ls
bin dev home lib64 mnt proc run srv tmp var
boot etc lib media opt root sbin sys usr
root@9ea2db1ae202:/# cd tmp/
root@9ea2db1ae202:/tmp# ll
total 8
drwxrwxrwt 2 root root 4096 Jul 6 2016 ./
drwxr-xr-x 1 root root 4096 Dec 25 03:47 ../
#创建新文件test.java
root@9ea2db1ae202:/tmp# touch test.java
root@9ea2db1ae202:/tmp# ls
test.java
root@9ea2db1ae202:/tmp# exit
exit
[root@iZ70eyv5ttqkcsZ home]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
9ea2db1ae202 ubuntu:15.10 "/bin/sh -c 'while t…" 30 minutes ago Up 30 minutes reverent_mestorf
#退出后拷贝
[root@iZ70eyv5ttqkcsZ home]# docker cp 9ea2db1ae202:tmp/test.java /temp #将容器内文件拷贝到主机路径了
[root@iZ70eyv5ttqkcsZ home]# ls
admin
[root@iZ70eyv5ttqkcsZ home]# cd ..
[root@iZ70eyv5ttqkcsZ /]# cd temp/
#检查拷贝结果
[root@iZ70eyv5ttqkcsZ temp]# ls
f t1.txt test.java
docker镜像详解
什么是镜像
镜像是一种轻量级、可执行的独立软件包,用来打包软件运行环境和基于运行环境开发的软件,它包含运行某个软件所需要的所有内容,包括代码,运行时(一个程序在运行或者在被执行的依赖)、库,环境变量和配置文件。
Docker镜像加载原理
Docker的镜像实际上由一层一层的文件系统组成,这种层级的文件系统是UnionFS联合文件系统。
UnionFS (联合文件系统) : Union文件系统( UnionFS)是一种分层、轻量级并且高性能的文件系统,它支持对文件系统的修改作为一次提交来层层的叠加,同时可以将不同目录挂载到同-个虚拟文件系统下(unite several directories into a single virtual filesystem)。Union 文件系统是Docker镜像的基础。镜像可以通过分层来进行继承,基于基础镜像(没有父镜像) , 可以制作各种具体的应用镜像。
特性: 一次同时加载多个文件系统,但从外面看起来,只能看到一个文件系统,联合加载会把各层文件系统叠加起来,这样最终的文件系统会包含所有底层的文件和目录
bootfs(boot file system)主要包含bootloader和kernel, bootloader主要是引导加载kernel, Linux刚启动时会加载bootfs文件系统,在Docker镜像的最底层是bootfs.这-层与我们典型的Linux/Unix系统是一样的,包含boot加载器和内核。当boot加载完成之后整个内核就都在内存中了,此时内存的使用权E Qbp fs转交给内核,此时系统也会卸载bootfs.
rootfs (root file system) , 在bootfs之上。包含的就是典型Linux系统中的/dev, /proc, /bin, /etc等标准目录和文件。rootfs就是各种不同的操作系统发行版,比如Ubuntu , Centos等等。
分层理解
[root@iZ70eyv5ttqkcsZ ~]# docker pull redis
Using default tag: latest
Trying to pull repository docker.io/library/redis ...
latest: Pulling from docker.io/library/redis
a2abf6c4d29d: Pull complete
c7a4e4382001: Pull complete
4044b9ba67c9: Pull complete
c8388a79482f: Pull complete
413c8bb60be2: Pull complete
1abfd3011519: Pull complete
Digest: sha256:db485f2e245b5b3329fdc7eff4eb00f913e09d8feb9ca720788059fdc2ed8339
Status: Downloaded newer image for docker.io/redis:latest
redis镜像的分层信息
[root@iZ70eyv5ttqkcsZ ~]# docker image inspect 7614ae9453d1
[
{
"Id": "sha256:7614ae9453d1d87e740a2056257a6de7135c84037c367e1fffa92ae922784631",
"RepoTags": [
"docker.io/redis:latest"
],
"RepoDigests": [
"docker.io/redis@sha256:db485f2e245b5b3329fdc7eff4eb00f913e09d8feb9ca720788059fdc2ed8339"
],
"Parent": "",
"Comment": "",
"Created": "2021-12-21T12:42:49.755107412Z",
"Container": "13d25f53410417c5220c8dfe8bd49f06abdbcd69faa62a9b877de02464bb04a3",
"ContainerConfig": {
"Hostname": "13d25f534104",
"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.2.6",
"REDIS_DOWNLOAD_URL=http://download.redis.io/releases/redis-6.2.6.tar.gz",
"REDIS_DOWNLOAD_SHA=5b2b8b7a50111ef395bf1c1d5be11e6e167ac018125055daa8b5c2317ae131ab"
],
"Cmd": [
"/bin/sh",
"-c",
"#(nop) ",
"CMD [\"redis-server\"]"
],
"Image": "sha256:e093f59d716c95cfce82c676f099b960cc700432ab531388fcedf79932fc81ec",
"Volumes": {
"/data": {}
},
"WorkingDir": "/data",
"Entrypoint": [
"docker-entrypoint.sh"
],
"OnBuild": null,
"Labels": {}
},
"DockerVersion": "20.10.7",
"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.2.6",
"REDIS_DOWNLOAD_URL=http://download.redis.io/releases/redis-6.2.6.tar.gz",
"REDIS_DOWNLOAD_SHA=5b2b8b7a50111ef395bf1c1d5be11e6e167ac018125055daa8b5c2317ae131ab"
],
"Cmd": [
"redis-server"
],
"Image": "sha256:e093f59d716c95cfce82c676f099b960cc700432ab531388fcedf79932fc81ec",
"Volumes": {
"/data": {}
},
"WorkingDir": "/data",
"Entrypoint": [
"docker-entrypoint.sh"
],
"OnBuild": null,
"Labels": null
},
"Architecture": "amd64",
"Os": "linux",
"Size": 112691373,
"VirtualSize": 112691373,
"GraphDriver": {
"Name": "overlay2",
"Data": {
"LowerDir": "/var/lib/docker/overlay2/62af77965a3476e4455a63a4a2c035de425c122126416a6d444bc3828b6e1565/diff:/var/lib/docker/overlay2/891aab6af76699a767e75221bde0813ded1b4d7a334ac2f871a054e22d3b6406/diff:/var/lib/docker/overlay2/6546f44f77123619d93872f6d62007c3063c396149e4e934bbe06ae6f934f673/diff:/var/lib/docker/overlay2/f01a1ec92c9bfbce291ebaadc090b089260d1b54f1abab456737b6a766945a53/diff:/var/lib/docker/overlay2/c077d83c4aea5d1eab5598f9abf2e771e757a06553ee4dd730e27b5498662783/diff",
"MergedDir": "/var/lib/docker/overlay2/67a7e9415012210b243784af52f52a9c7427ed40e55d4b91370138314602f2ab/merged",
"UpperDir": "/var/lib/docker/overlay2/67a7e9415012210b243784af52f52a9c7427ed40e55d4b91370138314602f2ab/diff",
"WorkDir": "/var/lib/docker/overlay2/67a7e9415012210b243784af52f52a9c7427ed40e55d4b91370138314602f2ab/work"
}
},
"RootFS": {
"Type": "layers",
"Layers": [
"sha256:2edcec3590a4ec7f40cf0743c15d78fb39d8326bc029073b41ef9727da6c851f",
"sha256:9b24afeb7c2f21e50a686ead025823cd2c6e9730c013ca77ad5f115c079b57cb",
"sha256:4b8e2801e0f956a4220c32e2c8b0a590e6f9bd2420ec65453685246b82766ea1",
"sha256:529cdb636f61e95ab91a62a51526a84fd7314d6aab0d414040796150b4522372",
"sha256:9975392591f2777d6bf4d9919ad1b2c9afa12f9a9b4d260f45025ec3cc9b18ed",
"sha256:8e5669d8329116b8444b9bbb1663dda568ede12d3dbcce950199b582f6e94952"
]
}
}
]
采用这种分层的方式有什么好处呢?
最大的好处在于资源共享,如果有多个镜像都使用了相同的Base镜像,name宿主机只需要保存一份base镜像,在加载的时候,都使用这一个镜像,节省了空间,带宽
示例:
所有的镜像都起始于一个基础镜像层,在修改和添加新内容的时候,都会在当前镜像层上面创建一个新的镜像层.
上图首先以ubuntu创建了一个镜像作为第一层镜像,之后添加了python包,就会在这个基础上新建第二个镜像层,添加了第三层安全层.
再添加额外的镜像层的时候,镜像也同时是当前所有镜像的集合,每层有三个文件,镜像包含了两个镜像层的6个文件
现在是一个三层镜像,添加了文件7作为第三层.但是在外部看来,只有六个文件.因为文件器是文件5的一个更新版本
实际外层展示的镜像层是合并后的结果
docker都是只读的,从镜像在启动了后,就会将一层新的可写层加载到镜像的顶部.这一层被称为容器层,在这个之下的都被称为镜像层
同时我们可以将改动后的操作打包为一个新的镜像.
commit镜像
docker commit -m="提交的描述信息" -a"作者" 容器id 目标镜像名:[TAG]
实例:tomcat运行并commit镜像
将tomcat的webapps.dist目录的东西cp到webapp下
进行commit命令进行提交为一个新镜像
以后使用新镜像即可
#进入tomcat进行拷贝操作
[root@iZ70eyv5ttqkcsZ ~]# docker exec -it mytomcat /bin/bash
root@4fb7a336b403:/usr/local/tomcat# cp -r webapps.dist/* webapps
root@4fb7a336b403:/usr/local/tomcat# ls
BUILDING.txt CONTRIBUTING.md LICENSE NOTICE README.md RELEASE-NOTES RUNNING.txt bin conf lib logs native-jni-lib temp webapps webapps.dist work
root@4fb7a336b403:/usr/local/tomcat# cd webapps
root@4fb7a336b403:/usr/local/tomcat/webapps# ls
ROOT docs examples host-manager manager
#然后进行打包
[root@iZ70eyv5ttqkcsZ ~]# docker commit -a="yjwtest" -m="add webapp" 4fb7a336b403 tomcattest:01
[root@iZ70eyv5ttqkcsZ ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
tomcattest 01 27a965b7b00e 9 seconds ago 684 MB
docker.io/tomcat latest fb5657adc892 3 days ago 680 MB
docker.io/redis latest 7614ae9453d1 4 days ago 113 MB
docker.io/mysql latest 3218b38490ce 5 days ago 516 MB
docker.io/hello-world latest feb5d9fea6a5 3 months ago 13.3 kB
docker.io/portainer/portainer latest 580c0e4e98b0 9 months ago 79.1 MB
看出来打包成功了
观察两个镜像的layers字段,可见增加了一层镜像层
容器数据卷volume
Docker将运用与运行的环境打包形成容器运行, Docker容器产生的数据,如果不通过docker commit生成新的镜像,使得数据做为镜像的一部分保存下来, 那么当容器删除后,数据自然也就没有了。 为了能保存数据在Docker中我们使用卷。
卷就是目录或文件,存在于一个或多个容器中,由Docker挂载到容器,但卷不属于联合文件系统(Union FileSystem),因此能够绕过联合文件系统提供一些用于持续存储或共享数据的特性:。
容器的持久化和同步操作,容器之间也可以数据共享
示例
创建一个centos系统将宿主机的/home/centostest目录和容器的home目录进行了卷挂载
[root@iZ70eyv5ttqkcsZ ~]# docker run -it -v /home/centostest:/home centos /bin/bash
docker inspect 容器id
"Mounts": [
{
"Type": "bind",
"Source": "/home/centostest", #主机内地址
"Destination": "/home", # 容器内地址
"Mode": "",
"RW": true,
"Propagation": "rprivate"
}
],
测试绑定是否成功
#宿主机-docker容器
#宿主机
[root@iZ70eyv5ttqkcsZ home]# cd centostest/
[root@iZ70eyv5ttqkcsZ centostest]# ls
[root@iZ70eyv5ttqkcsZ centostest]# touch 1.txt
[root@iZ70eyv5ttqkcsZ centostest]# ls
1.txt
#docker
[root@00dc126cf532 home]# ls
1.txt
#docker容器-宿主机
#容器
[root@00dc126cf532 home]# touch test.java
[root@00dc126cf532 home]# ls
1.txt test.java
#宿主机
[root@iZ70eyv5ttqkcsZ centostest]# ls
1.txt test.java
后续及时容器停止.修改目录下在启动后也能数据同步
实例:mysql数据和配置文件挂载,实现容器数据持久化
- 创建容器
docker run -d -p3306:3306 -v /home/mysql/conf:/etc/mysql/conf -v /home/mysql/data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=1234 --name mysqltest mysql:5.7
-d 后台运行
-v 卷挂载 可以多写
-e 环境配置
--name重命名
可能容器名字重复,可以使用docker ps -a 查看后,docker rm 删除容器,或者选择其他名字
"Mounts": [
{
"Type": "bind",
"Source": "/home/mysql/conf",
"Destination": "/etc/mysql/conf",
"Mode": "",
"RW": true,
"Propagation": "rprivate"
},
{
"Type": "bind",
"Source": "/home/mysql/data",
"Destination": "/var/lib/mysql",
"Mode": "",
"RW": true,
"Propagation": "rprivate"
}
],
- 通过3306:3306进行了端口映射.所以使用ip:端口号测试链接
测试链接成功
-
创建一个数据库test1
可以看到挂载的data目录出现了test1w文件夹
4.删除容器检查数据是否存在
[root@iZ70eyv5ttqkcsZ ~]# docker rm -f a3576fbdfab0
[root@iZ70eyv5ttqkcsZ conf]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
a3576fbdfab0 mysql:5.7 "docker-entrypoint..." 11 minutes ago Up 11 minutes 0.0.0.0:3306->3306/tcp, 33060/tcp mysqltest
[root@iZ70eyv5ttqkcsZ conf]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
已经进行了删除
[root@iZ70eyv5ttqkcsZ data]# ls
auto.cnf ca.pem client-key.pem ibdata1 ib_logfile1 mysql private_key.pem server-cert.pem sys
ca-key.pem client-cert.pem ib_buffer_pool ib_logfile0 ibtmp1 performance_schema public_key.pem server-key.pem test1
检查数据依旧存在们可以看出来数据是持久化的
具名挂载和匿名挂载
匿名和具名指的是挂载名没有指定
-v /容器内路径为匿名挂载
-v 卷名 /容器内路径为具名挂载
-v /宿主机路径:容器内路径
#匿名挂载
docker run -d -P --name nginx01 -v /ext/nginx nginx
DRIVER VOLUME NAME
local d50fc7dd550f516f0399bc44a7a6bb36f5c8a027d150d20186d4bcb1bf97a770
#具名挂载
docker run -d -P --name nginx02 -v juming-nginx:/etc/nginx nginx
DRIVER VOLUME NAME
local juming-nginx
#通过docker volume inspect 挂载名查看具体路径
[root@iZ70eyv5ttqkcsZ etc]# docker volume inspect juming-nginx
[
{
"Driver": "local",
"Labels": null,
"Mountpoint": "/var/lib/docker/volumes/juming-nginx/_data",#可以看出实际路径在这个地方,没有指定目录的情况下都在这个目录下存在
"Name": "juming-nginx",
"Options": {},
"Scope": "local"
}
]
只写了容器内路径没写容器外路径就会默认存储在这个目录下
[root@iZ70eyv5ttqkcsZ etc]# cd /var/lib/docker/volumes
[root@iZ70eyv5ttqkcsZ volumes]# ls
03bb1f56f95be70ae73ce7658b2b465db6357da7d934951fefa7da01a331b63f
374bd2397a0f963947e287c00383dc532a3291661eff5c65634b78d52da65312
56c60c435470192b3aea364948472035bd66437c78b5392f41a7e6dbb6037f7d
90b0ab7e3ee2171f964daa70944f097150505901d580d125c655c2a01a5f5c3a
d50fc7dd550f516f0399bc44a7a6bb36f5c8a027d150d20186d4bcb1bf97a770
juming-nginx
metadata.db
拓展:
ro readonly #只读 对于docker只能读取,写入只能从宿主机开始
rw readwrite#可写
docker run -d -P --name nginx02 -v juming-nginx:etc/nginx:ro nginx
docker run -d -P --name nginx02 -v juming-nginx:etc/nginx:rw nginx # 默认情况
Dockerfile中设置数据卷
我们可以在Dockerfile中使用VOLUME指令来给镜像添加一个或多个数据卷。
下面使用Dockerfile构建一个新的镜像,dockerfile01文件的内容,匿名挂载了volume01和volume02两个目录:
FROM centos
VOLUME ["volume01","volume02"]
CMD echo "----end----"
CMD /bin/bash
构建语句
[root@iZ70eyv5ttqkcsZ home]# docker build -f dockfile01 -t centos . #注意有个点 .
Sending build context to Docker daemon 219.9 MB
Step 1/4 : FROM centos
---> 5d0da3dc9764
Step 2/4 : VOLUME volume01 volume02
---> Running in fb1b6162c99a
---> 2324d5195be1
Removing intermediate container fb1b6162c99a
Step 3/4 : CMD echo "end------"
---> Running in b60ceb27c6cc
---> 47ae91d9d1a5
Removing intermediate container b60ceb27c6cc
Step 4/4 : CMD /bin/bash
---> Running in c35591f37d19
---> b87454c9f973
Removing intermediate container c35591f37d19
Successfully built b87454c9f973
#生成了自己的images
[root@iZ70eyv5ttqkcsZ home]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
centos latest b87454c9f973 22 seconds ago 231 MB
tomcattest 01 27a965b7b00e 22 hours ago 684 MB
docker.io/tomcat latest fb5657adc892 4 days ago 680 MB
docker.io/redis latest 7614ae9453d1 5 days ago 113 MB
#可以看到对应宿主机的数据卷目录
"Mounts": [
{
"Type": "volume",
"Name": "fd83740be3beed68e3592749bc30492832ed5d56084faa48d6ba6305814eba6c", #名字
"Source": "/var/lib/docker/volumes/fd83740be3beed68e3592749bc30492832ed5d56084faa48d6ba6305814eba6c/_data", #宿主机
"Destination": "volume01",#容器内地址
"Driver": "local",
"Mode": "",
"RW": true,
"Propagation": ""
},
{
"Type": "volume",
"Name": "74043b2e4ca2110706c73e76e6d04b49f58d5942a4dfd86ff0e66e4a9c89a94b",
"Source": "/var/lib/docker/volumes/74043b2e4ca2110706c73e76e6d04b49f58d5942a4dfd86ff0e66e4a9c89a94b/_data",
"Destination": "volume02",
"Driver": "local",
"Mode": "",
"RW": true,
"Propagation": ""
}
],
容器数据卷
通过参数--volumes-from
,设置容器2和容器1建立数据卷挂载关系。
docker run -d -p 6603: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
docker run -d -p 6604:3306 -e MYSQL_ROOT_PASSWORD=123456 --name mysql02 --volumes-from mysql01 mysql:5.7
实现了两个mysql数据库的同步
容器之间配置信息的传递,数据卷容器的生命周期持续到没有容器使用位置
上传镜像
上传到Docker Hub
#之前的镜像名为yjwtomcat1不能上传
[root@iZ70eyv5ttqkcsZ ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
yjwtomcat1 0 0ae4a098790e 14 hours ago 692 MB
entorypoint-test latest 7fe30dd55dc0 16 hours ago 231 MB
cmdtest latest f5a0a65d1e51 16 hours ago 231 MB
#使用docker tag 原名 现名修改镜像名字
[root@iZ70eyv5ttqkcsZ ~]# docker tag yjwtomcat1:0 cancan1230987/yjwtomcat:1.0
#修改之后的镜像名
[root@iZ70eyv5ttqkcsZ ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
cancan1230987/yjwtomcat 1.0 0ae4a098790e 14 hours ago 692 MB
yjwtomcat1 0 0ae4a098790e 14 hours ago 692 MB
entorypoint-test latest 7fe30dd55dc0 16 hours ago 231 MB
#上传成功
[root@iZ70eyv5ttqkcsZ ~]# docker push cancan1230987/yjwtomcat
docker运行名称
run命令快速查找
docker run -d -p 8088:9000 --restart=always -v /var/run/docker.sock:/var/run/docker.sock --privileged=true portainer/portainer
观看B站狂神视频学习笔记.
【狂神说Java】Docker最新超详细版教程通俗易懂