Docker入门

Docker容器学习笔记Ⅰ(狂神说Java)

狂神说B站视频:https://www.bilibili.com/video/BV1og4y1q7M4?p=1

学习docker:https://www.runoob.com/docker/docker-tutorial.html

使用docker:https://labs.play-with-docker.com/

一、大纲

入门:

  • Docker概述

  • Docker安装

  • Docker命令

    • 镜像命令
    • 容器命令
    • 操作命令
    • ……
  • Docker镜像

精髓:

  • 容器数据卷

  • DockerFile

  • Docker网络原理

企业级:

  • IDEA整合Docker

  • 集群

    • Docker Compose
    • Docker Swarm
  • CI/CD Jenkins流水线

二、Docker概述

1.Docker为什么会出现?

一款产品: 开发–上线 两套环境!应用环境,应用配置!

开发 — 运维。 问题:我在我的电脑上可以允许!版本更新,导致服务不可用!对于运维来说考验十分大?

环境配置是十分的麻烦,每一个机器都要部署环境(集群Redis、ES、Hadoop…) !费事费力。
发布一个项目( jar + (Redis MySQL JDK ES) ),项目能不能带上环境安装打包!

之前在服务器配置一个应用的环境 Redis MySQL JDK ES Hadoop 配置超麻烦了,不能够跨平台。

开发环境Windows,最后发布到Linux!

传统:开发jar,运维来做!

现在:开发打包部署上线,一套流程做完!

安卓流程:java — apk —发布(应用商店)一 张三使用apk一安装即可用!

docker流程: java-jar(环境) — 打包项目帯上环境(镜像) — ( Docker仓库:商店)—–

Docker给以上的问题,提出了解决方案!

Docker的思想就来自于集装箱!

JRE – 多个应用(端口冲突) – 原来都是交叉的!

隔离:Docker核心思想!打包装箱!每个箱子是互相隔离的。

Docker通过隔离机制,可以将服务器利用到极致!

本质:所有的技术都是因为出现了一些问题,我们需要去解决,才去学习!

2.Dcoker的历史

2010年,几个的年轻人,就在美国成立了一家公司 dotcloud

做一些pass的云计算服务!LXC(Linux Container容器)有关的容器技术!

  • Linux Container容器是一种内核虚拟化技术,可以提供轻量级的虚拟化,以便隔离进程和资源。

他们将自己的技术(容器化技术)命名就是 Docker。

Docker刚刚延生的时候,没有引起行业的注意!dotCloud,就活不下去!

  • 开源

2013年,Docker开源!

越来越多的人发现docker的优点!火了。Docker每个月都会更新一个版本!

2014年4月9日,Docker1.0发布!

docker为什么这么火?十分的轻巧!

在容器技术出来之前,我们都是使用虚拟机技术!

虚拟机:在window中装一个VMware,通过这个软件我们可以虚拟出来一台或者多台电脑!笨重!

虚拟机也属于虚拟化技术,Docker容器技术,也是一种虚拟化技术!

  • vm : linux centos 原生镜像(一个电脑!) 隔离、需要开启多个虚拟机! 几个G 几分钟

  • docker: 隔离,镜像(最核心的环境 4m + jdk + mysql)十分的小巧,运行镜像就可以了!小巧!几个M 秒级启动!

Docker基于Go语言开发的!开源项目!

docker官网:https://www.docker.com/

文档:https://docs.docker.com/ Docker的文档是超级详细的!

仓库:https://hub.docker.com/

3.Docker能做什么?

比较Docker和虚拟机技术的不同:

  • 传统虚拟机,虚拟出一条硬件,运行一个完整的操作系统,然后在这个系统上安装和运行软件

  • 容器内的应用直接运行在宿主机的内容,容器是没有自己的内核的,也没有虚拟我们的硬件,所以就轻便了

  • 每个容器间是互相隔离,每个容器内都有一个属于自己的文件系统,互不影响

4.DevOps(开发、运维)

  • 应用更快速的交付和部署

传统:一对帮助文档,安装程序。

Docker:打包镜像发布测试一键运行。

  • 更便捷的升级和扩缩容

使用了 Docker之后,我们部署应用就和搭积木一样

项目打包为一个镜像,扩展服务器A!服务器B

  • 更简单的系统运维

在容器化之后,我们的开发,测试环境都是高度一致的

  • 更高效的计算资源利用

Docker是内核级别的虚拟化,可以在一个物理机上可以运行很多的容器实例!服务器的性能可以被压榨到极致。

三、Docker安装

1.Docker的基本组成

  • 镜像(image):

docker镜像就好比是一个目标,可以通过这个目标来创建容器服务,tomcat镜像==>run==>容器(提供服务器),通过这个镜像可以创建多个容器(最终服务运行或者项目运行就是在容器中的)。

  • 容器(container):

Docker利用容器技术,独立运行一个或者一组应用,通过镜像来创建的.
启动,停止,删除,基本命令
目前就可以把这个容器理解为就是一个简易的 Linux系统。

  • 仓库(repository):

仓库就是存放镜像的地方!

仓库分为公有仓库和私有仓库。(很类似git)

Docker Hub是国外的。

阿里云…都有容器服务器(配置镜像加速!)

2.安装Docker

  • 环境准备

Linux要求内核3.0以上

1
2
3
4
5
6
7
8
9
10
11
12
pi@raspbian:~$ uname -r
5.4.83-OPENFANS+20210102-v8
pi@raspbian:~$ cat /etc/os-release
PRETTY_NAME="Debian GNU/Linux 10 (buster)"
NAME="Debian GNU/Linux"
VERSION_ID="10"
VERSION="10 (buster)"
VERSION_CODENAME=buster
ID=debian
HOME_URL="https://www.debian.org/"
SUPPORT_URL="https://www.debian.org/support"
BUG_REPORT_URL="https://bugs.debian.org/"
  • 安装
1
帮助文档:https://docs.docker.com/engine/install/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#1.卸载旧版本
sudo apt-get install \
apt-transport-https \
ca-certificates \
curl \
gnupg-agent \
software-properties-common
#2.添加Docker的官方GPG密钥
curl -fsSL https://download.docker.com/linux/debian/gpg | sudo apt-key add -
sudo apt-key fingerprint 0EBFCD88
#3.设置镜像的仓库
sudo add-apt-repository \
"deb [arch=arm64] https://download.docker.com/linux/debian \
$(lsb_release -cs) \
stable"
#默认是从国外的,不推荐
#推荐使用国内的
sudo add-apt-repository \
"deb [arch=amd64] http://mirrors.aliyun.com/docker-ce/linux/debian \
$(lsb_release -cs) \
stable"
#更新yum软件包索引
yum makecache fast
#4.安装docker相关的 docker-ce 社区版 而ee是企业版
sudo apt-get install docker-ce docker-ce-cli containerd.io
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#5. 使用docker version查看是否按照成功
pi@raspbian:~$ docker version
Client: Docker Engine - Community
Version: 20.10.1
API version: 1.41
Go version: go1.13.15
Git commit: 831ebea
Built: Tue Dec 15 04:35:39 2020
OS/Arch: linux/arm64
Context: default
Experimental: true

Server: Docker Engine - Community
Engine:
Version: 20.10.1
API version: 1.41 (minimum version 1.12)
Go version: go1.13.15
Git commit: f001486
Built: Tue Dec 15 04:33:40 2020
OS/Arch: linux/arm64
Experimental: false
containerd:
Version: 1.4.3
GitCommit: 269548fa27e0089a8b8278fc4fc781d7f65a939b
runc:
Version: 1.0.0-rc92
GitCommit: ff819c7e9184c13b7c2607fe6c30ae19403a7aff
docker-init:
Version: 0.19.0
GitCommit: de40ad0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#6. 测试
pi@raspbian:~$ docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
256ab8fe8778: Already exists
Digest: sha256:31b9c7d48790f0d8c50ab433d9c3b7e17666d6993084c002c2ff1ca09b96391d
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.
(arm64v8)
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/
1
2
3
4
#8.查看一下下载的镜像
pi@raspbian:~$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
hello-world latest a29f45ccde2a 12 months ago 9.14kB

了解:卸载docker

1
2
3
4
5
#1. 卸载依赖
yum remove docker-ce docker-ce-cli containerd.io
#2. 删除资源
rm -rf /var/lib/docker
# /var/lib/docker 是docker的默认工作路径!
  • 阿里云镜像加速

1、登录阿里云找到容器服务

镜像加速器

2、找到镜像加速器

3、配置使用

1
2
3
4
5
6
7
8
sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF'
{
"registry-mirrors": ["https://mabtc1tu.mirror.aliyuncs.com"]
}
EOF
sudo systemctl daemon-reload
sudo systemctl restart docker

3.底层原理

  • Docker是怎么工作的?

Docker是一个Client-Server结构的系统,Docker的守护进程运行在主机上。通过Socket从客户端访问!

Docker-Server接收到Docker-Client的指令,就会执行这个命令!

  • 为什么Docker比Vm快

1、docker有着比虚拟机更少的抽象层。由于docker不需要Hypervisor实现硬件资源虚拟化,运行在docker容器上的程序直接使用的都是实际物理机的硬件资源。因此在CPU、内存利用率上docker将会在效率上有明显优势。

2、docker利用的是宿主机的内核,而不需要Guest OS。

GuestOS: VM(虚拟机)里的的系统(OS);

HostOS:物理机里的系统(OS);

因此,当新建一个 容器时,docker不需要和虚拟机一样重新加载一个操作系统内核。然而避免引导、加载操作系统内核是个比较费时费资源的过程,当新建一个虚拟机时,虚拟机软件需要加载GuestOS,整个新建过程是分钟级别的。而docker由于直接利用宿主机的操作系统,则省略了这个复杂的过程,因此新建一个docker容器只需要几秒钟。

三、Docker的常用命令

1.帮助命令

1
docker version #显示docker的版本信息。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
pi@raspbian:~$ docker version
Client: Docker Engine - Community
Version: 20.10.1
API version: 1.41
Go version: go1.13.15
Git commit: 831ebea
Built: Tue Dec 15 04:35:39 2020
OS/Arch: linux/arm64
Context: default
Experimental: true

Server: Docker Engine - Community
Engine:
Version: 20.10.1
API version: 1.41 (minimum version 1.12)
Go version: go1.13.15
Git commit: f001486
Built: Tue Dec 15 04:33:40 2020
OS/Arch: linux/arm64
Experimental: false
containerd:
Version: 1.4.3
GitCommit: 269548fa27e0089a8b8278fc4fc781d7f65a939b
runc:
Version: 1.0.0-rc92
GitCommit: ff819c7e9184c13b7c2607fe6c30ae19403a7aff
docker-init:
Version: 0.19.0
GitCommit: de40ad0
1
docker info #显示docker的系统信息,包括镜像和容器的数量
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
pi@raspbian:~$ docker info
Client:
Context: default
Debug Mode: false
Plugins:
app: Docker App (Docker Inc., v0.9.1-beta3)
buildx: Build with BuildKit (Docker Inc., v0.5.0-docker)

Server:
Containers: 6
Running: 0
Paused: 0
Stopped: 6
Images: 1
Server Version: 20.10.1
Storage Driver: overlay2
Backing Filesystem: extfs
Supports d_type: true
Native Overlay Diff: true
Logging Driver: json-file
Cgroup Driver: cgroupfs
Cgroup Version: 1
Plugins:
Volume: local
Network: bridge host ipvlan macvlan null overlay
Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk syslog
Swarm: inactive
Runtimes: io.containerd.runc.v2 io.containerd.runtime.v1.linux runc
Default Runtime: runc
Init Binary: docker-init
containerd version: 269548fa27e0089a8b8278fc4fc781d7f65a939b
runc version: ff819c7e9184c13b7c2607fe6c30ae19403a7aff
init version: de40ad0
Security Options:
seccomp
Profile: default
Kernel Version: 5.4.83-OPENFANS+20210102-v8
Operating System: Debian GNU/Linux 10 (buster)
OSType: linux
Architecture: aarch64
CPUs: 4
Total Memory: 1.805GiB
Name: raspbian
ID: EUR5:D5VI:P5K6:JRE3:4YIL:POWU:QAFS:YLRT:SFV6:6ZI5:EJPM:NSLC
Docker Root Dir: /var/lib/docker
Debug Mode: false
Username: baixfxyz
Registry: https://index.docker.io/v1/
Labels:
Experimental: false
Insecure Registries:
127.0.0.0/8
Registry Mirrors:
http://hub-mirror.c.163.com/
Live Restore Enabled: false

WARNING: No blkio weight support
WARNING: No blkio weight_device support
WARNING: bridge-nf-call-ip6tables is disabled
1
2
docker 命令 --help #帮助命令
docker --help
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
pi@raspbian:~$ docker --help

Usage: docker [OPTIONS] COMMAND

A self-sufficient runtime for containers

Options:
--config string Location of client config files (default "/home/pi/.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 "/home/pi/.docker/ca.pem")
--tlscert string Path to TLS certificate file (default "/home/pi/.docker/cert.pem")
--tlskey string Path to TLS key file (default "/home/pi/.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* Build with BuildKit (Docker Inc., v0.5.0-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
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

Run 'docker COMMAND --help' for more information on a command.

To get more help with docker, check out our guides at https://docs.docker.com/go/guides/
1
#帮助文档的地址:https://docs.docker.com/engine/reference/commandline/build/

2.镜像命令

1
2
3
4
docker images #查看所有本地主机上的镜像 可以使用docker image ls代替
docker search 搜索镜像
docker pull 下载镜像 docker image pull
docker rmi 删除镜像 docker image rm

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

1
2
3
pi@raspbian:~$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
hello-world latest a29f45ccde2a 12 months ago 9.14kB
1
2
3
4
5
6
# 解释
#REPOSITORY # 镜像的仓库源
#TAG # 镜像的标签
#IMAGE ID # 镜像的id
#CREATED # 镜像的创建时间
#SIZE # 镜像的大小
1
2
3
4
5
6
7
8
9
10
11
12
13
# 可选项
pi@raspbian:~$ docker images --help
Usage: docker images [OPTIONS] [REPOSITORY[:TAG]]

List images

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 # 只显示镜像的id
1
2
pi@raspbian:~$ docker images -aq #显示所有镜像的id
a29f45ccde2a

docker pull 下载镜像

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 下载镜像 docker pull 镜像名[:tag]

➜ ~ docker pull tomcat:8
8: Pulling from library/tomcat #如果不写tag,默认就是latest
90fe46dd8199: Already exists #分层下载: docker image 的核心 联合文件系统
35a4f1977689: Already exists
bbc37f14aded: Already exists
74e27dc593d4: Already exists
93a01fbfad7f: Already exists
1478df405869: Pull complete
64f0dd11682b: Pull complete
68ff4e050d11: Pull complete
f576086003cf: Pull complete
3b72593ce10e: Pull complete
Digest: sha256:0c6234e7ec9d10ab32c06423ab829b32e3183ba5bf2620ee66de866df640a027
# 签名 防伪
Status: Downloaded newer image for tomcat:8
docker.io/library/tomcat:8 #真实地址
#等价于
docker pull tomcat:8
docker pull docker.io/library/tomcat:8
1
2
3
4
5
6
7
8
9
10
11
pi@raspbian:~$ docker pull --help

Usage: docker pull [OPTIONS] NAME[:TAG|@DIGEST]

Pull an image or a repository from a registry

Options:
-a, --all-tags Download all tagged images in the repository
--disable-content-trust Skip image verification (default true)
--platform string Set platform if server is multi-platform capable
-q, --quiet Suppress verbose output

docker rmi 删除镜像

1
2
3
docker rmi -f 镜像id #删除指定的镜像
docker rmi -f 镜像id 镜像id 镜像id 镜像id#删除指定的镜像
docker rmi -f $(docker images -aq) #删除全部的镜像

3.容器命令

说明:我们有了镜像才可以创建容器,Linux,下载centos镜像来学习

1
2
3
4
5
6
7
docker run 镜像id 新建容器并启动
docker ps 列出所有运行的容器 docker container list
docker rm 容器id 删除指定容器
docker start 容器id #启动容器
docker restart容器id #重启容器
docker stop 容器id #停止当前正在运行的容器
docker kill 容器id #强制停止当前容器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
pi@raspbian:~$ 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.

新建容器并启动

1
2
3
4
5
6
7
8
9
10
11
docker run [可选参数] image | docker container run [可选参数] image
#参书说明
--name="Name" 容器名字 tomcat01 tomcat02 用来区分容器
-d 后台方式运行
-it 使用交互方式运行,进入容器查看内容
-p 指定容器的端口 -p 8080(宿主机):8080(容器)
-p ip:主机端口:容器端口
-p 主机端口:容器端口(常用)
-p 容器端口
容器端口
-P(大写) 随机指定端口
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 测试、启动并进入容器
pi@raspbian:~$ docker run -it centos /bin/bash
Unable to find image 'centos:latest' locally
latest: Pulling from library/centos
latest: Pulling from library/centos
333cbcae3fb8: Already exists
Digest: sha256:5528e8b1b1719d34604c87e11dcd1c0a20bedf46e83b5632cdeac91b8c04efc1
Status: Downloaded newer image for centos:latest
[root@0c96b8cf9bc2 /]# ls
bin dev etc home lib lib64 lost+found media mnt opt proc root run sbin srv sys tmp usr var
[root@0c96b8cf9bc2 /]# exit #从容器退回主机
exit
pi@raspbian:~$ ls
com.oray.sunlogin.client_10.0.2.24779_arm64.deb pifan_win10_vm Wallpapers '学习强国-raspberrypi ' 视频
git SunloginRemote 下载 文档 软件
libary ThunderNetwork 公共 桌面 音乐
Miniconda3-latest-Linux-armv7l.sh tmp.text 图片 模板
pi@raspbian:~$

列出所有运行的容器

1
2
3
4
5
#docker ps命令 #列出当前正在运行的容器
-a, --all Show all containers (default shows just running)
-n, --last int Show n last created containers (includes all states)
(default -1)
-q, --quiet Only display numeric IDs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
pi@raspbian:~$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
pi@raspbian:~$ docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
0c96b8cf9bc2 centos "/bin/bash" 3 minutes ago Exited (0) About a minute ago nervous_albattani
09bcaba4de1f hello-world "/hello" 40 minutes ago Exited (0) 40 minutes ago brave_khayyam
0eaf062ca9fb e86f991e5d10 "/docker-entrypoint.…" 5 days ago Exited (0) 5 days ago nginx-test
f31980e0ab6a e86f991e5d10 "/docker-entrypoint.…" 5 days ago Exited (0) 5 days ago agitated_merkle
792d5e8c7575 e86f991e5d10 "/docker-entrypoint.…" 5 days ago Exited (0) 5 days ago charming_galois
5d4de87f016f centos "/bin/bash" 5 days ago Exited (0) 5 days ago suspicious_johnson
76bd27490955 hello-world "/hello" 5 days ago Exited (0) 5 days ago funny_khayyam
pi@raspbian:~$ docker ps -aq
0c96b8cf9bc2
09bcaba4de1f
0eaf062ca9fb
f31980e0ab6a
792d5e8c7575
5d4de87f016f
76bd27490955

退出容器

1
2
exit #容器直接退出
ctrl +P +Q #容器不停止退出

删除容器

1
2
3
docker rm 容器id #删除指定的容器,不能删除正在运行的容器,如果要强制删除 rm -rf
docker rm -f $(docker ps -aq) #删除指定的容器
docker ps -a -q|xargs docker rm #删除所有的容器

启动和停止容器的操作

1
2
3
4
docker start 容器id #启动容器
docker restart 容器id #重启容器
docker stop 容器id #停止当前正在运行的容器
docker kill 容器id #强制停止当前容器

4.常用其他命令

后台启动命令

1
# 命令 docker run -d 镜像名
1
2
3
4
pi@raspbian:~$ docker run -d centos
e6b768a79f51e29c9a8ef5379abc7a273c706a2550f771fd4dd4c744dd247fb2
pi@raspbian:~$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
1
2
3
4
5
6
# 问题docker ps. 发现centos 停止了
# 退出原因
# 1、docker容器运行必须有一个前台进程, 如果没有前台进程执行,容器认为空闲,就会自行退出
# 2、容器运行的命令如果不是那些一直挂起的命令( 运行top,tail、循环等),就是会自动退出
# 3、这个是 docker 的机制问题
# nginx,容器启动后,发现自己没有提供服务,就会立刻停止,就是没有程序了

查看日志

1
2
3
4
5
6
7
8
9
10
11
docker logs --help
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:37) or
relative (e.g. 42m for 42 minutes)
* --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:37)
or relative (e.g. 42m for 42 minutes)
1
2
3
4
5
6
7
8
pi@raspbian:~$ docker run -d centos /bin/sh -c "while true;do echo 6666;sleep 1;done"
f4311e01d77805cd82e583a75cf96e117fac719cf64ace3919158b9f6e3f8f5f
#模拟日志
#显示日志
-tf #显示日志信息(一直更新)
--tail number #需要显示日志条数
docker logs -t --tail n 容器id #查看n行日志
docker logs -ft 容器id #跟着日志

查看容器中进程信息 ps

1
docker top 容器id
1
2
3
4
5
6
7
pi@raspbian:~$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
f4311e01d778 centos "/bin/sh -c 'while t…" 9 seconds ago Up 5 seconds trusting_curie
pi@raspbian:~$ docker top f4311e01d778
UID PID PPID C STIME TTY TIME CMD
root 30484 30450 0 22:25 ? 00:00:00 /bin/sh -c while true;do echo 6666;sleep 1;done
root 32658 30484 0 22:27 ? 00:00:00 /usr/bin/coreutils --coreutils-prog-shebang=sleep /usr/bin/sleep 1

查看镜像的元数据

1
2
# 命令
docker inspect 容器id
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
#测试
pi@raspbian:~$ docker inspect f4311e01d778
[
{
"Id": "f4311e01d77805cd82e583a75cf96e117fac719cf64ace3919158b9f6e3f8f5f",
"Created": "2021-01-17T14:25:35.710610691Z",
"Path": "/bin/sh",
"Args": [
"-c",
"while true;do echo 6666;sleep 1;done"
],
"State": {
"Status": "running",
"Running": true,
"Paused": false,
"Restarting": false,
"OOMKilled": false,
"Dead": false,
"Pid": 30484,
"ExitCode": 0,
"Error": "",
"StartedAt": "2021-01-17T14:25:38.846444708Z",
"FinishedAt": "0001-01-01T00:00:00Z"
},
"Image": "sha256:a0477e85b8aebf57d58bfa74a6598eccfd3fcc43a78c8e29c380cde2e7300a1b",
"ResolvConfPath": "/var/lib/docker/containers/f4311e01d77805cd82e583a75cf96e117fac719cf64ace3919158b9f6e3f8f5f/resolv.conf",
"HostnamePath": "/var/lib/docker/containers/f4311e01d77805cd82e583a75cf96e117fac719cf64ace3919158b9f6e3f8f5f/hostname",
"HostsPath": "/var/lib/docker/containers/f4311e01d77805cd82e583a75cf96e117fac719cf64ace3919158b9f6e3f8f5f/hosts",
"LogPath": "/var/lib/docker/containers/f4311e01d77805cd82e583a75cf96e117fac719cf64ace3919158b9f6e3f8f5f/f4311e01d77805cd82e583a75cf96e117fac719cf64ace3919158b9f6e3f8f5f-json.log",
"Name": "/trusting_curie",
"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/f3f69aeb9705b9bc24f209af81cc90657c4c2eee115d3c9d53fd0c67dc661d9d-init/diff:/var/lib/docker/overlay2/c59748945340c6610a4112c42f1f9929a4a1f5b8ae5ab50084cbc3ad12951286/diff",
"MergedDir": "/var/lib/docker/overlay2/f3f69aeb9705b9bc24f209af81cc90657c4c2eee115d3c9d53fd0c67dc661d9d/merged",
"UpperDir": "/var/lib/docker/overlay2/f3f69aeb9705b9bc24f209af81cc90657c4c2eee115d3c9d53fd0c67dc661d9d/diff",
"WorkDir": "/var/lib/docker/overlay2/f3f69aeb9705b9bc24f209af81cc90657c4c2eee115d3c9d53fd0c67dc661d9d/work"
},
"Name": "overlay2"
},
"Mounts": [],
"Config": {
"Hostname": "f4311e01d778",
"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 6666;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": "5d580bec850d90d77a2f36592b1d15d4e56acbb7065320914677090968726a7b",
"HairpinMode": false,
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"Ports": {},
"SandboxKey": "/var/run/docker/netns/5d580bec850d",
"SecondaryIPAddresses": null,
"SecondaryIPv6Addresses": null,
"EndpointID": "6d7d115f815c56f29df5333be2296a0cfbb541227396fad448bca0f711e5ca9b",
"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": "33604500820e5692b82d7a1fff29f5f6586d572f6db2aef1440d0237a81a2b1e",
"EndpointID": "6d7d115f815c56f29df5333be2296a0cfbb541227396fad448bca0f711e5ca9b",
"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
2
3
4
5
6
7
8
9
10
11
# 我们通常容器都是使用后台方式运行的,需要进入容器,修改一些配置
# 命令
docker exec -it 容器id bin/bash
#测试
pi@raspbian:~$ docker exec -it f4311e01d778 bin/bash
[root@f4311e01d778 /]# ps
PID TTY TIME CMD
368 pts/0 00:00:00 bash
396 pts/0 00:00:00 ps
[root@f4311e01d778 /]# exit
exit
1
2
3
4
5
6
7
8
9
10
11
# 方式二
docker attach 容器id
#测试
pi@raspbian:~$ docker attach f4311e01d778
6666
6666
6666
6666
6666
6666
……
1
2
3
区别
#docker exec #进入当前容器后开启一个新的终端,可以在里面操作。(常用)
#docker attach # 进入容器正在执行的终端

从容器内拷贝到主机上

1
2
docker cp 容器id:容器内路径 主机目的路径
#进入docker容器内部
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
pi@raspbian:~$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
e7c4a115ff36 centos "/bin/bash" 2 minutes ago Up 2 minutes awesome_tereshkova
pi@raspbian:~$ docker exec -it e7c4a115ff36 /bin/bash
[root@e7c4a115ff36 /]# cd
[root@e7c4a115ff36 ~]# ls
anaconda-ks.cfg anaconda-post.log original-ks.cfg
[root@e7c4a115ff36 ~]# touch zsh
[root@e7c4a115ff36 ~]# echo "shadiao" > zsh
[root@e7c4a115ff36 ~]# cat zsh
shadiao
[root@e7c4a115ff36 ~]# docker cp e7c4a115ff36:~/zsh /
bash: docker: command not found
[root@e7c4a115ff36 ~]# pwd
/root
[root@e7c4a115ff36 ~]#
pi@raspbian:~$ docker cp e7c4a115ff36:/root/zsh /home/pi
pi@raspbian:~$ ls
com.oray.sunlogin.client_10.0.2.24779_arm64.deb pifan_win10_vm Wallpapers 图片 模板
git SunloginRemote zsh '学习强国-raspberrypi ' 视频
libary ThunderNetwork 下载 文档 软件
Miniconda3-latest-Linux-armv7l.sh tmp.text 公共 桌面 音乐
pi@raspbian:~$ cat zsh
shadiao

学习方式:将所有笔记敲一遍,自己记录笔记!

四、小结

Docker的所有命令

Docker命令帮助文档(重要)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
attach Attach local standard input, output, and error streams to a
running container
#当前shell下 attach连接指定运行的镜像
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 #创建一个新的容器
diff Inspect changes to files or directories on a container's
filesystem #查看docker容器的变化
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 #导出容器文件系统作
为一个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包中导入内容创建一个文件系统镜像
info Display system-wide information # 显示全系统信息
inspect Return low-level information on Docker objects #查看容器详细信息
kill Kill one or more running containers # kill指定docker容器
load Load an image from a tar archive or STDIN #从一个tar包或标准输入中加载
一个镜像[对应save]
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

作业练习

三个作业:作业1告诉我们暴露端口的重要性;作业2告诉我们进入容器的重要性;作业3告诉我们查看当前容器状态的重要性,如何修改容器运行的环境。

作业1:Docker 安装Nginx

1
2
3
4
5
6
#1. 搜索镜像 search 建议大家去docker搜索,可以看到帮助文档
#2. 拉取镜像 pull
#3. 运行测试
# -d 后台运行
# --name 给容器命名
# -p 宿主机端口:容器内部端口
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
pi@raspbian:~$ docker search -f  stars=5000 nginx
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
nginx Official build of Nginx. 14291 [OK]
pi@raspbian:~$ docker pull nginx
Using default tag: latest
latest: Pulling from library/nginx
f8be76fcf206: Pull complete
56d3a31c1999: Pull complete
61e3132252c9: Pull complete
703916d761e9: Pull complete
53e819da52d9: Pull complete
Digest: sha256:10b8cc432d56da8b61b070f4c7d2543a9ed17c2b23010b43af434fd40e2ca4aa
Status: Downloaded newer image for nginx:latest
docker.io/library/nginx:latest
pi@raspbian:~$ docker run -d --name nginx01 -p 8088:80 nginx
c86f35254ea1c2abad877c4942217d55d7e582b382a2510e6d4a5ac8b1118f0c
pi@raspbian:~$ curl localhost:8088
<!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>

端口暴露示意图:

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

作业2:docker 来装一个tomcat

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 官方的使用
docker run -it --rm tomcat:9.0
# 之前的启动都是后台,停止了容器,容器还是可以查到
# docker run -it --rm image 一般是用来测试,用完就删除(暂时不建议)
--rm Automatically remove the container when it exits
#下载
docker pull tomcat
#启动运行
docker run -d -p 8080:8080 --name tomcat01 tomcat
#测试访问有没有问题
curl localhost:8080
#进入容器
➜ ~ docker ps
CONTAINER ID IMAGE COMMAND CREATED
STATUS PORTS NAMES
db09851cf82e tomcat "catalina.sh run" 28 seconds ago
Up 27 seconds 0.0.0.0:8080->8080/tcp tomcat01
➜ ~ docker exec -it db09851cf82e /bin/bash
root@db09851cf82e:/usr/local/tomcat#
# 发现问题:1、linux命令少了。 2.没有webapps
# 阿里云镜像(阉割版),它为保证最小镜像,将不必要的都剔除了→保证最小可运行环境!

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

作业3:部署es+kibana

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# es 暴露的端口很多!
# es 十分耗内存
# es 的数据一般需要放置到安全目录!挂载
# --net somenetwork ? 网络配置
# 下载启动elasticsearch(Docker一步搞定)
docker run -d --name elasticsearch -p 9200:9200 -p 9300:9300 -e
"discovery.type=single-node" elasticsearch:7.6.2
# 测试一下es是否成功启动
➜ ~ curl localhost:9200
{
"name" : "d73ad2f22dd3",
"cluster_name" : "docker-cluster",
"cluster_uuid" : "atFKgANxS8CzgIyCB8PGxA",
"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"
}
# 查看docker容器使用内存情况(每秒刷新,也挺耗内存的一个命令)
➜ ~ docker stats
#关闭,添加内存的限制,修改配置文件 -e 环境配置修改
➜ ~ docker rm -f d73ad2f22dd3
➜ ~ docker run -d --name elasticsearch -p 9200:9200 -p 9300:9300 -e
"discovery.type=single-node" -e ES_JAVA_OPTS="-Xms64m -Xmx512m"
elasticsearch:7.6.2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
➜ ~ curl localhost:9200
{
"name" : "b72c9847ec48",
"cluster_name" : "docker-cluster",
"cluster_uuid" : "yNAK0EORSvq3Wtaqe2QqAg",
"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?思考网络如何才能连接。

五、Docker可视化

什么是portainer?

Docker图形化界面管理工具!提供一个后台面板供我们操作!

1
2
3
# 运行如下命令即可 打开可视化服务
docker run -d -p 8080:9000 \
--restart=always -v /var/run/docker.sock:/var/run/docker.sock --privileged=true portainer/portainer

访问:http://ip:8080/




六、Docker镜像讲解

镜像是什么

Docker镜像加载原理

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

  • UnionFs (联合文件系统)

我们下载的时候看到一层层的下载就是这个。

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

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

  • Docker镜像加载原理

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

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

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

平时我们安装进虚拟机的CentOS都是好几个G,为什么Docker这里才200M?

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

虚拟机是分钟级别,容器是秒级!

分层理解

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

1
2
3
4
5
6
7
8
9
10
11
12
pi@raspbian:~$ docker pull redis
Using default tag: latest
latest: Pulling from library/redis
f8be76fcf206: Already exists
10ca116bc5c3: Pull complete
8aa044f70158: Pull complete
c9ee276a1a0f: Pull complete
8954c3738673: Pull complete
082886f56848: Pull complete
Digest: sha256:0f97c1c9daf5b69b93390ccbe8d3e2971617ec4801fd0882c72bf7cad3a13494
Status: Downloaded newer image for redis:latest
docker.io/library/redis:latest

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

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
pi@raspbian:~$ docker image inspect redis
[
{
"Id": "sha256:aab98baa141a5336da8748325b8ef41bb387276bc8215b32070f38c27de20733",
"RepoTags": [
"redis:latest"
],
"RepoDigests": [
"redis@sha256:0f97c1c9daf5b69b93390ccbe8d3e2971617ec4801fd0882c72bf7cad3a13494"
],
"Parent": "",
"Comment": "",
"Created": "2021-01-13T06:05:21.619263128Z",
"Container": "7c9310c3295be6022a73a546d41a7ad89fa09e8502ee43cc0d7df2c9681e2b44",
"ContainerConfig": {
"Hostname": "7c9310c3295b",
"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:047d03cf5cdd81af3dd04d9ca945f956afec58fab4028bbd4cf24f561eae8c20",
"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:047d03cf5cdd81af3dd04d9ca945f956afec58fab4028bbd4cf24f561eae8c20",
"Volumes": {
"/data": {}
},
"WorkingDir": "/data",
"Entrypoint": [
"docker-entrypoint.sh"
],
"OnBuild": null,
"Labels": null
},
"Architecture": "arm64",
"Os": "linux",
"Size": 98563933,
"VirtualSize": 98563933,
"GraphDriver": {
"Data": {
"LowerDir": "/var/lib/docker/overlay2/8956154e500c52ffc3685660afda4a8cc58237d452eacb0cebabab49ed0b8081/diff:/var/lib/docker/overlay2/957892645b91290509180c7f3619c89ea140ee71f38a9bb6b00098784f3ff640/diff:/var/lib/docker/overlay2/0ea446714060db67ba0c18c012a8234a3015314e1a73ed4a9f9963a0d3635063/diff:/var/lib/docker/overlay2/aa9cc057f7ae7bb7655396dbd69b9c7c22f3124695f1e8640a7554896e9ecd6a/diff:/var/lib/docker/overlay2/843fddc80540357e3e639e8cb7cccbb9512354b70cfe10cee3ed3123dbaed53a/diff",
"MergedDir": "/var/lib/docker/overlay2/09b7e18ab5dd846f2c0c7a34930d87063daa356798e6716902bd98c8a96f1906/merged",
"UpperDir": "/var/lib/docker/overlay2/09b7e18ab5dd846f2c0c7a34930d87063daa356798e6716902bd98c8a96f1906/diff",
"WorkDir": "/var/lib/docker/overlay2/09b7e18ab5dd846f2c0c7a34930d87063daa356798e6716902bd98c8a96f1906/work"
},
"Name": "overlay2"
},
"RootFS": {
"Type": "layers",
"Layers": [
"sha256:5c4f3d84264daaff85b2f005a4c295693e48c0e9c3ae76e64a7f3914e94e583b",
"sha256:3a812f593e11f6ad98eae74e75a9fe026265d913e9cddc2478e966169e6e9040",
"sha256:34ec83b8d3276d5396b2b987f169e3ee22c25c21a701c2228cb7cbcb09f33ee6",
"sha256:4bf30474a6f6b17a5aa86cd8578a8bbd1ab6507bb1ca0096498811647dc8accc",
"sha256:b195ac169cf01ef7e5342d1cdbe506123584bcf2a3c1da48401adf92c2dfaecd",
"sha256:693285e577b858ea1cd2ad86bfaca34eac441f2be427131c5e676ad3d69cb5ef"
]
},
"Metadata": {
"LastTagTime": "0001-01-01T00:00:00Z"
}
}
]

理解:

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

举一个简单的例子,假如基于 Ubuntu Linux16.04创建一个新的镜像,这就是新镜像的第一层;如果在该镜像中添加 Python包,就会在基础镜像层之上创建第二个镜像层;如果继续添加一个安全补丁,就会创健第三个镜像层该像当前已经包含3个镜像层,如下图所示(这只是一个用于演示的很简单的例子)。

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

上图中的镜像层跟之前图中的略有区別,主要目的是便于展示文件。

下图中展示了一个稍微复杂的三层镜像,在外部看来整个镜像只有6个文件,这是因为最上层中的文件7是文件5的一个更新版。

这种情況下,上层镜像层中的文件覆盖了底层镜像层中的文件。这样就使得文件的更新版本作为一个新镜像层添加到镜像当中。

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

Linux上可用的存储引撃有AUFS、 Overlay2、 Device Mapper、Btrfs以及ZFS。顾名思义,每种存储引擎都基于 Linux中对应的文件系统或者块设备技术,井且每种存储引擎都有其独有的性能特点。

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

下图展示了与系统显示相同的三层镜像。所有镜像层堆并合井,对外提供统一的视图。

特点

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

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

如何提交一个镜像

commit镜像

1
2
3
4
# 命令和git原理类似
docker commit 提交容器成为一个新的副本

docker commit -m="描述信息" -a="作者" 容器id 目标镜像名:[TAG]

实战测试

1
2
3
4
5
6
7
pi@raspbian:~$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
redis latest aab98baa141a 4 days ago 98.6MB
tomcat latest 688bd6a32df3 5 days ago 639MB
nginx latest 9b016c5aa4e8 5 days ago 126MB
centos latest a0477e85b8ae 5 weeks ago 249MB
hello-world latest a29f45ccde2a 12 months ago 9.14kB
1
2
# 1、启动一个默认的tomcat
docker run -it -p 8080:8080 tomcat /bin/bash
1
2
pi@raspbian:~$ curl localhost:8080
curl: (56) Recv failure: Connection reset by peer
1
# 2、发现这个默认的tomcat 是没有webapps应用,官方的镜像默认webapps下面是没有文件的!拷贝文件进去
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
pi@raspbian:~$ docker run -it -p 8080:8080 tomcat /bin/bash
root@31df0aa6fb9e:/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@31df0aa6fb9e:/usr/local/tomcat# cd webapps
root@31df0aa6fb9e:/usr/local/tomcat/webapps# ls
root@31df0aa6fb9e:/usr/local/tomcat/webapps# cd ..
root@31df0aa6fb9e:/usr/local/tomcat# cp -r webapps.dist/* webapps
root@31df0aa6fb9e:/usr/local/tomcat# exit
exit
pi@raspbian:~$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
pi@raspbian:~$ docker run -d -p 8080:8080 tomcat
52a80307a7fcea44519a75a452369adbdb53cc91b35cc6d0e614f02b2c23db4c
pi@raspbian:~$ curl localhost:8080
<!doctype html><html lang="en"><head><title>HTTP Status 404 – Not Found</title><style type="text/css">body {font-family:Tahoma,Arial,sans-serif;} h1, h2, h3, b {color:white;background-color:#525D76;} h1 {font-size:22px;} h2 {font-size:16px;} h3 {font-size:14px;} p {font-size:12px;} a {color:black;} .line {height:1px;background-color:#525D76;border:none;}</style></head><body><h1>HTTP Status 404 – Not Found</h1><hr class="line" /><p><b>Type</b> Status Report</p><p><b>Description</b> The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.</p><hr class="line" /><h3>Apache Tomcat/9.0.41</h3></body></html>
1
2
# 3、将操作过的容器通过commit调教为一个镜像!我们以后就使用我们修改过的镜像即可,这就是我们自己的一个修改的镜像。
docker commit -m="描述信息" -a="作者" 容器id 目标镜像名:[TAG]
1
2
3
4
5
6
7
8
9
10
pi@raspbian:~$ docker commit -m="kuangshen666" -a="baixf" 52a80307a7fc tomcat:1.0
sha256:83ac74acd5e011fa39241a5d1c4c43ad65cc9b6a68d5cbbac96db14917e6e000
pi@raspbian:~$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
tomcat 1.0 83ac74acd5e0 17 seconds ago 639MB
redis latest aab98baa141a 4 days ago 98.6MB
tomcat latest 688bd6a32df3 5 days ago 639MB
nginx latest 9b016c5aa4e8 6 days ago 126MB
centos latest a0477e85b8ae 5 weeks ago 249MB
hello-world latest a29f45ccde2a 12 months ago 9.14kB

如果你想要保存当前容器的状态,就可以通过commit来提交,获得一个镜像,就好比我们我们使用虚拟机的快照

参考


Docker入门
https://blog.baixf.tk/2021/01/18/Docker/Docker入门/
作者
白小飞
发布于
2021年1月18日
许可协议