📖概述

故事

2010年,几个搞 IT 的年轻人,在美国旧金山成立了一家名叫 dotCloud 的公司。dotCloud 的平台即服务(Platform-as-a-Service)提供商。底层技术上,dotCloud 平台利用了LinuxLXC 容器技术。为了方便创建和管理这些容器,dotCloud 基于 Google 公司推出的 Go 语言开发了一套内部工具,之后被命名为 DockerDocker 就是这样诞生的。

2013年的后端技术领域已经太久没有出现让人振奋的东西了。当然Docker在发行之后也没用引起行业的关注。在开源之后才爆火。

Docker定义容器技术标砖使得容器技术的落地变得十分简单,应用可以稳定便携的运行在容器中。

特点

  • 更快速的应用交付和部署
  • 更便捷的升级和扩缩容
  • 更高效的计算资源利用
  • 更简单的系统运维

架构

镜像(image): 相当于一个模板,可以通过这个模板来创建容器服务

容器(container): 独立运行一个或者一个组应用

仓库(repository): 存放镜像的地方


🔨安装

官方文档

CentOS 7安装:https://docs.docker.com/engine/install/centos/

卸载旧版本

1
2
3
4
5
6
7
8
$ sudo yum remove docker \
docker-client \
docker-client-latest \
docker-common \
docker-latest \
docker-latest-logrotate \
docker-logrotate \
docker-engine

设置存储库

1
$ sudo yum install -y yum-utils

更换镜像源

1
$ sudo yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo

更新YUM包

更新YUM索引

1
2
$ sudo yum update
$ sudo yum makecache fast

安装docker引擎和容器

1
$ sudo yum install docker-ce docker-ce-cli containerd.io

启动Docker并测试hello-world

1
2
$ sudo systemctl start docker
$ sudo docker run hello-world

卸载方式

1
2
$ sudo yum remove docker-ce docker-ce-cli containerd.io
$ sudo rm -rf /var/lib/docker

镜像加速

1️⃣使用阿里镜像加速器

2️⃣使用中科大或者网易镜像加速

1
2
3
4
5
6
7
8
9
10
11
12
# 添加daemon.json
$ touch /etc/docker/daemon.json

# 写入内容并保存
# 科大源: https://docker.mirrors.ustc.edu.cn/
# 网易源:http://hub-mirror.c.163.com
{
"registry-mirrors": ["https://docker.mirrors.ustc.edu.cn/"]
}

# 重启Docker
$ sudo systemctl restart docker

🚀原理

docker run的执行流程

Docker的工作

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

为什么Docker比VM快?

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

2、Docker利用的是宿主机的内核,而不需要Guest OS。因此创建一个容器时,不需要和虚拟机一样重新加载一个操作系统内核。从而避免引寻、加载操作系统内核返回时耗时耗资源的过程,当新建一个虚拟机时,虚拟机软件需要加载Guest OS,返回新建过程是分钟级别的。而新建一个Docker容器只需要几秒钟。

3、Docker与VM相比:

  • Docker灵活,VM笨重
  • Docker存储的镜像小,便于存储和传输,VM镜像庞大

🔰命令

🌐官方文档

Command-line reference:https://docs.docker.com/reference/


1️⃣帮助命令

1
2
3
$ docker version    # 显示Docker版本信息
$ docker info # 显示Docker系统信息
$ docker --help # Docker命令帮助信息

2️⃣镜像命令

查看镜像

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$ docker images

# 可选项
-a, --all # 列出所有镜像
--digests # 显示镜像的摘要信息
-q, --quiet # 只显示镜像的ID

# 运行
[root@parak khighness]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
hello-world latest bf756fb1ae65 11 months ago 13.3kB
# 解释
REPOSITORY 镜像的仓库源
TAG 镜像的标签
IMAGE ID 镜像的ID
CREATED 镜像的创建时间
SIZE 镜像的大小

搜索镜像

1
2
3
4
$ docker search <IMAGE>

# 可选项
--filter=STARS=1000 # 镜像的STARS大于1000

下载镜像

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
$ docker pull <IMAGE>
$ docker pull .io/library/mysql:latest

# 如果不写tag,默认就是最新的

# 指定版本下载
[root@parak khighness]# docker pull mysql:8.0.20
8.0.20: Pulling from library/mysql # 分层下载
8559a31e96f4: Pull complete
d51ce1c2e575: Pull complete
c2344adc4858: Pull complete
fcf3ceff18fc: Pull complete
16da0c38dc5b: Pull complete
b905d1797e97: Pull complete
4b50d1c6b05c: Pull complete
c75914a65ca2: Pull complete
1ae8042bdd09: Pull complete
453ac13c00a3: Pull complete
9e680cd72f08: Pull complete
a6b5dc864b6c: Pull complete
Digest: sha256:8b7b328a7ff6de46ef96bcf83af048cb00a1c86282bfca0cb119c84568b4caf6
Status: Downloaded newer image for mysql:8.0.20
docker.io/library/mysql:8.0.20

删除镜像

1
2
3
4
# 通过镜像ID删除
$ docker rmi -f <IMAGE ID> ...
# 删除所有镜像
$ docker rmi -f $(docker images -aq)0

3️⃣容器命令

下载一个CentOS镜像来测试学(套)习(娃)

1
2
3
4
5
6
7
[root@parak khighness]# docker pull centos
Using default tag: latest
latest: Pulling from library/centos
3c72a8ed6814: Pull complete
Digest: sha256:76d24f3ba3317fa945743bb3746fbaf3a0b752f10b10376960de01da70685fbd
Status: Downloaded newer image for centos:latest
docker.io/library/centos:latest

新建容器并启动

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
$ docker run [可选参数] <IMAGE>

# 参数说明
--name="NAME" 容器名字,用于区分容器
-d 后台方式运行
-it 使用交互方式运行,进如容器查看内容
-p 指定容器端口 -p 8080:8080
-p ip:主机端口:容器端口
-p 主机端口:容器端口
-p 容器端口

# 测试,启动并进入容器
[root@parak khighness]# docker run -it centos /bin/bash
[root@e4efa1c507b8 /]# ls
bin dev etc home lib lib64 lost+found media mnt opt proc root run sbin srv sys tmp usr var
# 从容器中退回主机
[root@e4efa1c507b8 /]# exit
exit
[root@parak khighness]# ls
公共 模板 视频 图片 文档 下载 音乐 桌面

查看容器

1
2
3
4
$ docker ps  # 显示所有正在运行的容器
-a # 显示所有正在运行的容器+历史运行过的容器
-n=? # 显示最近创建的n个容器
-q # 只显示容器的编号

退出容器

1
$ exit        

删除容器

1
2
3
$ docker rm <Container ID/NAME>    # 删除指定的容器,不能删除只在运行的容器
$ docker rm -f $(docker ps -aq) # 删除所有的容器
$ docker ps -a -q|xargs docker rm # 删除所有的容器

容器操作

1
2
3
4
$ docker start   <Container ID/NAME>  # 启动容器 
$ docker restart <Container ID/NAME> # 重启容器
$ docker stop <Container ID/NAME> # 停止当前正在运行的容器
$ docker kill <Container ID/NAME> # 强制停止当前容器

查看日志

1
$ docker logs -tf --tail <n> <Container ID/NAME> # 显示指定行数的日志

查看容器中进程信息

1
$ docker top <Container ID/NAME>

查看镜像的元数据

1
$ docker inspect

进入当前正在运行的容器

1
2
3
4
5
6
7
$ docker exec -it <Container ID> bashShell  
# 进入容器后开启一个新的终端,可以在里面操作;
# exec之后不会终结当前容器进程

$ docker attach <Container ID>
# 进入容器中正在执行的终端,不会启动新的进程
# exec之后终结当前容器进程

从容器拷贝新的东西到主机

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 开启CentOS容器
[root@parak khighness]# docker start b9ace468ea7d
b9ace468ea7d
# 进入CentOS容器
[root@parak khighness]# docker attach b9ace468ea7d
# 创建文件夹和文件
[root@b9ace468ea7d /]# cd home/
[root@b9ace468ea7d home]# mkdir document
[root@b9ace468ea7d home]# vi K1.java
# 退出容器
[root@b9ace468ea7d document]# exit
exit
# 将容器文件复制到主机上
[root@parak khighness]# docker cp b9ace468ea7d:/home/document/K1.java document/
[root@parak khighness]# cd document/
[root@parak document]# ll
总用量 4
-rw-r--r--. 1 root root 186 12月 5 11:33 K1.java

🔱练习


🌠 安装Nginx

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
# 搜索镜像
[root@parak khighness]# docker search nginx
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
nginx Official build of Nginx. 14063 [OK]
jwilder/nginx-proxy Automated Nginx reverse proxy for docker con… 1912 [OK]
richarvey/nginx-php-fpm Container running Nginx + PHP-FPM capable of… 795 [OK]
linuxserver/nginx An Nginx container, brought to you by LinuxS… 131
jc21/nginx-proxy-manager Docker container for managing Nginx proxy ho… 115
tiangolo/nginx-rtmp Docker image with Nginx using the nginx-rtmp… 105 [OK]
bitnami/nginx Bitnami nginx Docker Image 90 [OK]
alfg/nginx-rtmp NGINX, nginx-rtmp-module and FFmpeg from sou… 80 [OK]
jlesage/nginx-proxy-manager Docker container for Nginx Proxy Manager 72 [OK]
nginxdemos/hello NGINX webserver that serves a simple page co… 63 [OK]
nginx/nginx-ingress NGINX Ingress Controller for Kubernetes 45
privatebin/nginx-fpm-alpine PrivateBin running on an Nginx, php-fpm & Al… 42 [OK]
nginxinc/nginx-unprivileged Unprivileged NGINX Dockerfiles 21
schmunk42/nginx-redirect A very simple container to redirect HTTP tra… 19 [OK]
nginx/nginx-prometheus-exporter NGINX Prometheus Exporter 15
centos/nginx-112-centos7 Platform for running nginx 1.12 or building … 15
staticfloat/nginx-certbot Opinionated setup for automatic TLS certs lo… 14 [OK]
raulr/nginx-wordpress Nginx front-end for the official wordpress:f… 13 [OK]
centos/nginx-18-centos7 Platform for running nginx 1.8 or building n… 13
mailu/nginx Mailu nginx frontend 8 [OK]
bitwarden/nginx The Bitwarden nginx web server acting as a r… 7
flashspys/nginx-static Super Lightweight Nginx Image 7 [OK]
bitnami/nginx-ingress-controller Bitnami Docker Image for NGINX Ingress Contr… 6 [OK]
wodby/nginx Generic nginx 1 [OK]
ansibleplaybookbundle/nginx-apb An APB to deploy NGINX 1 [OK]
# 下载镜像
[root@parak khighness]# docker pull nginx
Using default tag: latest
latest: Pulling from library/nginx
852e50cd189d: Pull complete
571d7e852307: Pull complete
addb10abd9cb: Pull complete
d20aa7ccdb77: Pull complete
8b03f1e11359: Pull complete
Digest: sha256:6b1daa9462046581ac15be20277a7c75476283f969cb3a61c8725ec38d3b01c3
Status: Downloaded newer image for nginx:latest
docker.io/library/nginx:latest
# 查看镜像
[root@parak khighness]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
nginx latest bc9a0695f571 10 days ago 133MB
centos latest 0d120b6ccaa8 3 months ago 215MB
mysql 8.0.20 be0dbf01a0f3 5 months ago 541MB
hello-world latest bf756fb1ae65 11 months ago 13.3kB
# 后台启动80端口nginx,对外开放3355端口
[root@parak khighness]# docker run -d --name nginx1 -p 3355:80 nginx
b6072408f44cd78594f01c95bc63da6baf911f74d62bf232ec42c1cd8b08b4d0
[root@parak khighness]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
b6072408f44c nginx "/docker-entrypoint.…" 6 seconds ago Up 4 seconds 0.0.0.0:3355->80/tcp nginx1
# 测试,可以用ip:3355在浏览器访问
[root@parak khighness]# curl localhost:3355
<!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>

🌠 安装Tomcat

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
[root@parak khighness]# docker pull tomcat:9.0
9.0: Pulling from library/tomcat
756975cb9c7e: Pull complete
d77915b4e630: Pull complete
5f37a0a41b6b: Pull complete
96b2c1e36db5: Pull complete
27a2d52b526e: Pull complete
a867dba77389: Pull complete
0939c055fb79: Pull complete
0b0694ce0ae2: Pull complete
81a5f8099e05: Pull complete
c3d7917d545e: Pull complete
Digest: sha256:a319b10d8729817c7ce0bcc2343a6f97711c7870395019340d96b6aafd6ccbea
Status: Downloaded newer image for tomcat:9.0
docker.io/library/tomcat:9.0

[root@parak khighness]# docker run -d -p 3355:8080 --name tomcat1 tomcat
48c7de09007af158b13a9bef1f2d2b77bed0c4bc2f93a4887eac427911118a9b
[root@parak khighness]# docker exec -it tomcat1 /bin/bash
root@48c7de09007a:/usr/local/tomcat# ls -al
total 128
drwxr-xr-x. 1 root root 30 Nov 19 06:16 .
drwxr-xr-x. 1 root root 20 Nov 19 06:12 ..
-rw-r--r--. 1 root root 18982 Nov 12 15:41 BUILDING.txt
-rw-r--r--. 1 root root 5409 Nov 12 15:41 CONTRIBUTING.md
-rw-r--r--. 1 root root 57092 Nov 12 15:41 LICENSE
-rw-r--r--. 1 root root 2333 Nov 12 15:41 NOTICE
-rw-r--r--. 1 root root 3257 Nov 12 15:41 README.md
-rw-r--r--. 1 root root 6898 Nov 12 15:41 RELEASE-NOTES
-rw-r--r--. 1 root root 16507 Nov 12 15:41 RUNNING.txt
drwxr-xr-x. 2 root root 4096 Nov 19 06:16 bin
drwxr-xr-x. 1 root root 22 Dec 5 13:15 conf
drwxr-xr-x. 2 root root 4096 Nov 19 06:16 lib
drwxrwxrwx. 1 root root 177 Dec 5 13:15 logs
drwxr-xr-x. 2 root root 134 Nov 19 06:16 native-jni-lib
drwxrwxrwx. 2 root root 30 Nov 19 06:16 temp
drwxr-xr-x. 2 root root 6 Nov 19 06:16 webapps
drwxr-xr-x. 7 root root 81 Nov 12 15:38 webapps.dist
drwxrwxrwx. 2 root root 6 Nov 12 15:35 work
# 可以发现webapps目录为空
root@48c7de09007a:/usr/local/tomcat# cd webapps
root@48c7de09007a:/usr/local/tomcat/webapps# ls -l
total 0

# 将webapps.list目录下的内容拷贝到webapps下,再用浏览器测试访问
root@48c7de09007a:/usr/local/tomcat/webapps# cd ..
root@48c7de09007a:/usr/local/tomcat# cd webapps.dist/
root@48c7de09007a:/usr/local/tomcat/webapps.dist# ls
ROOT docs examples host-manager manager
root@48c7de09007a:/usr/local/tomcat/webapps.dist# cd ..
root@48c7de09007a:/usr/local/tomcat# cp -r webapps.dist/* webapps/
root@48c7de09007a:/usr/local/tomcat# cd webapps
root@48c7de09007a:/usr/local/tomcat/webapps# ls
ROOT docs examples host-manager manager

测试访问 http://192.168.117.155:3355/


🌠安装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
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
# --net somenetwork 网络配置
$ docker run -d --name es1 -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" elasticsearch:7.6.2
# 查看主机状态
$ doucker stats

# 下载并运行ES
[root@parak khighness]# docker run -d --name es1 -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" elasticsearch:7.6.2
Unable to find image 'elasticsearch:7.6.2' locally
7.6.2: Pulling from library/elasticsearch
ab5ef0e58194: Pull complete
c4d1ca5c8a25: Pull complete
941a3cc8e7b8: Pull complete
43ec483d9618: Pull complete
c486fd200684: Pull complete
1b960df074b2: Pull complete
1719d48d6823: Pull complete
Digest: sha256:1b09dbd93085a1e7bca34830e77d2981521a7210e11f11eda997add1c12711fa
Status: Downloaded newer image for elasticsearch:7.6.2
51441d9abfb966c4baa0402ceb99e702f58ec68cd427710a2b8c8043983412e9
# 查看主机状态
[root@parak khighness]# docker stats
CONTAINER ID NAME CPU % MEM USAGE/LIMIT MEM % NET I/O BLOCK I/O PIDS
51441d9abfb9 es1 42.74% 495.6MiB/972.4MiB 50.97% 656B/0B 4.76GB/629MB 46

# 停止es1
$ docker stop es1
# 删除es1
$ docker rm es1

# 限制内存,启动ES
$ docker run -d --name es1 -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" -e ES_JAVA_OPTS="-Xms64m -Xmx512m" elasticsearch:7.6.2

# 重新启动es1
[root@parak khighness]# docker run -d --name es1 -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" -e ES_JAVA_OPTS="-Xms64m -Xmx512m" elasticsearch:7.6.2
ca4494f52e5642d5992c49816b636b1858f2e2f5c1aaf38621c76001262e8e4d
# 再次查看状态
[root@parak khighness]# docker stats
CONTAINER ID NAME CPU % MEM USAGE/LIMIT MEM % NET I/O BLOCK I/O PIDS
ca4494f52e56 es1 0.68% 357.5MiB/972.4MiB 36.77% 737B/0B 476MB/1.78MB 45
# 测试访问
[root@parak khighness]# curl localhost:9200
{
"name" : "ca4494f52e56",
"cluster_name" : "docker-cluster",
"cluster_uuid" : "aDKZlZW_T7Ss3Dr0CXZQlQ",
"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"
}

📈可视化

Y1S1可视化面板的前端写的真好看,我爱了。

1
2
# 安装运行
$ docker run -d -p 8088:9000 --name=pt --restart=always -v /var/run/docker.sock:/var/run/docker.sock --privileged=true portainer/portainer

访问测试 http://192.168.117.155:8088/

image-20201205232646075 image-20201206105337297

📑DockerFile

DockerFile就是用来构建docker镜像的构建文件-命令脚本。

命令

命令 描述 理解
FROM 指定基础镜像 公司的父公司
MAINTAINER 指定维护者信息 公司注册信息
RUN 把命令前面加上RUN即可 公司注册流程
ADD COPY文件,会自动解压 公司注册资金
WORKDIR 设置当前工作目录 公司大楼仓库
VOLUMN 挂载主机目录 公司的主仓库
EXPOSE 指定对外端口 公司开放大门
RUN 进程要一直运行下去 公司永不倒闭
命令 描述
CMD 指定这容器启动的时候要运行的命令只有最后一个会生效,可被替代。
ENTRYPOINT 指定这个容器启动的时候要运行的命令,可以追加命令。
ONBUILD 当构建一个被继承DockerFile这就会运行ONBUILD指令。触发指令.
COPY 类似ADD,将文件拷贝到镜像中。
ENV 构建的时候设置环境变量。

实例1-测试

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
[root@parak home]# mkdir volume
[root@parak home]# cd volume/
[root@parak volume]# vim dockerfile1
[root@parak volume]# cat dockerfile1
FROM centos
VOLUME ["volume01","volume02"]
CMD echo "---end---"
CMD /bin/bash
[root@parak volume]# docker build -f /home/volume/dockerfile1 -t khighness/centos:1.0 .
Sending build context to Docker daemon 2.048kB
Step 1/4 : FROM centos
---> 0d120b6ccaa8
Step 2/4 : VOLUME ["volume01","volume02"]
---> Running in 79dc7b449286
Removing intermediate container 79dc7b449286
---> 9a6608557c9a
Step 3/4 : CMD echo "---end---"
---> Running in 8b8c40056f99
Removing intermediate container 8b8c40056f99
---> 2158b18dedff
Step 4/4 : CMD /bin/bash
---> Running in 9d76c3598d69
Removing intermediate container 9d76c3598d69
---> 240a84cdfbef
Successfully built 240a84cdfbef
Successfully tagged khighness/centos:1.0

实例2-构建自己的centos

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
# 1、编写DockerFile文件
[root@parak dockerfile]# vim mydockerfile-centos
[root@parak dockerfile]# cat mydockerfile-centos
FROM centos
MAINTAINER khighness<1823676372@qq.com>

ENV MYPATH /usr/local
WORKDIR $MYPATH

RUN yum -y install vim
RUN yum -y install net-tools

EXPOSE 80

CMD echo $MYPATH
CMD echo "---end---"
CMD /bin/bash

# 2、通过DockerFile构建镜像
[root@parak dockerfile]# docker build -f mydockerfile-centos -t mycentos:1.0 .
Sending build context to Docker daemon 2.048kB
Step 1/10 : FROM centos
---> 0d120b6ccaa8
Step 2/10 : MAINTAINER khighness<1823676372@qq.com>
---> Running in 024da1b1d4cc
Removing intermediate container 024da1b1d4cc
---> 6c9b636504d2
Step 3/10 : ENV MYPATH /usr/local
---> Running in 4046d4e257ac
Removing intermediate container 4046d4e257ac
---> a5710fdc760e
Step 4/10 : WORKDIR $MYPATH
---> Running in 252416d49e94
Removing intermediate container 252416d49e94
---> fdbae7da4ca4
Step 5/10 : RUN yum -y install vim
---> Running in 9eb786294022
CentOS-8 - AppStream 288 kB/s | 6.2 MB 00:22
CentOS-8 - Base 703 kB/s | 2.3 MB 00:03
CentOS-8 - Extras 1.3 kB/s | 8.1 kB 00:06
Dependencies resolved.
================================================================================
Package Arch Version Repository Size
================================================================================
Installing:
vim-enhanced x86_64 2:8.0.1763-15.el8 AppStream 1.4 M
Installing dependencies:
gpm-libs x86_64 1.20.7-15.el8 AppStream 39 k
vim-common x86_64 2:8.0.1763-15.el8 AppStream 6.3 M
vim-filesystem noarch 2:8.0.1763-15.el8 AppStream 48 k
which x86_64 2.21-12.el8 BaseOS 49 k

Transaction Summary
================================================================================
Install 5 Packages

Total download size: 7.8 M
Installed size: 30 M
Downloading Packages:
(1/5): gpm-libs-1.20.7-15.el8.x86_64.rpm 340 kB/s | 39 kB 00:00
(2/5): vim-filesystem-8.0.1763-15.el8.noarch.rp 664 kB/s | 48 kB 00:00
(3/5): which-2.21-12.el8.x86_64.rpm 315 kB/s | 49 kB 00:00
(4/5): vim-enhanced-8.0.1763-15.el8.x86_64.rpm 543 kB/s | 1.4 MB 00:02
(5/5): vim-common-8.0.1763-15.el8.x86_64.rpm 387 kB/s | 6.3 MB 00:16
--------------------------------------------------------------------------------
Total 448 kB/s | 7.8 MB 00:17
warning: /var/cache/dnf/AppStream-02e86d1c976ab532/packages/gpm-libs-1.20.7-15.el8.x86_64.rpm: Header V3 RSA/SHA256 Signature, key ID 8483c65d: NOKEY
CentOS-8 - AppStream 1.6 MB/s | 1.6 kB 00:00
Importing GPG key 0x8483C65D:
Userid : "CentOS (CentOS Official Signing Key) <security@centos.org>"
Fingerprint: 99DB 70FA E1D7 CE22 7FB6 4882 05B5 55B3 8483 C65D
From : /etc/pki/rpm-gpg/RPM-GPG-KEY-centosofficial
Key imported successfully
Running transaction check
Transaction check succeeded.
Running transaction test
Transaction test succeeded.
Running transaction
Preparing : 1/1
Installing : which-2.21-12.el8.x86_64 1/5
Installing : vim-filesystem-2:8.0.1763-15.el8.noarch 2/5
Installing : vim-common-2:8.0.1763-15.el8.x86_64 3/5
Installing : gpm-libs-1.20.7-15.el8.x86_64 4/5
Running scriptlet: gpm-libs-1.20.7-15.el8.x86_64 4/5
Installing : vim-enhanced-2:8.0.1763-15.el8.x86_64 5/5
Running scriptlet: vim-enhanced-2:8.0.1763-15.el8.x86_64 5/5
Running scriptlet: vim-common-2:8.0.1763-15.el8.x86_64 5/5
Verifying : gpm-libs-1.20.7-15.el8.x86_64 1/5
Verifying : vim-common-2:8.0.1763-15.el8.x86_64 2/5
Verifying : vim-enhanced-2:8.0.1763-15.el8.x86_64 3/5
Verifying : vim-filesystem-2:8.0.1763-15.el8.noarch 4/5
Verifying : which-2.21-12.el8.x86_64 5/5

Installed:
gpm-libs-1.20.7-15.el8.x86_64 vim-common-2:8.0.1763-15.el8.x86_64
vim-enhanced-2:8.0.1763-15.el8.x86_64 vim-filesystem-2:8.0.1763-15.el8.noarch
which-2.21-12.el8.x86_64

Complete!
Removing intermediate container 9eb786294022
---> 491907dac3e2
Step 6/10 : RUN yum -y install net-tools
---> Running in 3a13d71952e5
Last metadata expiration check: 0:00:24 ago on Mon Dec 7 11:45:38 2020.
Dependencies resolved.
================================================================================
Package Architecture Version Repository Size
================================================================================
Installing:
net-tools x86_64 2.0-0.52.20160912git.el8 BaseOS 322 k

Transaction Summary
================================================================================
Install 1 Package

Total download size: 322 k
Installed size: 942 k
Downloading Packages:
net-tools-2.0-0.52.20160912git.el8.x86_64.rpm 1.0 MB/s | 322 kB 00:00
--------------------------------------------------------------------------------
Total 141 kB/s | 322 kB 00:02
Running transaction check
Transaction check succeeded.
Running transaction test
Transaction test succeeded.
Running transaction
Preparing : 1/1
Installing : net-tools-2.0-0.52.20160912git.el8.x86_64 1/1
Running scriptlet: net-tools-2.0-0.52.20160912git.el8.x86_64 1/1
Verifying : net-tools-2.0-0.52.20160912git.el8.x86_64 1/1

Installed:
net-tools-2.0-0.52.20160912git.el8.x86_64

Complete!
Removing intermediate container 3a13d71952e5
---> 0d095f331d4a
Step 7/10 : EXPOSE 80
---> Running in 66d8aceea20c
Removing intermediate container 66d8aceea20c
---> a86402c5f9b7
Step 8/10 : CMD echo $MYPATH
---> Running in b6af3ea8ff6a
Removing intermediate container b6af3ea8ff6a
---> 17533352607f
Step 9/10 : CMD echo "---end---"
---> Running in f015d24c9277
Removing intermediate container f015d24c9277
---> cf7d78851a04
Step 10/10 : CMD /bin/bash
---> Running in d0f70eaa39ec
Removing intermediate container d0f70eaa39ec
---> d59930f07e43
Successfully built d59930f07e43
Successfully tagged mycentos:1.0


# 3、测试运行,官方的centos镜像中是没有网络命令和VIM命令的,而自己构建的centos中已经有
[root@parak dockerfile]# docker run -it --name=mycen mycentos:1.0
[root@43b0b7eb76d8 local]# pwd
/usr/local
[root@43b0b7eb76d8 local]# vim test
[root@43b0b7eb76d8 local]# cat test
Khighness
[root@43b0b7eb76d8 local]# ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 172.17.0.4 netmask 255.255.0.0 broadcast 172.17.255.255
ether 02:42:ac:11:00:04 txqueuelen 0 (Ethernet)
RX packets 8 bytes 656 (656.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 0 bytes 0 (0.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
loop txqueuelen 1000 (Local Loopback)
RX packets 0 bytes 0 (0.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 0 bytes 0 (0.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
[root@43b0b7eb76d8 local]# exit
exit

# 4、查看镜像的变更历史
[root@parak dockerfile]# docker history mycentos:1.0
IMAGE CREATED CREATED BY SIZE COMMENT
d59930f07e43 23 minutes ago /bin/sh -c #(nop) CMD ["/bin/sh" "-c" "/bin… 0B
cf7d78851a04 23 minutes ago /bin/sh -c #(nop) CMD ["/bin/sh" "-c" "echo… 0B
17533352607f 23 minutes ago /bin/sh -c #(nop) CMD ["/bin/sh" "-c" "echo… 0B
a86402c5f9b7 23 minutes ago /bin/sh -c #(nop) EXPOSE 80 0B
0d095f331d4a 23 minutes ago /bin/sh -c yum -y install net-tools 23.2MB
491907dac3e2 23 minutes ago /bin/sh -c yum -y install vim 57.7MB
fdbae7da4ca4 24 minutes ago /bin/sh -c #(nop) WORKDIR /usr/local 0B
a5710fdc760e 24 minutes ago /bin/sh -c #(nop) ENV MYPATH=/usr/local 0B
6c9b636504d2 24 minutes ago /bin/sh -c #(nop) MAINTAINER khighness<1823… 0B
0d120b6ccaa8 3 months ago /bin/sh -c #(nop) CMD ["/bin/bash"] 0B
<missing> 3 months ago /bin/sh -c #(nop) LABEL org.label-schema.sc… 0B
<missing> 3 months ago /bin/sh -c #(nop) ADD file:538afc0c5c964ce0d… 215MB

CMD和ENTRYPOINT的区别

测试CMD

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
# 编写测试CMD的dockerfile
[root@parak dockerfile]# vim dockerfile-cmd-test1
# 内容就是一个CMD命令
[root@parak dockerfile]# cat dockerfile-cmd-test1
FROM centos
CMD ["ls","-a"]
# 构建镜像
[root@parak dockerfile]# docker build -f dockerfile-cmd-test1 -t cmdtest .
Sending build context to Docker daemon 3.072kB
Step 1/2 : FROM centos
---> 0d120b6ccaa8
Step 2/2 : CMD ["ls","-a"]
---> Running in e4df49ad7ca4
Removing intermediate container e4df49ad7ca4
---> 4be395747805
Successfully built 4be395747805
Successfully tagged cmdtest:latest
# 运行镜像就相当于运行CMD命令:ls -a
[root@parak dockerfile]# docker run cmdtest
.
..
.dockerenv
bin
dev
etc
home
lib
lib64
lost+found
media
mnt
opt
proc
root
run
sbin
srv
sys
tmp
usr
var
# 追加命令-l,即ls -al
[root@parak dockerfile]# docker run cmdtest -l
docker: Error response from daemon: OCI runtime create failed: container_linux.go:349: starting container process caused "exec: \"-l\": executable file not found in $PATH": unknown.


测试ENTRYPOINT

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
# 编写测试ENTRYPOINT的dockerfile
[root@parak dockerfile]# vim dockerfile-entrypoint-test1
# 内容就是一个ENTRYPOINT命令
[root@parak dockerfile]# cat dockerfile-entrypoint-test1
FROM centos
ENTRYPOINT ["ls", "-a"]
# 构建镜像
[root@parak dockerfile]# docker build -f dockerfile-entrypoint-test1 -t entrypointtest .
Sending build context to Docker daemon 4.096kB
Step 1/2 : FROM centos
---> 0d120b6ccaa8
Step 2/2 : ENTRYPOINT ["ls", "-a"]
---> Running in 0aa9b4c97293
Removing intermediate container 0aa9b4c97293
---> 472d86e826d8
Successfully built 472d86e826d8
Successfully tagged entrypointtest:latest
# 运行镜像
[root@parak dockerfile]# docker run entrypointtest
.
..
.dockerenv
bin
dev
etc
home
lib
lib64
lost+found
media
mnt
opt
proc
root
run
sbin
srv
sys
tmp
usr
var
# 追击命令-l,即ls -al
[root@parak dockerfile]# docker run entrypointtest -l
total 0
drwxr-xr-x. 1 root root 6 Dec 7 12:27 .
drwxr-xr-x. 1 root root 6 Dec 7 12:27 ..
-rwxr-xr-x. 1 root root 0 Dec 7 12:27 .dockerenv
lrwxrwxrwx. 1 root root 7 May 11 2019 bin -> usr/bin
drwxr-xr-x. 5 root root 340 Dec 7 12:27 dev
drwxr-xr-x. 1 root root 66 Dec 7 12:27 etc
drwxr-xr-x. 2 root root 6 May 11 2019 home
lrwxrwxrwx. 1 root root 7 May 11 2019 lib -> usr/lib
lrwxrwxrwx. 1 root root 9 May 11 2019 lib64 -> usr/lib64
drwx------. 2 root root 6 Aug 9 21:40 lost+found
drwxr-xr-x. 2 root root 6 May 11 2019 media
drwxr-xr-x. 2 root root 6 May 11 2019 mnt
drwxr-xr-x. 2 root root 6 May 11 2019 opt
dr-xr-xr-x. 259 root root 0 Dec 7 12:27 proc
dr-xr-x---. 2 root root 162 Aug 9 21:40 root
drwxr-xr-x. 11 root root 163 Aug 9 21:40 run
lrwxrwxrwx. 1 root root 8 May 11 2019 sbin -> usr/sbin
drwxr-xr-x. 2 root root 6 May 11 2019 srv
dr-xr-xr-x. 13 root root 0 Dec 6 08:24 sys
drwxrwxrwt. 7 root root 145 Aug 9 21:40 tmp
drwxr-xr-x. 12 root root 144 Aug 9 21:40 usr
drwxr-xr-x. 20 root root 262 Aug 9 21:40 var

🔍镜像

概念

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

UnionFS(联合文件系统)

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

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

Docker镜像加载原理

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

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

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

commit镜像

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$ docker commit -m="<messahe>" -a="<author>" <Container ID/NAME> <Target>:<Tag>

# 例如,改装tomcat:9.0的镜像打包成自己的镜像k-tom:1.0
[root@parak khighness]# docker commit -a="Khighness" -m="Add web application" tom1 k-tom:1.0
sha256:fa4617c8771c81b890dc2a87c7be1d2b851c6ba92b053d0d1d8730b2006550c5
[root@parak khighness]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
k-tom 1.0 fa4617c8771c 26 seconds ago 654MB
nginx latest bc9a0695f571 11 days ago 133MB
tomcat 9.0 e0bd8b34b4ea 2 weeks ago 649MB
redis latest 74d107221092 2 weeks ago 104MB
portainer/portainer latest 62771b0b9b09 4 months ago 79.1MB
elasticsearch 7.6.2 f29a1ee41030 8 months ago 791MB
hello-world latest bf756fb1ae65 11 months ago 13.3kB

🌀容器数据卷

概念

目录挂载,将容器内的目录挂载在CentOS上

  • 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
$ docker run -it -v -p <主机目录>:<容器目录> 

# 例如,将docker的centos容器目录/home/test与宿主centos的/home/test挂载起来
[root@parak khighness]# docker run -it --name=cen -v /home/test:/home/test centos /bin/bash
Unable to find image 'centos:latest' locally
latest: Pulling from library/centos
3c72a8ed6814: Pull complete
Digest: sha256:76d24f3ba3317fa945743bb3746fbaf3a0b752f10b10376960de01da70685fbd
Status: Downloaded newer image for centos:latest
[root@4410a5c86528 /]# ls
bin dev etc home lib lib64 lost+found media mnt opt proc root run sbin srv sys tmp usr var
[root@4410a5c86528 /]# cd home/
[root@4410a5c86528 home]# ls
test
[khighness@parak ~]$ cd /home/
[khighness@parak home]$ ls
khighness test
[root@parak home]# docker inspect cen
# 如下是挂载信息
"Mounts": [
{
"Type": "bind", # 类型:绑定
"Source": "/home/test", # 容器目录
"Destination": "/home/test", # 主机目录
"Mode": "",
"RW": true,
"Propagation": "rprivate"
}
]

在容器的挂载目录下新建K1.java,在宿主机的挂载目录中可以直接看到

安装MySQL

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 下载8.0.20版本的mysql镜像
$ docker pull mysql:8.0.20
# 启动mysql服务
# -d 后台运行
# -v 挂载配置和数据
# -e MYSQL_ROOT)PASSWORD 设置密码
$ docker run --name ksql -d -p 3306:3306 -v /home/mysql/conf:/etc/mysql/conf.d -v /home/mysql/data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=KAG1823 mysql:8.0.20

# 解决windows的navicat无法连接的问题
# 进入mysql客户端
$ docker exec -it ksql bash
# 登录mysql
$ mysql -u root -pKAG1823
# 重置密码
$ ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY 'KAG1823';

🌐Docker网络

实现原理

Docker使用Linux桥接,在宿主机虚拟一个Docker容器网桥(Docker0),Docker启动一个容器时会根据Docker网桥的网段分配给容器一个IP地址,称为Container-IP,同时Docker网桥是每个容器的默认网关。因为在同一宿主机内的容器都接入同一网桥。这样容器之间就能够通过容器的Contain-IP直接通信。

Docker网桥是宿主机虚拟出来的,并不是真实存在的网络设备,外部设备是无法寻址到的,这也意味着外部设备无法通过直接Container-IP访问到容器。如果容器希望外部访问到,可以通过映射容器端口到宿主主机(端口映射),即docker run创建容器时候通过-p或者-P参数来启动,访问容器的时候就通过[宿主机IP]:[容器端口]访问容器。

网络模式

模式 配置 说明
Bridge模式 -net=bridge 默认模式
Host模式 -net=host 容器和宿主机共享Network NameSpace
Container模式 -net=container : NAME OR ID 容器和另外一个容器共享Network NameSpace
None模式 -net=none 容器有独立的Network NameSpace,但并没有对其进行任何网络设置,如分配veth pair 和网桥连接,配置IP等

1️⃣host模式

如果启动容器的时候使用host模式,那么这个容器将不会获得一个独立的Network NameSpace,而是和宿主机共用一个Network NameSpace。容器将不会虚拟出自己的网卡,配置自己的IP等,而是使用宿主机的IP和端口。但是,容器的其他方面,如文件系统、进程列表等还是和宿主机隔离的。

使用host模式的容器可以直接使用宿主机的IP地址与外界通信,容器内部的服务端口也可以使用宿主机的端口,不需要进行NAT,host最大的优势就是网络性能比较好,但是docker host上已经使用的端口就不能再用了,网络的隔离性不好。


2️⃣container模式

这个模式指定新创建的容器和已经存在的一个容器共享一个 Network NameSpace,而不是和宿主机共享。新创建的容器不会创建自己的网卡,配置自己的 IP,而是和一个指定的容器共享 IP、端口范围等。同样,两个容器除了网络方面,其他的如文件系统、进程列表等还是隔离的。两个容器的进程可以通过 lo 网卡设备通信。


3️⃣none模式

使用none模式,Docker容器拥有自己的Network NameSpace,但是,并不为Docker容器进行任何网络配置。也就是说,这个Docker容器没有网卡、IP、路由等信息。需要我们自己为Docker容器添加网卡、配置IP等。

这种网络模式下容器只有lo回环网络,没有其他网卡。none模式可以在容器创建时通过–network=none来指定。这种类型的网络没有办法联网,封闭的网络能很好的保证容器的安全性。


4️⃣bridge模式

当Docker进程启动时,会在主机上创建一个名为docker0的虚拟网桥,此主机上启动的Docker容器会连接到这个虚拟网桥上。虚拟网桥的工作方式和物理交换机类似,这样主机上的所有容器就通过交换机连在了一个二层网络中。

从docker0子网中分配一个IP给容器使用,并设置docker0的IP地址为容器的默认网关。在主机上创建一对虚拟网卡veth pair设备,Docker将veth pair设备的一端放在新创建的容器中,并命名为eth0(容器的网卡),另一端放在主机中,以vethxxx这样类似的名字命名,并将这个网络设备加入到docker0网桥中。可以通过brctl show命令查看。

bridge模式是docker的默认网络模式,不写–net参数,就是bridge模式。使用docker run -p时,docker实际是在iptables做了DNAT规则,实现端口转发功能。可以使用iptables -t nat -vnL查看。

–link探究

官方已经不推荐使用,我们可以了解一下。

2个容器之间互相访问通信:docker run <container1-id/name> --link <container2-id/name> <image>

使用这个命令启动容器2的时候,容器便可以ping通容器1,但是反向ping不通。

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
# 创建容器tom1
[root@parak khighness]# docker run -d -p 3356:8080 --name tom1 tomcat:9.0
dd615d6d2ccb9467aad8ba008ece995588680d849b9f61945b10de5c3475f671
# 使用--link创建容器2
[root@parak khighness]# docker run -d -p 3357:8081 --name tom2 --link tom1 tomcat:9.0
b2c17969a2cb4407bb1a61a53703a38998a11db01ce516feb70e397b42af6ad3
# tom1不能ping通tom2
[root@parak khighness]# docker exec -it tom1 ping tom2
ping: tom2: Name or service not known
# tom2可以ping通tom1
[root@parak khighness]# docker exec -it tom2 ping tom1
PING tom1 (172.17.0.4) 56(84) bytes of data.
64 bytes from tom1 (172.17.0.4): icmp_seq=1 ttl=64 time=0.161 ms
64 bytes from tom1 (172.17.0.4): icmp_seq=2 ttl=64 time=0.108 ms
64 bytes from tom1 (172.17.0.4): icmp_seq=3 ttl=64 time=0.122 ms
^C
--- tom1 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 4ms
rtt min/avg/max/mdev = 0.108/0.130/0.161/0.024 ms
# 查看tom2内部的hosts文件
[root@parak khighness]# docker exec -it tom2 cat /etc/hosts
127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.4 tom1 dd615d6d2ccb # ==> 根源:本质就是tom2就是在本地配置了tom1的域名IP解析。
172.17.0.5 b2c17969a2cb

自定义网络

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
# 创建网络
[root@parak khighness]# docker network create --driver bridge --subnet 192.168.0.0/16 --gateway 192.168.0.1 mynet
abaebdc493149a140ee77965274885adea3882bf117c4f8e61e4034730c3b890
# 查看网络
[root@parak khighness]# docker network ls
NETWORK ID NAME DRIVER SCOPE
4399361ba4a9 bridge bridge local
65f0ec2bfb42 host host local
abaebdc49314 mynet bridge local
feab1dfce431 none null local
# 详细信息
[root@parak khighness]# docker network inspect mynet
[
{
"Name": "mynet",
"Id": "abaebdc493149a140ee77965274885adea3882bf117c4f8e61e4034730c3b890",
"Created": "2020-12-10T16:12:08.563828418+08:00",
"Scope": "local",
"Driver": "bridge",
"EnableIPv6": false,
"IPAM": {
"Driver": "default",
"Options": {},
"Config": [
{
"Subnet": "192.168.0.0/16",
"Gateway": "192.168.0.1"
}
]
},
"Internal": false,
"Attachable": false,
"Ingress": false,
"ConfigFrom": {
"Network": ""
},
"ConfigOnly": false,
"Containers": {},
"Options": {},
"Labels": {}
}
]
# 在mynet下启动tomcat1
[root@parak khighness]# docker run -d -it -p 8080:3355 --net mynet --name mynet-tom1 tomcat:9.0
4d799757f01f560af7fd44d610b7fdabd1e0f66ef528bf1259f09242bddbb636
# 在mynet下启动tomcat2
[root@parak khighness]# docker run -d -it -p 8081:3356 --net mynet --name mynet-tom2 tomcat:9.0
15c045f96d5b7b2ee2e470cb69e5b1f86511929f7ed05ed8f20db26ef4b975af
# 使用mynet-tom2 ping mynet-tom1
[root@parak khighness]# docker exec -it mynet-tom2 ping mynet-tom1
PING mynet-tom1 (192.168.0.2) 56(84) bytes of data.
64 bytes from mynet-tom1.mynet (192.168.0.2): icmp_seq=1 ttl=64 time=0.068 ms
64 bytes from mynet-tom1.mynet (192.168.0.2): icmp_seq=2 ttl=64 time=0.042 ms
64 bytes from mynet-tom1.mynet (192.168.0.2): icmp_seq=3 ttl=64 time=0.055 ms
--- mynet-tom1 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 4ms
rtt min/avg/max/mdev = 0.042/0.055/0.068/0.010 ms
# 使用mynet-tom1 ping mynet-tom2
[root@parak khighness]# docker exec -it mynet-tom1 ping mynet-tom2
PING mynet-tom2 (192.168.0.3) 56(84) bytes of data.
64 bytes from mynet-tom2.mynet (192.168.0.3): icmp_seq=1 ttl=64 time=0.036 ms
64 bytes from mynet-tom2.mynet (192.168.0.3): icmp_seq=2 ttl=64 time=0.048 ms
64 bytes from mynet-tom2.mynet (192.168.0.3): icmp_seq=3 ttl=64 time=0.058 ms
--- mynet-tom2 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2ms
rtt min/avg/max/mdev = 0.036/0.047/0.058/0.010 ms

自定义网络自动维护好容器的网络关系!

网络连通

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
# 在Docker0网络启动tomcat
[root@parak khighness]# docker run -d -it -p 8082:3357 --name tom1 tomcat:9.0
0344f04baab2eaeaac0118dac7a93d8b2d77946636c76ed3bde804cbeda836be
# 测试tom1 ping mynet—tom1
[root@parak khighness]# docker exec tom1 ping mynet-tom1
ping: mynet-tom1: Name or service not known
# 连通mynet - tom1
[root@parak khighness]# docker network connect mynet tom1
# 查看mynet1的详细信息
[root@parak khighness]# docker inspect mynet
[
{
"Name": "mynet",
"Id": "abaebdc493149a140ee77965274885adea3882bf117c4f8e61e4034730c3b890",
"Created": "2020-12-10T16:12:08.563828418+08:00",
"Scope": "local",
"Driver": "bridge",
"EnableIPv6": false,
"IPAM": {
"Driver": "default",
"Options": {},
"Config": [
{
"Subnet": "192.168.0.0/16",
"Gateway": "192.168.0.1"
}
]
},
"Internal": false,
"Attachable": false,
"Ingress": false,
"ConfigFrom": {
"Network": ""
},
"ConfigOnly": false,
"Containers": {
# 发现mynet将tom1放到了mynet网络下,即一个容器,两个IP
"0344f04baab2eaeaac0118dac7a93d8b2d77946636c76ed3bde804cbeda836be": {
"Name": "tom1",
"EndpointID": "8911ad05a9b0d7d0effbf50c82659f36b82d21e18f992359b09494073dddd969",
"MacAddress": "02:42:c0:a8:00:04",
"IPv4Address": "192.168.0.4/16",
"IPv6Address": ""
},
"15c045f96d5b7b2ee2e470cb69e5b1f86511929f7ed05ed8f20db26ef4b975af": {
"Name": "mynet-tom2",
"EndpointID": "907f16284e90be0d880a999b29210d1cd82adb2c79b4179eeb1d70d75130362a",
"MacAddress": "02:42:c0:a8:00:03",
"IPv4Address": "192.168.0.3/16",
"IPv6Address": ""
},
"4d799757f01f560af7fd44d610b7fdabd1e0f66ef528bf1259f09242bddbb636": {
"Name": "mynet-tom1",
"EndpointID": "6529ef4fc05dffe65fe875fdf15f2f4a61665c4d969767db94dd828baf88b323",
"MacAddress": "02:42:c0:a8:00:02",
"IPv4Address": "192.168.0.2/16",
"IPv6Address": ""
}
},
"Options": {},
"Labels": {}
}
]
# 再次测试tom1 ping mynet—tom1
[root@parak khighness]# docker exec -it tom1 ping mynet-tom1
PING mynet-tom1 (192.168.0.2) 56(84) bytes of data.
64 bytes from mynet-tom1.mynet (192.168.0.2): icmp_seq=1 ttl=64 time=0.097 ms
64 bytes from mynet-tom1.mynet (192.168.0.2): icmp_seq=2 ttl=64 time=0.052 ms
64 bytes from mynet-tom1.mynet (192.168.0.2): icmp_seq=3 ttl=64 time=0.053 ms
--- mynet-tom1 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 3ms
rtt min/avg/max/mdev = 0.052/0.067/0.097/0.022 ms

💠Redis集群部署

shell脚本

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
# 创建网卡
docker network create redis --subnet 172.38.0.0/16

# 通过脚本创建六个redis配置
for port in $(seq 1 6); \
do \
mkdir -p /mydata/redis/node-${port}/conf
touch /mydata/redis/node-${port}/conf/redis.conf
cat << EOF >>/mydata/redis/node-${port}/conf/redis.conf
port 6379
bind 0.0.0.0
cluster-enabled yes
cluster-config-file nodes.conf
cluster-node-timeout 5000
cluster-announce-ip 172.38.0.1${port}
cluster-announce-port 6379
cluster-announce-bus-port 16379
appendonly yes
EOF
done

# 运行redis
for port in $(seq 1 6); \
do
docker run -p 637${port}:6379 -p 1637${port}:16379 --name redis-${port} \
-v /mydata/redis/node-${port}/data:/data \
-v /mydata/redis/node-${port}/conf/redis.conf:/etc/redis/redis.conf \
-d --net redis --ip 172.38.0.1${port} redis:5.0.9-alpine3.11 redis-server /etc/redis/redis.conf
done

# 进入redis-1
docker exec -it redis-1 /bin/sh
# 搭建集群
redis-cli --cluster create 172.38.0.11:6379 172.38.0.12:6379 172.38.0.13:6379 172.38.0.14:6379 172.38.0.15:6379 172.38.0.16:6379

# 停止集群
for port in $(seq 1 6); \
do
docker stop redis-${port}
done

# 启动集群
for port in $(seq 1 6); \
do
docker start redis-${port}
done

💨SpringBoot测试

步骤

  • 构建SpringBoot项目
  • 打包web应用
  • 编写dockerfile
  • 构建镜像
  • 发布运行

编写Controller

1
2
3
4
5
6
7
@RestController
public class HelloController {
@GetMapping("/hello/{name}")
public String sayHello(@PathVariable("name") String name) {
return "Hello, " + name + "\n\n" + " -from KHighness";
}
}

通过maven的package打包

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
[INFO] Scanning for projects...
[INFO]
[INFO] --------------------------< top.parak:hello >---------------------------
[INFO] Building hello 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO] --- maven-resources-plugin:3.1.0:resources (default-resources) @ hello ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 0 resource
[INFO] Copying 0 resource
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ hello ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 2 source files to C:\Users\18236\Desktop\Recent\hello\target\classes
[INFO] --- maven-resources-plugin:3.1.0:testResources (default-testResources) @ hello ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory C:\Users\18236\Desktop\Recent\hello\src\test\resources
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) @ hello ---
[INFO] No sources to compile
[INFO] --- maven-surefire-plugin:2.22.2:test (default-test) @ hello ---
[INFO] No tests to run.
[INFO] --- maven-jar-plugin:3.1.2:jar (default-jar) @ hello ---
[INFO] Building jar: C:\Users\18236\Desktop\Recent\hello\target\hello-1.0-SNAPSHOT.jar
[INFO] --- spring-boot-maven-plugin:2.2.5.RELEASE:repackage (repackage) @ hello ---
[INFO] Replacing main artifact with repackaged archive
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 5.534 s
[INFO] Finished at: 2020-12-10T17:54:11+08:00
[INFO] ------------------------------------------------------------------------

编写Dockerfile

1
2
3
4
5
6
7
8
9
FROM java:8

COPY *.jar /app.jar

CMD ["--server.port=8080"]

EXPOSE 8080

ENTRYPOINT ["java", "-jar", "/app.jar"]

通过Xftp将构建好的jar包和DockerFile发送到虚拟机

构建镜像

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
[root@parak hello]# docker build -t hello .
Sending build context to Docker daemon 17.6MB
Step 1/5 : FROM java:8
---> d23bdf5b1b1b
Step 2/5 : COPY *.jar /app.jar
---> 34774df7a107
Step 3/5 : CMD ["--server.port=8080"]
---> [Warning] IPv4 forwarding is disabled. Networking will not work.
---> Running in 11d95474e047
Removing intermediate container 11d95474e047
---> e8b6fa21a3a0
Step 4/5 : EXPOSE 8080
---> [Warning] IPv4 forwarding is disabled. Networking will not work.
---> Running in 896cc7d50875
Removing intermediate container 896cc7d50875
---> b139242b232d
Step 5/5 : ENTRYPOINT ["java", "-jar", "/app.jar"]
---> [Warning] IPv4 forwarding is disabled. Networking will not work.
---> Running in 562f3bb605a0
Removing intermediate container 562f3bb605a0
---> 1d28463205d5
Successfully built 1d28463205d5
Successfully tagged hello:latest

运行镜像

1
2
3
4
5
6
[root@parak hello]# docker run -d -it -p 8001:8080 hello
7e19b364789de18c736c51e5c84d611e7474d3a733f188220dfd7cc011e55729
[root@parak hello]# curl http://192.168.117.155:8001/hello/KKK
Hello, KKK

-from KHighness

⭕相关问题

解决问题1: WARNING: IPv4 forwarding is disabled. Networking will not work.

1
2
$ echo "net.ipv4.ip_forward=1" >>/usr/lib/sysctl.d/00-system.conf
$ systemctl restart network && systemctl restart docker

解决问题2: 使用阿里云服务器运行一个容器,外部IP不能访问

需要在阿里云服务器配置防火墙相关端口对外开放。

比如跑一个开放端口为3333的springboot应用需要在阿里云服务器控制台的防火墙添加规则: