Docker基础学习

Docker的常用命令

帮助命令

docker version #显示docker的版本信息
docker info #显示docker的系统信息,包括镜像和容器的数量
docker 命令 --help #帮助命令

帮助文档的地址:
https://docs.docker.com/engine/reference/commandline/docker/

镜像命令

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

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

[root@VM-0-15-centos ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
hello-world latest bf756fb1ae65 11 months ago 13.3kB


#解释
REPOSITORY #镜像的仓库
TAG #镜像的标签
IMAGE ID #镜像的ID
CREATED #镜像的创建时间
SIZE #镜像的大小

#可选项
Options:
-a, --all #列出所有镜像
--digests Show digests
-q, --quiet #仅显示镜像的ID

docker search #搜索镜像

[root@VM-0-15-centos ~]# docker search tensorflow
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
tensorflow/tensorflow Official Docker images for the machine learn… 1799
jupyter/tensorflow-notebook Jupyter Notebook Scientific Python Stack w/ … 248
tensorflow/serving Official images for TensorFlow Serving (http… 102
rocm/tensorflow Tensorflow with ROCm backend support 58
xblaster/tensorflow-jupyter Dockerized Jupyter with tensorflow 54 [OK]
floydhub/tensorflow tensorflow 26 [OK]
bitnami/tensorflow-serving Bitnami Docker Image for TensorFlow Serving 14 [OK]
opensciencegrid/tensorflow-gpu TensorFlow GPU set up for OSG 12

docker pull #下载镜像

#docker pull mysql 镜像名[:tag]

[root@VM-0-15-centos ~]# docker pull mysql
Using default tag: latest #不写tag,默认latest
latest: Pulling from library/mysql
852e50cd189d: Pull complete #分层下载,docker 镜像的核心 联合文件系统
29969ddb0ffb: Pull complete
a43f41a44c48: Pull complete
5cdd802543a3: Pull complete
b79b040de953: Pull complete
938c64119969: Pull complete
7689ec51a0d9: Pull complete
a880ba7c411f: Pull complete
984f656ec6ca: Pull complete
9f497bce458a: Pull complete
b9940f97694b: Pull complete
2f069358dc96: Pull complete
Digest: sha256:4bb2e81a40e9d0d59bd8e3dc2ba5e1f2197696f6de39a91e90798dd27299b093 #签名
Status: Downloaded newer image for mysql:latest
docker.io/library/mysql:latest #真实地址


#指定版本
docker pull mysql:5.7

[root@VM-0-15-centos ~]# docker pull mysql:5.7
5.7: Pulling from library/mysql
852e50cd189d: Already exists
29969ddb0ffb: Already exists
a43f41a44c48: Already exists
5cdd802543a3: Already exists
b79b040de953: Already exists
938c64119969: Already exists
7689ec51a0d9: Already exists
36bd6224d58f: Pull complete
cab9d3fa4c8c: Pull complete
1b741e1c47de: Pull complete
aac9d11987ac: Pull complete
Digest: sha256:8e2004f9fe43df06c3030090f593021a5f283d028b5ed5765cc24236c2c4d88e
Status: Downloaded newer image for mysql:5.7
docker.io/library/mysql:5.7

docker rmi #删除镜像

#按docker id镜像删除
[root@VM-0-15-centos ~]# docker rmi -f ae0658fdbad5
Untagged: mysql:5.7
Untagged: mysql@sha256:8e2004f9fe43df06c3030090f593021a5f283d028b5ed5765cc24236c2c4d88e
Deleted: sha256:ae0658fdbad5fb1c9413c998d8a573eeb5d16713463992005029c591e6400d02
Deleted: sha256:a2cf831f4221764f4484ff0df961b54f1f949ed78220de1b24046843c55ac40f
Deleted: sha256:0a7adcc95a91b1ec2beab283e0bfce5ccd6df590bd5a5e894954fcf27571e7f5
Deleted: sha256:0fae465cbacf7c99aa90bc286689bc88a35d086f37fd931e03966d312d5dfb10
Deleted: sha256:23af125b9e54a94c064bdfacc2414b1c8fba288aff48308e8117beb08b38cb19

#递归删除所有的镜像
[root@VM-0-15-centos ~]# docker rmi -f $(docker images -aq)
Untagged: mysql:latest
Untagged: mysql@sha256:4bb2e81a40e9d0d59bd8e3dc2ba5e1f2197696f6de39a91e90798dd27299b093
Deleted: sha256:dd7265748b5dc3211208fb9aa232cef8d3fefd5d9a2a80d87407b8ea649e571c
Deleted: sha256:aac9a624212bf416c3b41a62212caf12ed3c578d6b17b0f15be13a7dab56628d
Deleted: sha256:1bf3ce09276e9e128108b166121e5d04abd16e7de7473b53b3018c6db0cf23ff
Deleted: sha256:24c6444cea460c3cc2f4e0385e3e97819a0672a54a361921f95d4582583abd59
Deleted: sha256:77585ebe3eaa035694084b3c5937fe82b8972aae1e6c6070fc4d7bc391d10928
Deleted: sha256:1cfd539163ceb17f7bb85a0da968714fe9258b75dbf73f5ad45392a45cfd34b7
Deleted: sha256:c37f414ac8d2b5e5d39f159a6dffd30b279c1268f30186cee5da721e451726ea
Deleted: sha256:955b3c214bccf3ee2a7930768137fd7ed6a72677334be67a07c78a622abd318a
Deleted: sha256:a2e35a0fdb20100365e2fb26c65357fcf926ac7990bf9074a51cbac5a8358d7e
Deleted: sha256:8c3a028fc66f360ce6ce6c206786df68fac4c24257474cbe4f67eda0ac21efd6
Deleted: sha256:0a6d37fabaceb4faa555e729a7d97cb6ee193cb97789a213907a3d3c156d7e35
Deleted: sha256:579519c51de1afe1e29d284b1741af239a307975197cf6ce213a70068d923231
Deleted: sha256:f5600c6330da7bb112776ba067a32a9c20842d6ecc8ee3289f1a713b644092f8
Untagged: hello-world:latest
Untagged: hello-world@sha256:e7c70bb24b462baa86c102610182e3efcb12a04854e8c582838d92970a09f323
Deleted: sha256:bf756fb1ae65adf866bd8c456593cd24beb6a0a061dedf42b26a993176745f6b

容器命令

有了镜像才能创建容器,linux,下载一个centos镜像来测试

[root@VM-0-15-centos ~]# docker pull centos

新建容器并启动

docker run [可选参数] image

#参数说明
--name="Name" #容器名字
-d #使用后台方式运行,类似nohup
-it #使用交互方式运行,进入容器查看内容
-p #指定容器端口 -p 8080:8080
-p 主机端口:容器端口 (常用)
-p 容器端口
容器端口
-P #随机指定端口

启动并进入容器

[root@VM-0-15-centos ~]# docker run -it centos /bin/bash
[root@1faa1a0b849e /]#
[root@1faa1a0b849e /]# ls
bin etc lib lost+found mnt proc run srv tmp var
dev home lib64 media opt root sbin sys usr
#退出容器
[root@1faa1a0b849e /]# exit
exit
[root@VM-0-15-centos ~]# ls

列出所有运行中的容器

#列出当前在运行的容器
[root@VM-0-15-centos ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
#列出所有运行过的容器
[root@VM-0-15-centos ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
1faa1a0b849e centos "/bin/bash" 4 minutes ago Exited (0) 55 seconds ago frosty_cori
0d482f3a4d60 bf756fb1ae65 "/hello" 34 hours ago Exited (0) 34 hours ago nifty_visvesvaraya
e05f6bfe06e0 bf756fb1ae65 "/hello" 34 hours ago Exited (0) 34 hours ago amazing_diffie
8a40e14a2c36 bf756fb1ae65 "/hello" 34 hours ago Exited (0) 34 hours ago goofy_liskov

#列出最近创建的容器
[root@VM-0-15-centos ~]# docker ps -n=1
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
1faa1a0b849e centos "/bin/bash" 5 minutes ago Exited (0) About a minute ago frosty_cori

#只显示容器的编号
[root@VM-0-15-centos ~]# docker ps -aq
1faa1a0b849e
0d482f3a4d60
e05f6bfe06e0
8a40e14a2c36

退出容器

exit  #直接容器停止并退出
CTRL+P+Q #容器不停止并退出

[root@VM-0-15-centos ~]# docker run -it centos /bin/bash
[root@e5a4a59f28ff /]# [root@VM-0-15-centos ~]#
[root@VM-0-15-centos ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
e5a4a59f28ff centos "/bin/bash" 21 seconds ago Up 20 seconds agitated_ritchie

删除容器

docker rm 容器id  #删除指定的容器,不能删除正在运行的容器,如要删除,加-f
#递归删除所有docker容器
docker rm -f $(docker ps -aq)
#删除所有容器
docker ps -a -q|xargs docker rm

[root@VM-0-15-centos ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
e5a4a59f28ff centos "/bin/bash" 5 minutes ago Up 5 minutes agitated_ritchie
c4fd9794c39a centos "/bin/bash" 5 minutes ago Exited (0) 5 minutes ago dreamy_lumiere
1faa1a0b849e centos "/bin/bash" 16 minutes ago Exited (0) 12 minutes ago frosty_cori
0d482f3a4d60 bf756fb1ae65 "/hello" 34 hours ago Exited (0) 34 hours ago nifty_visvesvaraya
e05f6bfe06e0 bf756fb1ae65 "/hello" 34 hours ago Exited (0) 34 hours ago amazing_diffie
8a40e14a2c36 bf756fb1ae65 "/hello" 34 hours ago Exited (0) 34 hours ago goofy_liskov
[root@VM-0-15-centos ~]# docker rm e5a4a59f28ff
Error response from daemon: You cannot remove a running container e5a4a59f28ffc678ab9ea5ed7a9af825ff053e1816cd94c90880b3d2a87997df. Stop the container before attempting removal or force remove
[root@VM-0-15-centos ~]# docker rm -f $(docker ps -aq)
e5a4a59f28ff
c4fd9794c39a
1faa1a0b849e
0d482f3a4d60
e05f6bfe06e0
8a40e14a2c36
[root@VM-0-15-centos ~]# docker ps -aq
[root@VM-0-15-centos ~]#

启动和停止容器的操作

docker start 容器id #启动 
docker restart 容器id #重启
docker stop 容器id #停止当前运行的容器
docker kill 容器id #强制停止当前容器

常用其他命令

后台启动容器

docker run -d centos #后台启动 
#docker ps 时候,发现centos会停止,因为容器后台运行,就必须要一个前台进程,docker发现没有应用,就会自动停止

查看日志

docker logs -f -t --tail 10  容器id #发现没有日志

查看容器中的进程信息

docker top 容器id

[root@VM-0-15-centos ~]# docker run -it centos /bin/bash
[root@ba393184f315 /]# [root@VM-0-15-centos ~]#
[root@VM-0-15-centos ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
ba393184f315 centos "/bin/bash" 9 seconds ago Up 8 seconds wizardly_cerf
[root@VM-0-15-centos ~]# docker top ba393184f315
UID PID PPID C STIME TTY TIME CMD
root 25856 25840 0 09:46 pts/0 00:00:00 /bin/bash

查看镜像的元数据

docker inspect 容器id

[root@VM-0-15-centos ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
ba393184f315 centos "/bin/bash" 3 minutes ago Up 3 minutes wizardly_cerf
[root@VM-0-15-centos ~]# docker inspect ba393184f315
[
{
"Id": "ba393184f3157b86b24aa040b24b4e169c3d1aed0ca56edee01596a7f833fd73",
"Created": "2020-12-01T01:46:02.700180427Z",
"Path": "/bin/bash",
"Args": [],
"State": {
"Status": "running",
"Running": true,
"Paused": false,
"Restarting": false,
"OOMKilled": false,
"Dead": false,
"Pid": 25856,
"ExitCode": 0,
"Error": "",
"StartedAt": "2020-12-01T01:46:02.955068318Z",
"FinishedAt": "0001-01-01T00:00:00Z"
},
"Image": "sha256:0d120b6ccaa8c5e149176798b3501d4dd1885f961922497cd0abef155c869566",
"ResolvConfPath": "/var/lib/docker/containers/ba393184f3157b86b24aa040b24b4e169c3d1aed0ca56edee01596a7f833fd73/resolv.conf",
"HostnamePath": "/var/lib/docker/containers/ba393184f3157b86b24aa040b24b4e169c3d1aed0ca56edee01596a7f833fd73/hostname",
"HostsPath": "/var/lib/docker/containers/ba393184f3157b86b24aa040b24b4e169c3d1aed0ca56edee01596a7f833fd73/hosts",
"LogPath": "/var/lib/docker/containers/ba393184f3157b86b24aa040b24b4e169c3d1aed0ca56edee01596a7f833fd73/ba393184f3157b86b24aa040b24b4e169c3d1aed0ca56edee01596a7f833fd73-json.log",
"Name": "/wizardly_cerf",
"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,
"Capabilities": null,
"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/78d46a1dd3114ea4472382c70d189091005ab80b93b328fdf6917ea374e09135-init/diff:/var/lib/docker/overlay2/9977c7654d8482400f51116d18f3c0562764ac2c1082c8de455e689c10593b30/diff",
"MergedDir": "/var/lib/docker/overlay2/78d46a1dd3114ea4472382c70d189091005ab80b93b328fdf6917ea374e09135/merged",
"UpperDir": "/var/lib/docker/overlay2/78d46a1dd3114ea4472382c70d189091005ab80b93b328fdf6917ea374e09135/diff",
"WorkDir": "/var/lib/docker/overlay2/78d46a1dd3114ea4472382c70d189091005ab80b93b328fdf6917ea374e09135/work"
},
"Name": "overlay2"
},
"Mounts": [],
"Config": {
"Hostname": "ba393184f315",
"Domainname": "",
"User": "",
"AttachStdin": true,
"AttachStdout": true,
"AttachStderr": true,
"Tty": true,
"OpenStdin": true,
"StdinOnce": true,
"Env": [
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
],
"Cmd": [
"/bin/bash"
],
"Image": "centos",
"Volumes": null,
"WorkingDir": "",
"Entrypoint": null,
"OnBuild": null,
"Labels": {
"org.label-schema.build-date": "20200809",
"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": "913e925d94cac8aaa4ead2ed29197af7d07d4fbfd35625642019116a42cff156",
"HairpinMode": false,
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"Ports": {},
"SandboxKey": "/var/run/docker/netns/913e925d94ca",
"SecondaryIPAddresses": null,
"SecondaryIPv6Addresses": null,
"EndpointID": "9da28d1e996685ffa1a39d26fe042919d661c4b4c8267f3470f2042ee78810ed",
"Gateway": "172.18.0.1",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"IPAddress": "172.18.0.2",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"MacAddress": "02:42:ac:12:00:02",
"Networks": {
"bridge": {
"IPAMConfig": null,
"Links": null,
"Aliases": null,
"NetworkID": "df77c62f666112b12946dbbbc16f1dcdbbcc8548e3fa56519fd062e5331a0c08",
"EndpointID": "9da28d1e996685ffa1a39d26fe042919d661c4b4c8267f3470f2042ee78810ed",
"Gateway": "172.18.0.1",
"IPAddress": "172.18.0.2",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"MacAddress": "02:42:ac:12:00:02",
"DriverOpts": null
}
}
}
}
]

进入当前运行的容器

通常容器都是后台运行的,有时我们需要进入容器修改一些配置

docker exec -it 容器id bashShell

[root@VM-0-15-centos ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
ba393184f315 centos "/bin/bash" 11 minutes ago Up 11 minutes wizardly_cerf
[root@VM-0-15-centos ~]# docker exec -it ba393184f315 /bin/bash
[root@ba393184f315 /]# ps -ef
UID PID PPID C STIME TTY TIME CMD
root 1 0 0 01:46 pts/0 00:00:00 /bin/bash
root 14 0 0 01:57 pts/1 00:00:00 /bin/bash
root 27 14 0 01:57 pts/1 00:00:00 ps -ef

docker attach 容器id

[root@VM-0-15-centos ~]# docker attach ba393184f315
[root@ba393184f315 /]#

docker exec 进入容器后,开启新的终端,可以在里面操作
docker attach 进入容器正在执行的终端

从容器拷贝文件到主机

docker cp 容器id:容器内路径 目的的主机路径

[root@VM-0-15-centos home]# docker attach b67b64394534
[root@b67b64394534 /]# cd /home
[root@b67b64394534 home]# ls
[root@b67b64394534 home]# touch rx.java
[root@b67b64394534 home]# read escape sequence
[root@VM-0-15-centos home]#
[root@VM-0-15-centos home]# docker cp b67b64394534:/home/rx.java /home
[root@VM-0-15-centos home]# ls
rx.java rxk.java

Test1-Docker部属nginx

#下载Nginx
[root@VM-0-15-centos ~]# 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@VM-0-15-centos ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
b67b64394534 centos "/bin/bash" 10 hours ago Up 10 hours suspicious_sutherland
[root@VM-0-15-centos ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
nginx latest bc9a0695f571 6 days ago 133MB
centos latest 0d120b6ccaa8 3 months ago 215MB
#以后台方式运行镜像,并且将nginx的80端口映射到本地3344端口,同时给此镜像一个名字--name nginx01
[root@VM-0-15-centos ~]# docker run -d --name nginx01 -p 3344:80 nginx
5a3e8a8e16e5e1f46b8bbe6c23662aebd3c13dc5cacfd63fb24d0703c1235819
[root@VM-0-15-centos ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
5a3e8a8e16e5 nginx "/docker-entrypoint.…" 2 minutes ago Up 2 minutes 0.0.0.0:3344->80/tcp nginx01
b67b64394534 centos "/bin/bash" 10 hours ago Up 10 hours suspicious_sutherland
#请求本地3344端口,显示nginx,成功运行
[root@VM-0-15-centos ~]# curl localhost:3344
<!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>


#进入容器
[root@VM-0-15-centos ~]# docker exec -it nginx01 /bin/bash
root@5a3e8a8e16e5:/# whereis nginx
nginx: /usr/sbin/nginx /usr/lib/nginx /etc/nginx /usr/share/nginx
#关闭容器
[root@VM-0-15-centos ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
5a3e8a8e16e5 nginx "/docker-entrypoint.…" 33 minutes ago Up 33 minutes 0.0.0.0:3344->80/tcp nginx01
b67b64394534 centos "/bin/bash" 10 hours ago Up 10 hours suspicious_sutherland
[root@VM-0-15-centos ~]# docker stop nginx01
nginx01
[root@VM-0-15-centos ~]# docker stop centos
Error response from daemon: No such container: centos
[root@VM-0-15-centos ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
b67b64394534 centos "/bin/bash" 10 hours ago Up 10 hours suspicious_sutherland
[root@VM-0-15-centos ~]# docker stop b67b64394534
b67b64394534

Test2-Docker部属tomcat

#下载并启动tomcat (加了--rm 意味着用完就会删除)
[root@VM-0-15-centos ~]# docker run -it --rm tomcat:9.0
Unable to find image 'tomcat:9.0' locally
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

#正常下载
[root@VM-0-15-centos ~]# docker pull tomcat:9.0
9.0: Pulling from library/tomcat
Digest: sha256:a319b10d8729817c7ce0bcc2343a6f97711c7870395019340d96b6aafd6ccbea
Status: Image is up to date for tomcat:9.0
docker.io/library/tomcat:9.0

#将tomcat 8080端口映射到外部3355端口
[root@VM-0-15-centos ~]# docker run -d -p 3355:8080 --name tomcat01 tomcat
af2d7437747112b51f83c556b1790503f41e2632bbbe965e00a8bff3d3268c92

#进入tomcat
[root@VM-0-15-centos ~]# docker exec -it tomcat01 /bin/bash
root@af2d74377471:/usr/local/tomcat# ls
BUILDING.txt LICENSE README.md RUNNING.txt conf logs temp webapps.dist
CONTRIBUTING.md NOTICE RELEASE-NOTES bin lib native-jni-lib webapps work

Test3-Docker部属ES+kibana

ES暴露的端口较多,十分耗内存,ES的数据一般挂载在安全目录

# --net somenetwork网络配置
docker run -d --name elasticsearch --net somenetwork -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" elasticsearch:tag


#下载并启动ES
docker run -d --name elasticsearch -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" elasticsearch:7.6.2

#启动之后 服务器会较为卡顿

#查看CPU和内存状态
#docker stats

#增加内存限制 -e环境配置修改
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

CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
db5428acc88d elasticsearch02 0.77% 358.6MiB / 1.795GiB 19.51% 656B / 0B 6.41MB / 729kB 43
^C
[root@VM-0-15-centos ~]# curl localhost:9200
{
"name" : "db5428acc88d",
"cluster_name" : "docker-cluster",
"cluster_uuid" : "MqrmYUWDTT2jYZJHxsVU0A",
"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"
}

可视化

启动portainer

[root@VM-0-15-centos ~]# docker run -d -p 8088:9000 --restart=always -v /var/run/docker.sock:/var/run/docker.sock --privileged=true portainer/portainer
Unable to find image 'portainer/portainer:latest' locally
latest: Pulling from portainer/portainer
d1e017099d17: Pull complete
717377b83d5c: Pull complete
Digest: sha256:f8c2b0a9ca640edf508a8a0830cf1963a1e0d2fd9936a64104b3f658e120b868
Status: Downloaded newer image for portainer/portainer:latest
cb19cef5927877f6e10e15013b81fffdaefd5cb2e426f34819fc869c109ab7b3

commit镜像

#先启动tomcat 并确保在运行
[root@VM-0-15-centos ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
675a7261e3b7 tomcat "catalina.sh run" 55 seconds ago Up 54 seconds 0.0.0.0:8080->8080/tcp heuristic_curie

#进入tomcat
[root@VM-0-15-centos ~]# docker exec -it 675a7261e3b7 /bin/bash

#将webapps中的东西复制上去
root@675a7261e3b7:/usr/local/tomcat# cd webapps
root@675a7261e3b7:/usr/local/tomcat/webapps# ls
root@675a7261e3b7:/usr/local/tomcat/webapps# cd ..
root@675a7261e3b7:/usr/local/tomcat# cp -r webapps.dist/* webapps
root@675a7261e3b7:/usr/local/tomcat# cd webapps
root@675a7261e3b7:/usr/local/tomcat/webapps# ls
ROOT docs examples host-manager manager
root@675a7261e3b7:/usr/local/tomcat/webapps# exit
[root@VM-0-15-centos ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
675a7261e3b7 tomcat "catalina.sh run" 7 minutes ago Up 7 minutes 0.0.0.0:8080->8080/tcp heuristic_curie

#commit一个镜像,-a是作者,-m是描述
[root@VM-0-15-centos ~]# docker commit -a="cinkate" -m="add webapps" 675a7261e3b7 tomcat02:1.0
sha256:80b6126c75b93053ee013c1a724a10fb958ddab21e5b0f3f10a58dbb996c74eb
[root@VM-0-15-centos ~]# docker imgaes
docker: 'imgaes' is not a docker command.
See 'docker --help'

#查看是否commit成功
[root@VM-0-15-centos ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
tomcat02 1.0 80b6126c75b9 8 seconds ago 654MB
nginx latest bc9a0695f571 8 days ago 133MB
tomcat 9.0 e0bd8b34b4ea 2 weeks ago 649MB
tomcat latest e0bd8b34b4ea 2 weeks ago 649MB
centos latest 0d120b6ccaa8 3 months ago 215MB
portainer/portainer latest 62771b0b9b09 4 months ago 79.1MB
elasticsearch 7.6.2 f29a1ee41030 8 months ago 791MB

docker容器数据卷

即使删除了容器,数据还是存在的,类似于数据持久化
容器之间应该有一个数据共享的技术!Docker容器中产生的数据,同步到本地!

这就是卷技术!目录的挂载,将容器的目录,挂载到Linux上面!

总结:为了容器的持久化和同步操作~,容器间也是可以数据共享!

使用数据卷

方式一:直接使用命令来挂载

#-v 主机目录,容器内目录
#-p 主机端口,容器内端口
[root@VM-0-15-centos ~]# docker run -it -v

#将centos /home下的目录 挂载到 主机下/home/ceshi下
[root@VM-0-15-centos home]# docker run -it -v /home/ceshi:/home centos /bin/bash
[root@081342dcbd4f /]#


#另一个terminal(本机的home目录)
[root@VM-0-15-centos ~]# cd /home
[root@VM-0-15-centos home]# ls
ceshi rx.java rxk.java

#查看元信息,挂载成功 Mounts
[root@VM-0-15-centos home]# docker inspect 081342dcbd4f
[
{
"Id": "081342dcbd4f81f7d9d8495b8741dc2270b88d89123f5f422802cece726e75ee",
"Created": "2020-12-03T13:39:28.974545204Z",
"Path": "/bin/bash",
"Args": [],
"State": {
"Status": "running",
"Running": true,
"Paused": false,
"Restarting": false,
"OOMKilled": false,
"Dead": false,
"Pid": 1314,
"ExitCode": 0,
"Error": "",
"StartedAt": "2020-12-03T13:39:29.238082253Z",
"FinishedAt": "0001-01-01T00:00:00Z"
},
"Image": "sha256:0d120b6ccaa8c5e149176798b3501d4dd1885f961922497cd0abef155c869566",
"ResolvConfPath": "/var/lib/docker/containers/081342dcbd4f81f7d9d8495b8741dc2270b88d89123f5f422802cece726e75ee/resolv.conf",
"HostnamePath": "/var/lib/docker/containers/081342dcbd4f81f7d9d8495b8741dc2270b88d89123f5f422802cece726e75ee/hostname",
"HostsPath": "/var/lib/docker/containers/081342dcbd4f81f7d9d8495b8741dc2270b88d89123f5f422802cece726e75ee/hosts",
"LogPath": "/var/lib/docker/containers/081342dcbd4f81f7d9d8495b8741dc2270b88d89123f5f422802cece726e75ee/081342dcbd4f81f7d9d8495b8741dc2270b88d89123f5f422802cece726e75ee-json.log",
"Name": "/clever_lovelace",
"RestartCount": 0,
"Driver": "overlay2",
"Platform": "linux",
"MountLabel": "",
"ProcessLabel": "",
"AppArmorProfile": "",
"ExecIDs": null,
"HostConfig": {
"Binds": [
"/home/ceshi:/home"
],
"ContainerIDFile": "",
"LogConfig": {
"Type": "json-file",
"Config": {}
},
"NetworkMode": "default",
"PortBindings": {},
"RestartPolicy": {
"Name": "no",
"MaximumRetryCount": 0
},
"AutoRemove": false,
"VolumeDriver": "",
"VolumesFrom": null,
"CapAdd": null,
"CapDrop": null,
"Capabilities": null,
"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/519ce3c698154cf997249d71ab41e9203f413522d25e777dc5f8544f2ba22c9e-init/diff:/var/lib/docker/overlay2/9977c7654d8482400f51116d18f3c0562764ac2c1082c8de455e689c10593b30/diff",
"MergedDir": "/var/lib/docker/overlay2/519ce3c698154cf997249d71ab41e9203f413522d25e777dc5f8544f2ba22c9e/merged",
"UpperDir": "/var/lib/docker/overlay2/519ce3c698154cf997249d71ab41e9203f413522d25e777dc5f8544f2ba22c9e/diff",
"WorkDir": "/var/lib/docker/overlay2/519ce3c698154cf997249d71ab41e9203f413522d25e777dc5f8544f2ba22c9e/work"
},
"Name": "overlay2"
},
"Mounts": [
{
"Type": "bind",
"Source": "/home/ceshi",
"Destination": "/home",
"Mode": "",
"RW": true,
"Propagation": "rprivate"
}
],
"Config": {
"Hostname": "081342dcbd4f",
"Domainname": "",
"User": "",
"AttachStdin": true,
"AttachStdout": true,
"AttachStderr": true,
"Tty": true,
"OpenStdin": true,
"StdinOnce": true,
"Env": [
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
],
"Cmd": [
"/bin/bash"
],
"Image": "centos",
"Volumes": null,
"WorkingDir": "",
"Entrypoint": null,
"OnBuild": null,
"Labels": {
"org.label-schema.build-date": "20200809",
"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": "7cc48bb3849fdd8ca238a8ba1f09409e01e7c50856abbccf23d59caaf5997c8d",
"HairpinMode": false,
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"Ports": {},
"SandboxKey": "/var/run/docker/netns/7cc48bb3849f",
"SecondaryIPAddresses": null,
"SecondaryIPv6Addresses": null,
"EndpointID": "6bcd4d80b78f3f8ddeb0ee5468ba2e738509eafd745ca2a5e969ff0fa6dceb08",
"Gateway": "172.18.0.1",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"IPAddress": "172.18.0.2",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"MacAddress": "02:42:ac:12:00:02",
"Networks": {
"bridge": {
"IPAMConfig": null,
"Links": null,
"Aliases": null,
"NetworkID": "df77c62f666112b12946dbbbc16f1dcdbbcc8548e3fa56519fd062e5331a0c08",
"EndpointID": "6bcd4d80b78f3f8ddeb0ee5468ba2e738509eafd745ca2a5e969ff0fa6dceb08",
"Gateway": "172.18.0.1",
"IPAddress": "172.18.0.2",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"MacAddress": "02:42:ac:12:00:02",
"DriverOpts": null
}
}
}
}
]


#容器的home目录下
[root@081342dcbd4f home]# touch test.java
[root@081342dcbd4f home]# ls
test.java

#主机挂载的ceshi目录下
[root@VM-0-15-centos home]# cd ceshi/
[root@VM-0-15-centos ceshi]# ls
test.java

关闭容器之后,在主机中挂载的目录中创建,修改文件,都是可以同步到容器中的目录。

Test4–安装MySQL

#获取镜像
[root@VM-0-15-centos home]# docker pull mysql:5.7
5.7: Pulling from library/mysql
852e50cd189d: Already exists
29969ddb0ffb: Pull complete
a43f41a44c48: Pull complete
5cdd802543a3: Pull complete
b79b040de953: Pull complete
938c64119969: Pull complete
7689ec51a0d9: Pull complete
36bd6224d58f: Pull complete
cab9d3fa4c8c: Pull complete
1b741e1c47de: Pull complete
aac9d11987ac: Pull complete
Digest: sha256:8e2004f9fe43df06c3030090f593021a5f283d028b5ed5765cc24236c2c4d88e
Status: Downloaded newer image for mysql:5.7
docker.io/library/mysql:5.7


#运行容器,需要做数据挂载
# -d后台启动
# -p端口映射
# -v 挂载配置文件 和 数据文件
# -e 修改环境变量,修改密码
# --name 重命名
[root@VM-0-15-centos home]# docker run -d -p 3310: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
2f81782daf7d49e73365da7def107120a8f79c71b9c5bb21a4fc082f2ebef664

#启动成功后,使用本地数据库管理软件可以进行正常连接

假设将容器删除,挂载在本地的数据卷不会丢失,实现了容器的持久化技术。

具名和匿名挂载

#匿名挂载

-v不写本地路径,会匿名进行挂载
docker run -d -P --name nginx01 -v /etc/nginx nginx

#具名挂载
docker run -d -P --name nginx02 -v juming-nginx:/etc/nginx nginx

#通过-v 卷名:容器内路径
#查看这个卷
所有docker容器内的卷,没有指定目录的情况下:
都是在
/var/lib/docker/volumes/xxxx/_data

通过具名挂载,可以方便的找到一个卷,大多数情况使用具名挂载

如何确定是具名还是匿名挂载?还是指定路径挂载?

-v 容器内路径 #匿名挂载
-v 卷名:容器内路径 #具名挂载
-v /宿主机路径:容器内路径 #指定路径挂载

拓展

#通过 -v 容器内路径:ro rw 可以改变读写权限
#ro readonly
#rw readwrite

#一旦设定了容器权限,容器对我们挂载出来的内容就有限定了!
#ro 说明这个路径只能通过宿主机来操作,容器内部无法操作!
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就是用来构建docker镜像的构建文件!通过这个脚本,可以生成镜像,脚本为一个个命令,每个命令都是一层。

#构建一个rxk/centos

[root@VM-0-15-centos home]# cd docker-test-volume/
[root@VM-0-15-centos docker-test-volume]# ls
[root@VM-0-15-centos docker-test-volume]# pwd
/home/docker-test-volume
[root@VM-0-15-centos docker-test-volume]#
[root@VM-0-15-centos docker-test-volume]# nano dockerfile1
#文件中的内容
[root@VM-0-15-centos docker-test-volume]# cat dockerfile1
FROM centos
VOLUME ["volume01","volume02"]
CMD echo "-----end-------"
CMD /bin/bash
[root@VM-0-15-centos docker-test-volume]# docker build -f dockerfile1 -t /rxk/centos .
invalid argument "/rxk/centos" for "-t, --tag" flag: invalid reference format
See 'docker build --help'.
[root@VM-0-15-centos docker-test-volume]# docker build -f dockerfile1 -t rxk/centos .
Sending build context to Docker daemon 2.048kB
Step 1/4 : FROM centos
---> 0d120b6ccaa8
Step 2/4 : VOLUME ["volume01","volume02"]
---> Running in 634e59a80996
Removing intermediate container 634e59a80996
---> 02a6fde9ba35
Step 3/4 : CMD echo "-----end-------"
---> Running in 3fe4feb278df
Removing intermediate container 3fe4feb278df
---> d64085501c38
Step 4/4 : CMD /bin/bash
---> Running in 09d704b706fe
Removing intermediate container 09d704b706fe
---> 7735159af50c
Successfully built 7735159af50c
Successfully tagged rxk/centos:latest


#查看当前镜像
[root@VM-0-15-centos docker-test-volume]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
rxk/centos latest 7735159af50c 5 minutes ago 215MB
tomcat02 1.0 80b6126c75b9 7 hours ago 654MB
nginx latest bc9a0695f571 8 days ago 133MB
mysql 5.7 ae0658fdbad5 12 days ago 449MB
tomcat 9.0 e0bd8b34b4ea 2 weeks ago 649MB
tomcat latest e0bd8b34b4ea 2 weeks ago 649MB
centos latest 0d120b6ccaa8 3 months ago 215MB
portainer/portainer latest 62771b0b9b09 4 months ago 79.1MB
elasticsearch 7.6.2 f29a1ee41030 8 months ago 791MB
#进入自己
[root@VM-0-15-centos docker-test-volume]# docker run -it 7735159af50c /bin/bash
#可以看到挂载的两个volume卷
[root@d6463f570ce4 /]# ls -l
total 56
lrwxrwxrwx 1 root root 7 May 11 2019 bin -> usr/bin
drwxr-xr-x 5 root root 360 Dec 3 15:21 dev
drwxr-xr-x 1 root root 4096 Dec 3 15:21 etc
drwxr-xr-x 2 root root 4096 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 4096 Aug 9 21:40 lost+found
drwxr-xr-x 2 root root 4096 May 11 2019 media
drwxr-xr-x 2 root root 4096 May 11 2019 mnt
drwxr-xr-x 2 root root 4096 May 11 2019 opt
dr-xr-xr-x 91 root root 0 Dec 3 15:21 proc
dr-xr-x--- 2 root root 4096 Aug 9 21:40 root
drwxr-xr-x 11 root root 4096 Aug 9 21:40 run
lrwxrwxrwx 1 root root 8 May 11 2019 sbin -> usr/sbin
drwxr-xr-x 2 root root 4096 May 11 2019 srv
dr-xr-xr-x 13 root root 0 Dec 3 15:21 sys
drwxrwxrwt 7 root root 4096 Aug 9 21:40 tmp
drwxr-xr-x 12 root root 4096 Aug 9 21:40 usr
drwxr-xr-x 20 root root 4096 Aug 9 21:40 var
drwxr-xr-x 2 root root 4096 Dec 3 15:21 volume01
drwxr-xr-x 2 root root 4096 Dec 3 15:21 volume02

#这个卷Volume一定和外部有一个同步的目录
[root@d6463f570ce4 volume01]# touch container.txt
[root@d6463f570ce4 volume01]# ls
container.txt
[root@d6463f570ce4 volume01]# [root@VM-0-15-centos docker-test-volume]#
[root@VM-0-15-centos docker-test-volume]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
d6463f570ce4 7735159af50c "/bin/bash" 7 minutes ago Up 7 minutes zen_faraday
[root@VM-0-15-centos docker-test-volume]# docker inspect d6463f570ce4
[
{
"Id": "d6463f570ce423c10082cce5414bf5ba70b8cb9f0ab47df998fde77b8e965881",
"Created": "2020-12-03T15:21:34.913373526Z",
"Path": "/bin/bash",
"Args": [],
"State": {
"Status": "running",
"Running": true,
"Paused": false,
"Restarting": false,
"OOMKilled": false,
"Dead": false,
"Pid": 15638,
"ExitCode": 0,
"Error": "",
"StartedAt": "2020-12-03T15:21:35.202804066Z",
"FinishedAt": "0001-01-01T00:00:00Z"
},
"Image": "sha256:7735159af50c4ff09863f0a97c37447043ac0eca6657913a4e33c65b0be4a24d",
"ResolvConfPath": "/var/lib/docker/containers/d6463f570ce423c10082cce5414bf5ba70b8cb9f0ab47df998fde77b8e965881/resolv.conf",
"HostnamePath": "/var/lib/docker/containers/d6463f570ce423c10082cce5414bf5ba70b8cb9f0ab47df998fde77b8e965881/hostname",
"HostsPath": "/var/lib/docker/containers/d6463f570ce423c10082cce5414bf5ba70b8cb9f0ab47df998fde77b8e965881/hosts",
"LogPath": "/var/lib/docker/containers/d6463f570ce423c10082cce5414bf5ba70b8cb9f0ab47df998fde77b8e965881/d6463f570ce423c10082cce5414bf5ba70b8cb9f0ab47df998fde77b8e965881-json.log",
"Name": "/zen_faraday",
"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,
"Capabilities": null,
"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/16864c6fe5942b10aff31e1156dbb08a055e31975f8725d25a205bd9f76b6f23-init/diff:/var/lib/docker/overlay2/9977c7654d8482400f51116d18f3c0562764ac2c1082c8de455e689c10593b30/diff",
"MergedDir": "/var/lib/docker/overlay2/16864c6fe5942b10aff31e1156dbb08a055e31975f8725d25a205bd9f76b6f23/merged",
"UpperDir": "/var/lib/docker/overlay2/16864c6fe5942b10aff31e1156dbb08a055e31975f8725d25a205bd9f76b6f23/diff",
"WorkDir": "/var/lib/docker/overlay2/16864c6fe5942b10aff31e1156dbb08a055e31975f8725d25a205bd9f76b6f23/work"
},
"Name": "overlay2"
},
"Mounts": [
{
"Type": "volume",
"Name": "4bb7c13d437e16eb97bfcc71aa2faac18594ded837fcefc6d266e8ad36845c6a",
"Source": "/var/lib/docker/volumes/4bb7c13d437e16eb97bfcc71aa2faac18594ded837fcefc6d266e8ad36845c6a/_data",
"Destination": "volume01",
"Driver": "local",
"Mode": "",
"RW": true,
"Propagation": ""
},
{
"Type": "volume",
"Name": "0eca9d146b2fd63f434657516305c20241da68936914059527e728865109e3f1",
"Source": "/var/lib/docker/volumes/0eca9d146b2fd63f434657516305c20241da68936914059527e728865109e3f1/_data",
"Destination": "volume02",
"Driver": "local",
"Mode": "",
"RW": true,
"Propagation": ""
}
],
"Config": {
"Hostname": "d6463f570ce4",
"Domainname": "",
"User": "",
"AttachStdin": true,
"AttachStdout": true,
"AttachStderr": true,
"Tty": true,
"OpenStdin": true,
"StdinOnce": true,
"Env": [
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
],
"Cmd": [
"/bin/bash"
],
"Image": "7735159af50c",
"Volumes": {
"volume01": {},
"volume02": {}
},
"WorkingDir": "",
"Entrypoint": null,
"OnBuild": null,
"Labels": {
"org.label-schema.build-date": "20200809",
"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": "cf151107d8fa56fd220695eed265b431618350222be583761b13354867477e39",
"HairpinMode": false,
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"Ports": {},
"SandboxKey": "/var/run/docker/netns/cf151107d8fa",
"SecondaryIPAddresses": null,
"SecondaryIPv6Addresses": null,
"EndpointID": "1c1bab6bce8a119f4731a2555a39256791d792539b260d2fd230aea73940d75b",
"Gateway": "172.18.0.1",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"IPAddress": "172.18.0.2",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"MacAddress": "02:42:ac:12:00:02",
"Networks": {
"bridge": {
"IPAMConfig": null,
"Links": null,
"Aliases": null,
"NetworkID": "df77c62f666112b12946dbbbc16f1dcdbbcc8548e3fa56519fd062e5331a0c08",
"EndpointID": "1c1bab6bce8a119f4731a2555a39256791d792539b260d2fd230aea73940d75b",
"Gateway": "172.18.0.1",
"IPAddress": "172.18.0.2",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"MacAddress": "02:42:ac:12:00:02",
"DriverOpts": null
}
}
}
}
]

数据卷容器

不同容器之间同步数据

#docker01已经启动了
[root@VM-0-15-centos _data]# docker run -it --name docker02 --volumes-from docker01 rxk/centos

#--volumes-from类似于 docker02继承docker01

#即使docker01被删了,docker02中卷的文件也是存在的,类似硬链接

DockerFile

dockerfile是用来构建docker镜像的文件!命令参数脚本!

构建步骤:

1.编写一个dockerfile文件

2.docker build构建成为一个镜像

3.docker run运行镜像

4.docker push发布镜像(DockerHub、阿里云镜像仓库!)

很多官方镜像都是基础包,很多功能没有,通常会自己搭建自己的镜像。

DockerFile的构建过程

基础知识

1.每个保留关键字(指令)都必须是大写字母

2.执行从上到下顺序执行

3.# 表示注释

4.每一个指令都会创建提交一个新的镜像层 并提交

DockerFile:构建文件,定义了一切的步骤,源代码。

DockerImages:通过DockerFile构建生成的镜像,最终发布和运行的产品

Docker容器:容器就是镜像运行起来提供服务的

DockerFile的指令

FROM  # 基础镜像,一切从这里开始构建

MAINTAINER #镜像是谁写的,姓名+邮箱

RUN #镜像构建的时候需要运行的命令

ADD #步骤:构建基于tomcat的镜像,进行添加!ADD为添加内容

WORKDIR #镜像的工作目录

VOLUME #挂载的容器卷

EXPOSE #指定暴露端口

CMD #指定这个容器启动时候要运行的命令,只有最后一个会生效,可被替代

ENTRYPOINT #指定这个容器启动的时候要运行的命令,可以追加命令

ONBUILD #当构建一个被继承DockerFile, 这个时候就会运行ONBUILD命令。触发指令

COPY #类似ADD命令 ,将文件拷贝到镜像中

ENV #构建时候设置环境变量

构建自己的centos

构建自己的centos

#1.编写dockerfile的文件
FROM centos
MAINTAINER kuangshen<179049243@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.通过文件构建镜像
# docker build -f dockerfile文件路径 -t 镜像名:[tag].
#docker build -f my-dockerfile -t mycentos:0.1 .
[root@VM-0-15-centos dockerfile]# docker build -f my-dockerfile -t mycentos:0.1 .
Sending build context to Docker daemon 2.048kB
Step 1/10 : FROM centos
---> 0d120b6ccaa8
Step 2/10 : MAINTAINER kuangshen<179049243@qq.com>
---> Running in 3dd9d64bfbff
Removing intermediate container 3dd9d64bfbff
---> e56a7b5f722b
Step 3/10 : ENV MYPATH /usr/local
---> Running in 7707c6ee0441
Removing intermediate container 7707c6ee0441
---> b67dab755631
Step 4/10 : WORKDIR $MYPATH
---> Running in 1797c746ab6b
Removing intermediate container 1797c746ab6b
---> 3ed5689097b4
Step 5/10 : RUN yum -y install vim
---> Running in 5791c022d132
CentOS-8 - AppStream 969 kB/s | 6.2 MB 00:06
CentOS-8 - Base 950 kB/s | 2.3 MB 00:02
CentOS-8 - Extras 11 kB/s | 8.1 kB 00:00
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 327 kB/s | 39 kB 00:00
(2/5): vim-filesystem-8.0.1763-15.el8.noarch.rp 827 kB/s | 48 kB 00:00
(3/5): which-2.21-12.el8.x86_64.rpm 316 kB/s | 49 kB 00:00
(4/5): vim-enhanced-8.0.1763-15.el8.x86_64.rpm 1.2 MB/s | 1.4 MB 00:01
(5/5): vim-common-8.0.1763-15.el8.x86_64.rpm 983 kB/s | 6.3 MB 00:06
--------------------------------------------------------------------------------
Total 974 kB/s | 7.8 MB 00:08
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 5791c022d132
---> 05dc9bde286e
Step 6/10 : RUN yum -y install net-tools
---> Running in 900fc6c0b10e
Last metadata expiration check: 0:00:15 ago on Thu Dec 10 15:07:33 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 969 kB/s | 322 kB 00:00
--------------------------------------------------------------------------------
Total 181 kB/s | 322 kB 00:01
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 900fc6c0b10e
---> 3f8796ecbdea
Step 7/10 : EXPOSE 80
---> Running in 37e6f3792548
Removing intermediate container 37e6f3792548
---> 2d37cf00b36b
Step 8/10 : CMD echo $MYPATH
---> Running in 7e4ff55e4b24
Removing intermediate container 7e4ff55e4b24
---> d74bce644e74
Step 9/10 : CMD echo "----end----"
---> Running in fc3301142b73
Removing intermediate container fc3301142b73
---> 2c7e307a481c
Step 10/10 : CMD /bin/bash
---> Running in 4e5c6edd147c
Removing intermediate container 4e5c6edd147c
---> 071c7fb7d0f9
Successfully built 071c7fb7d0f9
Successfully tagged mycentos:0.1



#3.测试镜像
[root@VM-0-15-centos dockerfile]# docker run -it mycentos:0.1
[root@5b68abc14a5a local]# pwd
/usr/local
[root@5b68abc14a5a local]# vim

sh: wq: command not found

shell returned 127

Press ENTER or type command to continue
sh: wq: command not found

shell returned 127

Press ENTER or type command to continue

镜像构建历史查看

[root@VM-0-15-centos dockerfile]# docker history 071c7fb7d0f9
IMAGE CREATED CREATED BY SIZE COMMENT
071c7fb7d0f9 6 minutes ago /bin/sh -c #(nop) CMD ["/bin/sh" "-c" "/bin… 0B
2c7e307a481c 6 minutes ago /bin/sh -c #(nop) CMD ["/bin/sh" "-c" "echo… 0B
d74bce644e74 6 minutes ago /bin/sh -c #(nop) CMD ["/bin/sh" "-c" "echo… 0B
2d37cf00b36b 6 minutes ago /bin/sh -c #(nop) EXPOSE 80 0B
3f8796ecbdea 6 minutes ago /bin/sh -c yum -y install net-tools 23.1MB
05dc9bde286e 6 minutes ago /bin/sh -c yum -y install vim 57.7MB
3ed5689097b4 7 minutes ago /bin/sh -c #(nop) WORKDIR /usr/local 0B
b67dab755631 7 minutes ago /bin/sh -c #(nop) ENV MYPATH=/usr/local 0B
e56a7b5f722b 7 minutes ago /bin/sh -c #(nop) MAINTAINER kuangshen<1790… 0B
0d120b6ccaa8 4 months ago /bin/sh -c #(nop) CMD ["/bin/bash"] 0B
<missing> 4 months ago /bin/sh -c #(nop) LABEL org.label-schema.sc… 0B
<missing> 4 months ago /bin/sh -c #(nop) ADD file:538afc0c5c964ce0d… 215MB

实战:Dockerfile制作tomcat镜像

1、准备镜像文件tomcat压缩包,jdk的压缩包!
2、编写dockerfile文件。

Docker0网络详解

#删除所有镜像
[root@VM-0-15-centos ~]# docker rmi -f $(docker images -aq)
Untagged: rxk/centos:latest
Deleted: sha256:7735159af50c4ff09863f0a97c37447043ac0eca6657913a4e33c65b0be4a24d
Deleted: sha256:d64085501c38257f9828c1dc9717f26e20df9bcb8d1b958b7f49ea5bb0425ae0
Deleted: sha256:02a6fde9ba357c11d75c6d828c8fee80e1e5e77c4aedb3a83c7e302fc1745d40
Untagged: tomcat02:1.0
Deleted: sha256:80b6126c75b93053ee013c1a724a10fb958ddab21e5b0f3f10a58dbb996c74eb
Deleted: sha256:20e9e09986f8d937efa6f2ad283aa9a1b837cc5cc5d4d76e6105f83e38e8f3de
Untagged: nginx:latest
Untagged: nginx@sha256:6b1daa9462046581ac15be20277a7c75476283f969cb3a61c8725ec38d3b01c3
Deleted: sha256:bc9a0695f5712dcaaa09a5adc415a3936ccba13fc2587dfd76b1b8aeea3f221c
Untagged: mysql:5.7
Untagged: mysql@sha256:8e2004f9fe43df06c3030090f593021a5f283d028b5ed5765cc24236c2c4d88e
Deleted: sha256:ae0658fdbad5fb1c9413c998d8a573eeb5d16713463992005029c591e6400d02
Untagged: tomcat:9.0
Untagged: tomcat:latest
Untagged: tomcat@sha256:a319b10d8729817c7ce0bcc2343a6f97711c7870395019340d96b6aafd6ccbea
Deleted: sha256:e0bd8b34b4ea904874e55eae50e8987815030d140f9773a4b61759f4f85bf38d
Untagged: portainer/portainer:latest
Untagged: portainer/portainer@sha256:f8c2b0a9ca640edf508a8a0830cf1963a1e0d2fd9936a64104b3f658e120b868
Deleted: sha256:62771b0b9b0973a3e8e95595534a1240d8cfd968d30ec82dc0393ce0a256c5f3
Untagged: elasticsearch:7.6.2
Untagged: elasticsearch@sha256:1b09dbd93085a1e7bca34830e77d2981521a7210e11f11eda997add1c12711fa
Deleted: sha256:f29a1ee41030e3963026369105f3bee76d75fdecbeca07932ac054126be7bff9
Error response from daemon: conflict: unable to delete 071c7fb7d0f9 (cannot be forced) - image is being used by running container 5b68abc14a5a
Error response from daemon: conflict: unable to delete 3f8796ecbdea (cannot be forced) - image has dependent child images
Error response from daemon: conflict: unable to delete d74bce644e74 (cannot be forced) - image has dependent child images
Error response from daemon: conflict: unable to delete 2d37cf00b36b (cannot be forced) - image has dependent child images
Error response from daemon: conflict: unable to delete 2c7e307a481c (cannot be forced) - image has dependent child images
Error response from daemon: conflict: unable to delete 05dc9bde286e (cannot be forced) - image has dependent child images
Error response from daemon: conflict: unable to delete 3ed5689097b4 (cannot be forced) - image has dependent child images
Error response from daemon: conflict: unable to delete e56a7b5f722b (cannot be forced) - image has dependent child images
Error response from daemon: conflict: unable to delete b67dab755631 (cannot be forced) - image has dependent child images
Error: No such image: 02a6fde9ba35
Error: No such image: d64085501c38
Error: No such image: e0bd8b34b4ea
Error response from daemon: conflict: unable to delete 0d120b6ccaa8 (cannot be forced) - image has dependent child images

三个网络
image

#启动一个tomcat
[root@VM-0-15-centos ~]# docker run -d -P --name tomcat02 tomcat
942539fdda0c018ffa3750661373e624c4f2226f5d9532323d5c42c1daea98db
[root@VM-0-15-centos ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
942539fdda0c tomcat "catalina.sh run" 3 seconds ago Up 3 seconds 0.0.0.0:32768->8080/tcp tomcat02



#查看容器的内部网络地址
[root@VM-0-15-centos ~]# docker exec -it tomcat02 ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
112: eth0@if113: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
link/ether 02:42:ac:12:00:02 brd ff:ff:ff:ff:ff:ff link-netnsid 0
inet 172.18.0.2/16 brd 172.18.255.255 scope global eth0
valid_lft forever preferred_lft forever

linux可以ping通docker容器内部

原理

1.我们每安装一个docker容器,docker就会给docker容器分配一个ip,我们只要安装了docker,就会有一个网卡,docker0,使用桥接模式,使用技术是veth-pair技术!

再次测试ip addr:

image

2.再启动一个容器测试,又会多一对网卡,这样一对对的网卡,其实是veth-pair技术,就是一对的虚拟设备,他们都是成对出现,一段连着协议,一段彼此相连,veth-pair充当一个桥梁,链接各种虚拟网络设备
image

3.测试下tomcat02和tomcat03能否ping通,确实可以ping通

容器和容器之间是可以互相ping通的

[root@VM-0-15-centos ~]# docker exec -it tomcat03 ping 172.18.0.2
PING 172.18.0.2 (172.18.0.2) 56(84) bytes of data.
64 bytes from 172.18.0.2: icmp_seq=1 ttl=64 time=0.076 ms
64 bytes from 172.18.0.2: icmp_seq=2 ttl=64 time=0.054 ms
64 bytes from 172.18.0.2: icmp_seq=3 ttl=64 time=0.053 ms
^C
--- 172.18.0.2 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 0.053/0.061/0.076/0.010 ms

结论:tomcat02和tomcat03共用一个路由器,docker0

所有容器不指定网络的情况下,都是由docker0路由的,docker会给我们容器分配一个默认的可用IP

当把docker容器删除之后,ip addr之后 容器ip就没了

[root@VM-0-15-centos ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
be137857cf4e tomcat "catalina.sh run" 29 minutes ago Up 29 minutes 0.0.0.0:32769->8080/tcp tomcat03
942539fdda0c tomcat "catalina.sh run" 37 minutes ago Up 37 minutes 0.0.0.0:32768->8080/tcp tomcat02
[root@VM-0-15-centos ~]# docker rm -f be137857cf4e
be137857cf4e
[root@VM-0-15-centos ~]# docker rm -f 942539fdda0c
942539fdda0c
[root@VM-0-15-centos ~]# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether 52:54:00:83:af:57 brd ff:ff:ff:ff:ff:ff
inet 172.17.0.15/20 brd 172.17.15.255 scope global eth0
valid_lft forever preferred_lft forever
inet6 fe80::5054:ff:fe83:af57/64 scope link
valid_lft forever preferred_lft forever
3: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default
link/ether 02:42:18:37:f9:06 brd ff:ff:ff:ff:ff:ff
inet 172.18.0.1/16 brd 172.18.255.255 scope global docker0
valid_lft forever preferred_lft forever
inet6 fe80::42:18ff:fe37:f906/64 scope link
valid_lft forever preferred_lft forever

使用服务名去ping通tomcat

docker run -d -P tomcat03 --link tomcat02 tomcat

docker exec -it tomcat03 ping tomcat02

#此时3能ping 通2,但是2 ping不通3

Docker自定义网络

查看docker所有网络

[root@VM-0-15-centos ~]# docker network ls
NETWORK ID NAME DRIVER SCOPE
df77c62f6661 bridge bridge local
c916a7eaedff host host local
00b73cedd526 none null local

网络模式

bridge:桥接 bridge(默认)

none:不配置网络

host:和宿主机共享网络

container:容器内网络连通(使用较少)

创建自己的自定义网络

–driver bridge 默认桥接

–subnet 192.168.0.0/16 子网地址

–gateway 192.168.0.1 网关地址

[root@VM-0-15-centos ~]# docker network create --driver bridge --subnet 192.168.0.0/16 --gateway 192.168.0.1 mynet

[root@VM-0-15-centos ~]# docker network ls
NETWORK ID NAME DRIVER SCOPE
df77c62f6661 bridge bridge local
c916a7eaedff host host local
f5100a69756f mynet bridge local
00b73cedd526 none null local

[root@VM-0-15-centos ~]# docker network inspect mynet
[
{
"Name": "mynet",
"Id": "f5100a69756fbedf28ab9ad7ecbf354417328efc06d7f0bfae40a0d4c7d33de4",
"Created": "2020-12-22T11:03:05.693800981+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": {}
}
]

#启动两个容器
[root@VM-0-15-centos ~]# docker run -d -P --name tomcat-net-01 --network mynet tomcat
8fc4551bbad9d836cea86a3feb957596af6e1310781eadee1baacbb177d84a33
[root@VM-0-15-centos ~]# docker run -d -P --name tomcat-net-02 --network mynet tomcat
01a3d2a47af6a79689dc85e0a110d576cbdfa8bb979d25d7f493b13157b3e26a
[root@VM-0-15-centos ~]# docker network inspect mynet
[
{
"Name": "mynet",
"Id": "f5100a69756fbedf28ab9ad7ecbf354417328efc06d7f0bfae40a0d4c7d33de4",
"Created": "2020-12-22T11:03:05.693800981+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": {
"01a3d2a47af6a79689dc85e0a110d576cbdfa8bb979d25d7f493b13157b3e26a": {
"Name": "tomcat-net-02",
"EndpointID": "25be3c90c1e1a4b74f5fc9e10a59c50029ca7ff3bf692d7de636738edb3457b3",
"MacAddress": "02:42:c0:a8:00:03",
"IPv4Address": "192.168.0.3/16",
"IPv6Address": ""
},
"8fc4551bbad9d836cea86a3feb957596af6e1310781eadee1baacbb177d84a33": {
"Name": "tomcat-net-01",
"EndpointID": "a83c09df1a4595735453dafdde352123dd024707400716fbab256c7e3c02ea4a",
"MacAddress": "02:42:c0:a8:00:02",
"IPv4Address": "192.168.0.2/16",
"IPv6Address": ""
}
},
"Options": {},
"Labels": {}
}
]

#再次测试,不再使用--link 也是可以连接通的,不管使用ip还是服务名
[root@VM-0-15-centos ~]# docker exec -it tomcat-net-01 ping 192.168.0.3
PING 192.168.0.3 (192.168.0.3) 56(84) bytes of data.
64 bytes from 192.168.0.3: icmp_seq=1 ttl=64 time=0.085 ms
64 bytes from 192.168.0.3: icmp_seq=2 ttl=64 time=0.055 ms
64 bytes from 192.168.0.3: icmp_seq=3 ttl=64 time=0.053 ms
^C
--- 192.168.0.3 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 1000ms
rtt min/avg/max/mdev = 0.053/0.064/0.085/0.016 ms
[root@VM-0-15-centos ~]# docker exec -it tomcat-net-01 ping tomcat-net-02
PING tomcat-net-02 (192.168.0.3) 56(84) bytes of data.
64 bytes from tomcat-net-02.mynet (192.168.0.3): icmp_seq=1 ttl=64 time=0.050 ms
64 bytes from tomcat-net-02.mynet (192.168.0.3): icmp_seq=2 ttl=64 time=0.052 ms
64 bytes from tomcat-net-02.mynet (192.168.0.3): icmp_seq=3 ttl=64 time=0.053 ms
^C
--- tomcat-net-02 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2ms
rtt min/avg/max/mdev = 0.050/0.051/0.053/0.008 ms

我们自定义的网络docker 都已经帮我们维护好了对应的关系,推荐这样使用网络!

好处:
不同的集群使用不同的网络,保证集群是安全和健康

网络连通

把一个容器连接到网络上

#将tomcat01连接到mynet网络下,一个容器两个ip

docker network connect mynet tomcat01

Redis集群实战

通过脚本创建六个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
daemonize no
appendonly yes
EOF
done

启动redis

docker run -p 6371:6379 -p 16371:16379 --name redis-1 -v /mydata/redis/node-1/data:/data -v /mydata/redis/node-1/conf/redis.conf:/etc/redis/redis.conf -d --net redis --ip 172.38.0.11 redis:5.0.9-alpine3.11 redis-server /etc/redis/redis.conf


docker run -p 6372:6379 -p 16372:16379 --name redis-2 -v /mydata/redis/node-2/data:/data -v /mydata/redis/node-2/conf/redis.conf:/etc/redis/redis.conf -d --net redis --ip 172.38.0.12 redis:5.0.9-alpine3.11 redis-server /etc/redis/redis.conf


docker run -p 6373:6379 -p 16373:16379 --name redis-3 -v /mydata/redis/node-3/data:/data -v /mydata/redis/node-3/conf/redis.conf:/etc/redis/redis.conf -d --net redis --ip 172.38.0.13 redis:5.0.9-alpine3.11 redis-server /etc/redis/redis.conf

docker run -p 6374:6379 -p 16374:16379 --name redis-4 -v /mydata/redis/node-4/data:/data -v /mydata/redis/node-4/conf/redis.conf:/etc/redis/redis.conf -d --net redis --ip 172.38.0.14 redis:5.0.9-alpine3.11 redis-server /etc/redis/redis.conf


docker run -p 6375:6379 -p 16375:16379 --name redis-5 -v /mydata/redis/node-5/data:/data -v /mydata/redis/node-5/conf/redis.conf:/etc/redis/redis.conf -d --net redis --ip 172.38.0.15 redis:5.0.9-alpine3.11 redis-server /etc/redis/redis.conf

docker run -p 6376:6379 -p 16376:16379 --name redis-6 -v /mydata/redis/node-6/data:/data -v /mydata/redis/node-6/conf/redis.conf:/etc/redis/redis.conf -d --net redis --ip 172.38.0.16 redis:5.0.9-alpine3.11 redis-server /etc/redis/redis.conf

#正常启动之后
[root@VM-0-15-centos ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
e1535aac14ce redis:5.0.9-alpine3.11 "docker-entrypoint.s…" 22 seconds ago Up 22 seconds 0.0.0.0:6376->6379/tcp, 0.0.0.0:16376->16379/tcp redis-6
fcf18ac7033d redis:5.0.9-alpine3.11 "docker-entrypoint.s…" 31 seconds ago Up 30 seconds 0.0.0.0:6375->6379/tcp, 0.0.0.0:16375->16379/tcp redis-5
b17f66d41588 redis:5.0.9-alpine3.11 "docker-entrypoint.s…" 37 seconds ago Up 37 seconds 0.0.0.0:6374->6379/tcp, 0.0.0.0:16374->16379/tcp redis-4
afb2f4e6484e redis:5.0.9-alpine3.11 "docker-entrypoint.s…" 44 seconds ago Up 44 seconds 0.0.0.0:6373->6379/tcp, 0.0.0.0:16373->16379/tcp redis-3
ef59db5b0cc0 redis:5.0.9-alpine3.11 "docker-entrypoint.s…" 54 seconds ago Up 53 seconds 0.0.0.0:6372->6379/tcp, 0.0.0.0:16372->16379/tcp redis-2
0eca360704d7 redis:5.0.9-alpine3.11 "docker-entrypoint.s…" About a minute ago Up About a minute 0.0.0.0:6371->6379/tcp, 0.0.0.0:16371->16379/tcp redis-1

#进入redis-1
[root@VM-0-15-centos ~]# docker exec -it redis-1 /bin/sh
/data #

#创建redis集群
[root@VM-0-15-centos ~]# docker exec -it redis-1 /bin/sh
/data # 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 --cluster-replicas 1
>>> Performing hash slots allocation on 6 nodes...
Master[0] -> Slots 0 - 5460
Master[1] -> Slots 5461 - 10922
Master[2] -> Slots 10923 - 16383
Adding replica 172.38.0.15:6379 to 172.38.0.11:6379
Adding replica 172.38.0.16:6379 to 172.38.0.12:6379
Adding replica 172.38.0.14:6379 to 172.38.0.13:6379
M: f70e64b741bad779e2b545b1429b47b2732a9a13 172.38.0.11:6379
slots:[0-5460] (5461 slots) master
M: de19aadcb9d25a77ca0e5a23f1c45f31a6ece84d 172.38.0.12:6379
slots:[5461-10922] (5462 slots) master
M: 43b45750adfaea90314c724dd1b800621f6b40bf 172.38.0.13:6379
slots:[10923-16383] (5461 slots) master
S: 13b65b47fcac7126bf6ca15a322037571c90464f 172.38.0.14:6379
replicates 43b45750adfaea90314c724dd1b800621f6b40bf
S: 03e58c163b80baf32990d6faf3a104d97e14f1e4 172.38.0.15:6379
replicates f70e64b741bad779e2b545b1429b47b2732a9a13
S: b80d23b1516da408f9f9bad22007ce4389e529ca 172.38.0.16:6379
replicates de19aadcb9d25a77ca0e5a23f1c45f31a6ece84d
Can I set the above configuration? (type 'yes' to accept): yes
>>> Nodes configuration updated
>>> Assign a different config epoch to each node
>>> Sending CLUSTER MEET messages to join the cluster
Waiting for the cluster to join
...
>>> Performing Cluster Check (using node 172.38.0.11:6379)
M: f70e64b741bad779e2b545b1429b47b2732a9a13 172.38.0.11:6379
slots:[0-5460] (5461 slots) master
1 additional replica(s)
M: de19aadcb9d25a77ca0e5a23f1c45f31a6ece84d 172.38.0.12:6379
slots:[5461-10922] (5462 slots) master
1 additional replica(s)
S: 13b65b47fcac7126bf6ca15a322037571c90464f 172.38.0.14:6379
slots: (0 slots) slave
replicates 43b45750adfaea90314c724dd1b800621f6b40bf
S: 03e58c163b80baf32990d6faf3a104d97e14f1e4 172.38.0.15:6379
slots: (0 slots) slave
replicates f70e64b741bad779e2b545b1429b47b2732a9a13
M: 43b45750adfaea90314c724dd1b800621f6b40bf 172.38.0.13:6379
slots:[10923-16383] (5461 slots) master
1 additional replica(s)
S: b80d23b1516da408f9f9bad22007ce4389e529ca 172.38.0.16:6379
slots: (0 slots) slave
replicates de19aadcb9d25a77ca0e5a23f1c45f31a6ece84d
[OK] All nodes agree about slots configuration.
>>> Check for open slots...
>>> Check slots coverage...
[OK] All 16384 slots covered.


/data # redis-cli -c
127.0.0.1:6379> cluster info
cluster_state:ok
cluster_slots_assigned:16384
cluster_slots_ok:16384
cluster_slots_pfail:0
cluster_slots_fail:0
cluster_known_nodes:6
cluster_size:3
cluster_current_epoch:6
cluster_my_epoch:1
cluster_stats_messages_ping_sent:149
cluster_stats_messages_pong_sent:140
cluster_stats_messages_sent:289
cluster_stats_messages_ping_received:135
cluster_stats_messages_pong_received:149
cluster_stats_messages_meet_received:5
cluster_stats_messages_received:289

127.0.0.1:6379> cluster nodes
de19aadcb9d25a77ca0e5a23f1c45f31a6ece84d 172.38.0.12:6379@16379 master - 0 1608624786213 2 conn61-10922
13b65b47fcac7126bf6ca15a322037571c90464f 172.38.0.14:6379@16379 slave 43b45750adfaea90314c724ddf6b40bf 0 1608624785000 4 connected
03e58c163b80baf32990d6faf3a104d97e14f1e4 172.38.0.15:6379@16379 slave f70e64b741bad779e2b545b1432a9a13 0 1608624785000 5 connected
43b45750adfaea90314c724dd1b800621f6b40bf 172.38.0.13:6379@16379 master - 0 1608624785210 3 conn923-16383
b80d23b1516da408f9f9bad22007ce4389e529ca 172.38.0.16:6379@16379 slave de19aadcb9d25a77ca0e5a23f6ece84d 0 1608624785712 6 connected
f70e64b741bad779e2b545b1429b47b2732a9a13 172.38.0.11:6379@16379 myself,master - 0 1608624785000cted 0-5460
127.0.0.1:6379> set a b
-> Redirected to slot [15495] located at 172.38.0.13:6379
OK

172.38.0.13:6379> get a
^C
#即使把redis-3 stop了,仍然可以通过其他slaver找到key a所对应的值b,主从配置成功
/data # redis-cli -c
127.0.0.1:6379> get a
-> Redirected to slot [15495] located at 172.38.0.14:6379
"b"
172.38.0.14:6379>

搭建redis集群完成

image

Author: CinKate
Link: http://renxingkai.github.io/2020/12/01/docker-learning/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.