有狂神视频所做笔记。适用于有Linux基础知识(必要)和SpringBoot。视频地址:https://www.bilibili.com/video/BV1og4y1q7M4?p=6&spm_id_from=pageDriver
一款产品:开发–上线 两套环境! 应用环境,应用配置!
开发 — 运维:
# 系统内核是3.10以上的
[root@haodop1 ~]# uname -r
3.10.0-957.el7.x86_64
# 存储系统信息的文件 /etc/os-release
[root@haodop1 ~]# cat /etc/os-release
NAME="CentOS Linux"
VERSION="7 (Core)"
ID="centos"
ID_LIKE="rhel fedora"
VERSION_ID="7"
PRETTY_NAME="CentOS Linux 7 (Core)"
ANSI_COLOR="0;31"
CPE_NAME="cpe:/o:centos:centos:7"
HOME_URL="https://www.centos.org/"
BUG_REPORT_URL="https://bugs.centos.org/"
CENTOS_MANTISBT_PROJECT="CentOS-7"
CENTOS_MANTISBT_PROJECT_VERSION="7"
REDHAT_SUPPORT_PRODUCT="centos"
REDHAT_SUPPORT_PRODUCT_VERSION="7"
#1.卸载旧版本的Docker
[root@haodop1 ~]# yum remove docker \
> docker-client \
> docker-client-latest \
> docker-common \
> docker-latest \
> docker-latest-logrotate \
> docker-logrotate \
> docker-engine
#2.安装需要的安装包
[root@haodop1 ~]# yum install -y yum-utils
#3、默认的Docker自己的仓库镜像地址,国外的 下载速度慢
yum-config-manager \
--add-repo \
https://download.docker.com/linux/centos/docker-ce.repo
#阿里云的仓库镜像地址,推荐这个
yum-config-manager \
--add-repo \
http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
[root@localhost ~]# yum makecache fast
已加载插件:fastestmirror, langpacks
Loading mirror speeds from cached hostfile
* base: mirrors.tuna.tsinghua.edu.cn
* extras: mirrors.tuna.tsinghua.edu.cn
* updates: mirrors.tuna.tsinghua.edu.cn
base | 3.6 kB 00:00:00
docker-ce-stable | 3.5 kB 00:00:00
extras | 2.9 kB 00:00:00
updates | 2.9 kB 00:00:00
元数据缓存已建立
#4.安装docker相关的内容(最新版) docker-ce 社区版(推荐) ee 企业版
#安装时 中途会提示你是否安装 需要输入 y 确定
yum install docker-ce docker-ce-cli containerd.io
#安装时指定版本
yum install docker-ce-<VERSION_STRING> docker-ce-cli-<VERSION_STRING> containerd.io
#5.启动docker,docker相当于一个服务了
systemctl start docker
# 设置开机自启动
systemctl enable docker
#6.查看docker版本
[root@localhost ~]# docker version
Client: Docker Engine - Community
Version: 20.10.8 #版本号
API version: 1.41
Go version: go1.16.6
Git commit: 3967b7d
Built: Fri Jul 30 19:55:49 2021
OS/Arch: linux/amd64
Context: default
Experimental: true
Server: Docker Engine - Community #社区版
Engine:
Version: 20.10.8
API version: 1.41 (minimum version 1.12)
Go version: go1.16.6
Git commit: 75249d8
Built: Fri Jul 30 19:54:13 2021
OS/Arch: linux/amd64 #Linux系统
Experimental: false
containerd:
Version: 1.4.9
GitCommit: e25210fe30a0a703442421b0f60afac609f950a3
runc:
Version: 1.0.1
GitCommit: v1.0.1-0-g4144b63
docker-init:
Version: 0.19.0
GitCommit: de40ad0
# 7.启动 官方的 hello-world 镜像
[root@localhost ~]# docker run hello-world
Unable to find image 'hello-world:latest' locally #找不到hello-world镜像 尝试去下载
latest: Pulling from library/hello-world #远程拉取镜像
2db29710123e: Pull complete
Digest: sha256:393b81f0ea5a98a7335d7ad44be96fe76ca8eb2eaa76950eb8c989ebf2b78ec0
Status: Downloaded newer image for hello-world:latest
Hello from Docker! #docker已经安装成功了
This message shows that your installation appears to be working correctly.
To generate this message, Docker took the following steps:
1. The Docker client contacted the Docker daemon.
2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
(amd64)
3. The Docker daemon created a new container from that image which runs the
executable that produces the output you are currently reading.
4. The Docker daemon streamed that output to the Docker client, which sent it
to your terminal.
To try something more ambitious, you can run an Ubuntu container with:
$ docker run -it ubuntu bash
Share images, automate workflows, and more with a free Docker ID:
https://hub.docker.com/
For more examples and ideas, visit:
https://docs.docker.com/get-started/
#8.查看下载的这个hello-word镜像
[root@localhost ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
hello-world latest feb5d9fea6a5 26 hours ago 13.3kB
#1.卸载依赖
sudo yum remove docker-ce docker-ce-cli containerd.io
#2.删除资源
sudo rm -rf /var/lib/docker
sudo rm -rf /var/lib/containerd
sudo mkdir -p /etc/docker
sudo tee /etc/ docker/daemon. json <<-' EOF '
{
"registry- mirrors": ["https://qiyb9988.mirror. aliyuncs. com"]
}
EOF
sudo systemct1 daemon-reload
sudo systemct1 restart docker
#镜像找不到错误
[root@localhost docker]# docker run 666666666
Unable to find image '666666666:latest' locally
docker: Error response from daemon: pull access denied for 666666666, repository does not exist or may require 'docker login': denied: requested access to the resource is denied.
See 'docker run --help'.
命令官方文档地址
[root@localhost docker]# docker version
#显示镜像个数,镜像启动个数等情况
[root@localhost docker]# docker info
#显示某个命令的帮助文档
[root@localhost docker]# docker 命令 --help
[root@localhost docker]# docker images --help
Usage: docker images [OPTIONS] [REPOSITORY[:TAG]]
List images
Options:
-a, --all Show all images (default hides intermediate images)
--digests Show digests
-f, --filter filter Filter output based on conditions provided
--format string Pretty-print images using a Go template
--no-trunc Don't truncate output
-q, --quiet Only show image IDs
[root@localhost docker]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
hello-world latest feb5d9fea6a5 27 hours ago 13.3kB
#解释:
REPOSITORY 镜像的仓库源
TAG 镜像的标签
IMAGE ID 镜像的id
CREATED 镜像的创建时间
SIZE 镜像的大小
# 可选参数
-a/--all 列出所有镜像
-q/--quiet 只显示镜像的id
#显示所有的镜像
[root@localhost docker]# docker images -a
REPOSITORY TAG IMAGE ID CREATED SIZE
hello-world latest feb5d9fea6a5 27 hours ago 13.3kB
#显示所有镜像的ID
[root@localhost docker]# docker images -q
feb5d9fea6a5
#显示所有镜像的ID
[root@localhost docker]# docker images -aq
feb5d9fea6a5
[root@localhost docker]# docker search mysql
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
mysql MySQL is a widely used, open-source relation… 11461 [OK]
mariadb MariaDB Server is a high performing open sou… 4351 [OK]
mysql/mysql-server Optimized MySQL Server Docker images. Create… 848 [OK]
#可选参数 -f, --filter 过滤条件
#过滤条件为STARS大于3000的
[root@localhost docker]# docker search mysql -f=STARS=3000
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
mysql MySQL is a widely used, open-source relation… 11461 [OK]
mariadb MariaDB Server is a high performing open sou… 4351 [OK]
#过滤条件为STARS大于5000的
[root@localhost docker]# docker search mysql -f=STARS=5000
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
mysql MySQL is a widely used, open-source relation… 11461 [OK]
[root@localhost docker]# docker pull mysql
Using default tag: latest #如果不写tag默认就是latest
latest: Pulling from library/mysql
a330b6cecb98: Pull complete #分层下载,docker image的核心-联合文件系统
9c8f656c32b8: Pull complete
88e473c3f553: Pull complete
062463ea5d2f: Pull complete
daf7e3bdf4b6: Pull complete
1839c0b7aac9: Pull complete
cf0a0cfee6d0: Pull complete
1b42041bb11e: Pull complete
10459d86c7e6: Pull complete
b7199599d5f9: Pull complete
1d6f51e17d45: Pull complete
50e0789bacad: Pull complete
Digest: sha256:99e0989e7e3797cfbdb8d51a19d32c8d286dd8862794d01a547651a896bcf00c
Status: Downloaded newer image for mysql:latest
docker.io/library/mysql:latest #下载来源的真实地址
#docker pull mysq l等价于 docker pull docker.io/library/mysql:latest
[root@iZwz99sm8v95sckz8bd2c4Z ~]# docker pull mysql:5.7
5.7: Pulling from library/mysql
6ec7b7d162b2: Already exists
fedd960d3481: Already exists
7ab947313861: Already exists
64f92f19e638: Already exists
3e80b17bff96: Already exists
014e976799f9: Already exists
59ae84fee1b3: Already exists
7d1da2a18e2e: Pull complete
301a28b700b9: Pull complete
529dc8dbeaf3: Pull complete
bc9d021dc13f: Pull complete
Digest: sha256:c3a567d3e3ad8b05dfce401ed08f0f6bf3f3b64cc17694979d5f2e5d78e10173
Status: Downloaded newer image for mysql:5.7
docker.io/library/mysql:5.7
#删除指定的镜像id
[root@iZwz99sm8v95sckz8bd2c4Z ~]# docker rmi -f 镜像id
#删除多个镜像id
[root@iZwz99sm8v95sckz8bd2c4Z ~]# docker rmi -f 镜像id 镜像id 镜像id
#通过镜像的名称删除镜像
[root@localhost docker]# docker rmi mysql
#删除全部的镜像id $(...) 代表参数信息 docker images -aq 获取所以镜像id
[root@iZwz99sm8v95sckz8bd2c4Z ~]# docker rmi -f $(docker images -aq)
说明:我们有了镜像才可以创建容器, linux,下载一个centos镜像来测试学习
#下载一个centOS镜像
[root@localhost ~]# docker pull centos
新建并运行容器
docker run [可选参数] image
#参数说明
--name="名字" 指定容器名字 tomcat01 tomcat01 区分容器名称
-d 后台方式运行
-it 使用交互方式运行,进入容器查看内容
-p 指定容器的端口 宿主机的端口映射到容器端口
-p ip:主机端口:容器端口 配置主机端口映射到容器端口
-p 主机端口:容器端口 (常用)
-p 容器端口
容器端口号
-P 随机指定端口(大写的P) 随机产生端口映射
#测试,启动并进入容器
[root@localhost ~]# docker run -it centos /bin/bash
#主机名称变了 证明进入容器成功
[root@f8ea34ea99d6 /]#
#查看容器内的centos, 基础版本,很多命令都是不完善的!
[root@f8ea34ea99d6 /]# ls
bin etc lib lost+found mnt proc run srv tmp var
dev home lib64 media opt root sbin sys usr
#宿主机的ls 比容器中的东西多
[root@localhost /]# ls
bin boot dev etc home lib lib64 media mnt opt proc root run sbin srv sys tmp usr var
退出容器
[root@f8ea34ea99d6 /]# exit
exit
不停止容器退出
列出运行过的容器
#列出正在运行的容器
[root@localhost /]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
#列出运行过的容器
[root@localhost /]# docker ps -a
参数说明:
列出当前正在运行的容器
-a 列出所有容器的运行记录 包括运行的和未运行的
-n=? 显示最近创建的n个容器
-q 只显示容器的编号
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
f8ea34ea99d6 centos "/bin/bash" 6 minutes ago Exited (127) 2 minutes ago elegant_mahavira
4662c9a87254 feb5d9fea6a5 "/hello" 2 hours ago Exited (0) 2 hours ago friendly_kilby
#显示最近创建过容器
[root@localhost /]# docker ps -n=1
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
f8ea34ea99d6 centos "/bin/bash" 11 minutes ago Exited (127) 8 minutes ago elegant_mahavira
删除容器
docker rm 容器id #删除指定的容器,不能删除正在运行的容器,强制删除使用 rm -f
docker rm -f $(docker ps -aq) #删除所有的容器
docker ps -a -q|xargs docker rm #删除所有的容器
#删除正在运行的容器报错
[root@localhost /]# docker rm 8eff292318fa
Error response from daemon: You cannot remove a running container 8eff292318fa9abc1626e46e90f64af022c809498fdaa7015d46a6ac1d3a4ad1. Stop the container before attempting removal or force remove
#强制删除
[root@localhost /]# docker rm -f 8eff292318fa
8eff292318fa
启动和停止容器(启动以前启动过的容器)
docker start 容器id #启动容器
docker restart 容器id #重启容器
docker stop 容器id #停止当前运行的容器
docker kill 容器id #强制停止当前容器
#启动容器
[root@localhost ~]# docker run -it centos /bin/bash
#退出容器
[root@237857fa7604 /]# exit
exit
#查看所有启动过的容器
[root@localhost ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
237857fa7604 centos "/bin/bash" 15 seconds ago Exited (0) 7 seconds ago great_hellman
#通过启动过的容器id,启动未启动的容器
[root@localhost ~]# docker start 237857fa7604
237857fa7604
#查看启动的容器
[root@localhost ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
237857fa7604 centos "/bin/bash" 56 seconds ago Up 14 seconds great_hellman
#停止启动了的ring器
[root@localhost ~]# docker stop 237857fa7604
237857fa7604
#查看启动的容器
[root@localhost ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
# 命令docker run -d 镜像名! -d:通过后台启动容器
[root@localhost ~]# docker run -d centos
02c0339f711b8ad483d644a6de9add5a35cd52b1d535145e4e02c5e89011a373
#问题docker ps,发现centos停止了
[root@localhost ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
#产生问题的原因:常见的坑,docker容器使用后台运行,就必须要有要一个前台进程,docker发现没有前台应用,就会自动停止(不是没有提供服务,而是启动后没有其他的指令,就自己结束了)
#nginx:nginx 容器启动后,发现自己没有提供服务,就会立刻停止,就是没有程序了
[root@localhost ~]# docker logs --help
#参数解析
Options:
--details #显示提供给日志的其他详细信息
-f, --follow #跟踪日志输出
--since string #显示自时间戳以来的日志
-n, --tail string #显示n条日志,不指定显示所有
-t, --timestamps #显示时间戳
--until string #在时间戳(例如2013-01-02T13:23:37Z)或相对时间戳之前显示日志(例如,42米跑42分钟)
常用:
docker logs -tf 容器id
docker logs -tf --tail number 容器id #number为要显示的日志条数,不指定默认显示所有
#docker容器后台运行,必须要有一个前台的进程,否则会自动停止
#编写shell脚本循环执行,使得centos容器保持运行状态
[root@localhost ~]# docker run -d centos /bin/bash -c "while true;do echo yyds;sleep 5;done"
e35123013dec93452c6b8886ada225584f17a668f4f3683ad18b26623a49d16c
#查看当前运行的容器 如果不加shell脚本,会自动停止
[root@localhost ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
e35123013dec centos "/bin/bash -c 'while…" 8 seconds ago Up 7 seconds objective_rosalind
#查看日志 会自动追踪日志进行输出
[root@localhost ~]# docker log
login logout logs
[root@localhost ~]# docker logs -tf --tail 10 e35123013dec
2021-09-25T06:17:15.055348714Z yyds
2021-09-25T06:17:20.082568234Z yyds
2021-09-25T06:17:25.086254765Z yyds
2021-09-25T06:17:30.090379614Z yyds
2021-09-25T06:17:35.095466135Z yyds
2021-09-25T06:17:40.099160475Z yyds
2021-09-25T06:17:45.103262540Z yyds
#命令:docker top 容器id
[root@localhost ~]# docker top e35123013dec
UID(当期用户ID) PID(进程ID) PPID(父ID) C STIME TTY TIME CMD
root 20073 20052 0 14:17 ? 00:00:00 /bin/bash -c while true;do echo yyds;sleep 5;done
root 20383 20073 0 14:20 ? 00:00:00 /usr/bin/coreutils --coreutils-prog-shebang=sleep /usr/bin/sleep 5
#可以通过进程ID杀死进程
# docker inspect 容器id
#包括 执行的脚本信息、容器的Id生成(截取了显示Id的前一段)、状态、从哪个镜像过来的、一些配置、挂载点(数据存储到宿主机上)、环境变量、网络配置等。
[root@localhost ~]# docker inspect e35123013dec
[
{
"Id": "e35123013dec93452c6b8886ada225584f17a668f4f3683ad18b26623a49d16c", #容器的Id生成(截取了Id的前一段)
"Created": "2021-09-25T06:17:14.320046194Z",
"Path": "/bin/bash",
"Args": [
"-c", #执行的脚本
"while true;do echo yyds;sleep 5;done"
],
"State": {
#状态
"Status": "running",
"Running": true,
"Paused": false,
"Restarting": false,
"OOMKilled": false,
"Dead": false,
"Pid": 20073,
"ExitCode": 0,
"Error": "",
"StartedAt": "2021-09-25T06:17:15.056344032Z",
"FinishedAt": "0001-01-01T00:00:00Z"
},
"Image": "sha256:5d0da3dc976460b72c77d94c8a1ad043720b0416bfc16c52c45d4847e53fadb6",# 来自于哪个镜像
"ResolvConfPath": "/var/lib/docker/containers/e35123013dec93452c6b8886ada225584f17a668f4f3683ad18b26623a49d16c/resolv.conf",
"HostnamePath": "/var/lib/docker/containers/e35123013dec93452c6b8886ada225584f17a668f4f3683ad18b26623a49d16c/hostname",
"HostsPath": "/var/lib/docker/containers/e35123013dec93452c6b8886ada225584f17a668f4f3683ad18b26623a49d16c/hosts",
"LogPath": "/var/lib/docker/containers/e35123013dec93452c6b8886ada225584f17a668f4f3683ad18b26623a49d16c/e35123013dec93452c6b8886ada225584f17a668f4f3683ad18b26623a49d16c-json.log",
"Name": "/objective_rosalind",
"RestartCount": 0,
"Driver": "overlay2",
"Platform": "linux",
"MountLabel": "",
"ProcessLabel": "",
"AppArmorProfile": "",
"ExecIDs": null,
"HostConfig": {
"Binds": null,
"ContainerIDFile": "",
"LogConfig": {
"Type": "json-file",
"Config": {
}
},
"NetworkMode": "default",
"PortBindings": {
},
"RestartPolicy": {
"Name": "no",
"MaximumRetryCount": 0
},
"AutoRemove": false,
"VolumeDriver": "",
"VolumesFrom": null,
"CapAdd": null,
"CapDrop": null,
"CgroupnsMode": "host",
"Dns": [],
"DnsOptions": [],
"DnsSearch": [],
"ExtraHosts": null,
"GroupAdd": null,
"IpcMode": "private",
"Cgroup": "",
"Links": null,
"OomScoreAdj": 0,
"PidMode": "",
"Privileged": false,
"PublishAllPorts": false,
"ReadonlyRootfs": false,
"SecurityOpt": null,
"UTSMode": "",
"UsernsMode": "",
"ShmSize": 67108864,
"Runtime": "runc",
"ConsoleSize": [
0,
0
],
"Isolation": "",
"CpuShares": 0,
"Memory": 0,
"NanoCpus": 0,
"CgroupParent": "",
"BlkioWeight": 0,
"BlkioWeightDevice": [],
"BlkioDeviceReadBps": null,
"BlkioDeviceWriteBps": null,
"BlkioDeviceReadIOps": null,
"BlkioDeviceWriteIOps": null,
"CpuPeriod": 0,
"CpuQuota": 0,
"CpuRealtimePeriod": 0,
"CpuRealtimeRuntime": 0,
"CpusetCpus": "",
"CpusetMems": "",
"Devices": [],
"DeviceCgroupRules": null,
"DeviceRequests": null,
"KernelMemory": 0,
"KernelMemoryTCP": 0,
"MemoryReservation": 0,
"MemorySwap": 0,
"MemorySwappiness": null,
"OomKillDisable": false,
"PidsLimit": null,
"Ulimits": null,
"CpuCount": 0,
"CpuPercent": 0,
"IOMaximumIOps": 0,
"IOMaximumBandwidth": 0,
"MaskedPaths": [
"/proc/asound",
"/proc/acpi",
"/proc/kcore",
"/proc/keys",
"/proc/latency_stats",
"/proc/timer_list",
"/proc/timer_stats",
"/proc/sched_debug",
"/proc/scsi",
"/sys/firmware"
],
"ReadonlyPaths": [
"/proc/bus",
"/proc/fs",
"/proc/irq",
"/proc/sys",
"/proc/sysrq-trigger"
]
},
"GraphDriver": {
"Data": {
"LowerDir": "/var/lib/docker/overlay2/f988af69671f553e198b64f9b8a3e1f9e9094c885622b48a5c5e396f48c86123-init/diff:/var/lib/docker/overlay2/28328ab684924e5f92ae20e053f9bfd2aba2327ec445c419ce928e6d5eccae02/diff",
"MergedDir": "/var/lib/docker/overlay2/f988af69671f553e198b64f9b8a3e1f9e9094c885622b48a5c5e396f48c86123/merged",
"UpperDir": "/var/lib/docker/overlay2/f988af69671f553e198b64f9b8a3e1f9e9094c885622b48a5c5e396f48c86123/diff",
"WorkDir": "/var/lib/docker/overlay2/f988af69671f553e198b64f9b8a3e1f9e9094c885622b48a5c5e396f48c86123/work"
},
"Name": "overlay2"
},
"Mounts": [], #挂载点
"Config": {
"Hostname": "e35123013dec",
"Domainname": "",
"User": "",
"AttachStdin": false,
"AttachStdout": false,
"AttachStderr": false,
"Tty": false,
"OpenStdin": false,
"StdinOnce": false,
"Env": [ #环境变量
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
],
"Cmd": [
"/bin/bash",
"-c",
"while true;do echo yyds;sleep 5;done"
],
"Image": "centos",
"Volumes": null,
"WorkingDir": "",
"Entrypoint": null,
"OnBuild": null,
"Labels": {
"org.label-schema.build-date": "20210915",
"org.label-schema.license": "GPLv2",
"org.label-schema.name": "CentOS Base Image",
"org.label-schema.schema-version": "1.0",
"org.label-schema.vendor": "CentOS"
}
},
"NetworkSettings": {
#网络
"Bridge": "",
"SandboxID": "8145dbde5e6fcb66c2cc228e7afe51076ad22f43d497594d1f4a37c5e2eb9090",
"HairpinMode": false,
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"Ports": {
},
"SandboxKey": "/var/run/docker/netns/8145dbde5e6f",
"SecondaryIPAddresses": null,
"SecondaryIPv6Addresses": null,
"EndpointID": "a08f621c7dc249b29984bbfc7a330aa8ab734e9a0e0664c30a562fcc334c5833",
"Gateway": "172.17.0.1",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"IPAddress": "172.17.0.2",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"MacAddress": "02:42:ac:11:00:02",
"Networks": {
"bridge": {
"IPAMConfig": null,
"Links": null,
"Aliases": null,
"NetworkID": "a2e4e02e76cee14c798b2b84b348e5212ceb491efefc91d6d8f58bc66a401eea",
"EndpointID": "a08f621c7dc249b29984bbfc7a330aa8ab734e9a0e0664c30a562fcc334c5833",
"Gateway": "172.17.0.1",
"IPAddress": "172.17.0.2",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"MacAddress": "02:42:ac:11:00:02",
"DriverOpts": null
}
}
}
}
]
#方式一: 命令: docker exec -it 容器id /bin/bash
#查看当前正在运行的容器
[root@localhost ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
e35123013dec centos "/bin/bash -c 'while…" 15 minutes ago Up 15 minutes objective_rosalind
#进入正在运行的容器 通过 bash窗口
[root@localhost ~]# docker exec -it e35123013dec /bin/bash
[root@e35123013dec /]# ls
bin etc lib lost+found mnt proc run srv tmp var
dev home lib64 media opt root sbin sys usr
#查看当前容器的进程
[root@e35123013dec /]# ps -ef
UID PID PPID C STIME TTY TIME CMD
root 1 0 0 06:17 ? 00:00:00 /bin/bash -c while true;do echo yyds;sleep 5;done
root 205 0 0 06:33 pts/0 00:00:00 /bin/bash
root 241 1 0 06:35 ? 00:00:00 /usr/bin/coreutils --coreutils-prog-shebang=sleep /us
root 242 205 0 06:35 pts/0 00:00:00 ps -ef
# 方式二: 命令:docker attach 容器id
#如果有正在运行且不停止的服务 使用exit 不会触发停止容器的操作 只会退出容器到宿主机
[root@e35123013dec /]# exit
exit
#查看正在运行的容器
[root@localhost ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
e35123013dec centos "/bin/bash -c 'while…" 19 minutes ago Up 19 minutes objective_rosalind
#进入容器正在执行的终端
[root@localhost ~]# docker attach e35123013dec
yyds
yyds
#命令:docker cp 容器id:容器内路径 目的主机路径
#启动容器
[root@localhost ~]# docker run -it centos /bin/bash
#查看容器中的文件
[root@f6918c83c3f0 /]# ls
bin etc lib lost+found mnt proc run srv tmp var
dev home lib64 media opt root sbin sys usr
#进入home目录
[root@f6918c83c3f0 /]# cd /home/
[root@f6918c83c3f0 home]# ls
#创建文件夹
[root@f6918c83c3f0 home]# touch test.java
#退出容器 容器停止运行 但是数据不会丢失 容器没有被删除 只是停止而已
[root@f6918c83c3f0 home]# exit
exit
#查看之前运行过的容器
[root@localhost ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
f6918c83c3f0 centos "/bin/bash" About a minute ago Exited (0) 6 seconds ago vigilant_hawking
#拷贝容器的文件到宿主机上
[root@localhost ~]# docker cp f6918c83c3f0:/home/test.java /home
[root@localhost ~]# cd /home/
[root@localhost home]# ls
pj test.java 安装包
attach Attach to a running container #当前she11下attach连接指定运行镜像
build Build an image from a Dockerfile #通过Dockerfile定制镜像
commit Create a new image from a container changes #提交当前容器为新的镜像
cp Copy files/folders from the containers filesystem to the host path #从容器中拷贝指定文件或者目录到宿主机中
create Create a new container #创建一个新的容器,同run,但不启动容器
diff Inspect changes on a container's fi lesys tem #查看docker容器变化
events Get real time events from the server #从docker 服务获取容器实时事件
exec Run a command in an existing container #在已存在的容器上运行命令
export Stream the contents of a container as a tar. archive #导出容器的内容流作为一个tar 归档文件[对应import ]
history show the history of an image #展示一个镜像形成历史
images List images #列出系统当前镜像
import Create a new filesystem image from the contents of a tarba1l #从tar包中的内容创建一个 新的文件系统映像[对应export]
info Display system-wide information #显示系统相关信息
inspect Return 1ow- 1eve1 information on a container #查看容器详细信息
kil1 Ki11 a running container # ki11指定docker容器
load Load an image from a tar archive #从一个tar包中加载一个镜像[对应save]
login Register or Login to the docker registry server #注册或者登陆一个docker 源服务器
logout Log out from a Docker registry server #从当前Docker registry退出
logs Fetch the logs of a container #输出当前容器日志信息
port Lookup the public-facing port which is NAT-ed to PRIVATE_ PORT #查看映射端口对应的容器内部源端口
pause Pause a11 processes within a conta iner #暂停容器
ps List containers #列出容器列表
pu11 Pu11 an image or a repository from the docker registry server #从docker镜像源服务器拉取指定镜像或者库镜像
push Push an image or a repository to the docker registry server #推送指定镜像或者库镜像至docker源服务器
restart Restart a running contai ner #重启运行的容器
rm Remove one or more containers #移除一个或者多个容器
rmi Renove one or more images #移除一个或多个镜像[无容器使用该镜像才可删除,否则需删除相关容器才可继续或-f强制删除]
run Run a command in a new container #创建一个新的容器并运行一个命令
save Save an image to a tar archive #保存一个镜像为一个tar包[对应load]
search Search for an image on the Docker Hub #在docker hub中搜索镜像
start Start a stopped containers #启动容器
stop Stop a running containers #停止容器
tag Tag an image into a repository #给源中镜像打标签
top Lookup the running processes of a container #查看容器中运行的进程信息
unpause Unpause a paused container #取消暂停容器
version Show the docker version informati on #查看docker版本号
wait Block until a container stops,then print its exit code #截取容器停止时的退出状态值
Docker安装Nginx
#1、搜索镜像 search 建议大家去docker搜索,可以看到帮助文档
[root@localhost home]# docker search nginx
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
nginx Official build of Nginx. 15529 [OK]
#2、下载镜像 pull
[root@localhost home]# docker pull nginx
Using default tag: latest
latest: Pulling from library/nginx
a330b6cecb98: Already exists
e0ad2c0621bc: Pull complete
9e56c3e0e6b7: Pull complete
09f31c94adc6: Pull complete
32b26e9cdb83: Pull complete
20ab512bbb07: Pull complete
Digest: sha256:853b221d3341add7aaadf5f81dd088ea943ab9c918766e295321294b035f3f3e
Status: Downloaded newer image for nginx:latest
docker.io/library/nginx:latest
#查看所有镜像
[root@localhost home]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
centos latest 5d0da3dc9764 9 days ago 231MB
nginx latest ad4c705f24d3 2 weeks ago 133MB
#3、运行测试
#-d后台运行
#--name 指定容器的名称
# -p 容器暴露的端口号映射到宿主机上的端口号 宿主机端口号:容器内部端口号
[root@localhost home]# docker run -d --name nginx01 -p:3344:80 nginx
9f7bd3098ee7877e474bfa946158c1fb596a620cfca1777522a592a6e485cac6
#查看运行的容器
[root@localhost home]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
9f7bd3098ee7 nginx "/docker-entrypoint.…" About a minute ago Up About a minute 0.0.0.0:3344->80/tcp, :::3344->80/tcp nginx01
#4、使用宿主机访问Nginx
[root@localhost home]# curl localhost:3344
#访问的html 代码 证明访问成功
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
......
# 进入Nginx容器
[root@localhost home]# docker exec -it nginx01 /bin/bash
#查看Nginx的文件存储的位置
root@9f7bd3098ee7:/# whereis nginx
nginx: /usr/sbin/nginx /usr/lib/nginx /etc/nginx /usr/share/nginx
#进入Nginx配置文件的目录
root@9f7bd3098ee7:/# cd /etc/nginx/
root@9f7bd3098ee7:/etc/nginx# ls
conf.d fastcgi_params mime.types modules nginx.conf scgi_params uwsgi_params
# 退出容器
root@9f7bd3098ee7:/etc/nginx# exit
exit
#查看正在执行的容器
[root@localhost home]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
9f7bd3098ee7 nginx "/docker-entrypoint.…" 2 hours ago Up 2 hours 0.0.0.0:3344->80/tcp, :::3344->80/tcp nginx01
#停止容器 再次通过访问外网访问Nginx不会显示页面
[root@localhost home]# docker stop 9f7bd3098ee7
9f7bd3098ee7
Docker安装tomcat
#我们之前的启动都是后台,停止了容器之后,容器还是可以查到
#docker run -it --rm,一般用来测试,用完就删除
$ docker run -it --rm tomcat:9.0
# 下载
docker pull tomcat
# 启动运行
docker run -d -p 3355:8080 --name tomcat01 tomcat
# 测试访问没有问题 由于webapps下没有东西 导致访问会报404错误 但是证明tomcat启动起来了
# 进入容器
[root@localhost home]# docker exec -it tomcat01 /bin/bash
#查看容器的文件
root@697daf09db74:/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
#进入webapps中
root@697daf09db74:/usr/local/tomcat# cd webapps
#查看文件 没有任何文件
root@697daf09db74:/usr/local/tomcat/webapps# ls
#返回上层,目录
root@697daf09db74:/usr/local/tomcat/webapps# cd ..
#进入webapps.dist中
root@697daf09db74:/usr/local/tomcat# cd webapps.dist/
#查看文件 有root等文件 存储了访问页
root@697daf09db74:/usr/local/tomcat/webapps.dist# ls
ROOT docs examples host-manager manager
#返回上层目录
root@697daf09db74:/usr/local/tomcat/webapps.dist# cd ..
#将webapps.dist下的所有文件拷贝到webapps下 再次访问
root@697daf09db74:/usr/local/tomcat# cp -r webapps.dist/* webapps/
# 发现问题:1、linux命令少了,2、没有webapps,阿里云镜像的原因。默认是最小的镜像,所有不必要的都剔除掉了。# 保证最小可运行的环境
安装es+ kibana(kibana是es的一个可视化控制台)
#es暴露的端口很多!
# es十分耗内存
# es的数据一般放置到安全目录!挂载
# --net somenetwork 网络配置
#下载并运行镜像
[root@localhost ~]#docker run -d --name elasticsearch -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" elasticsearch:7.6.2
#通过宿主机进行访问 能够访问成功 但是很卡
[root@localhost ~]# curl localhost:9200
{
"name" : "317bb9c437d5",
"cluster_name" : "docker-cluster",
"cluster_uuid" : "sqSb4TAxRVeiCw8bytyC8w",
"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"
}
#启动了linux就卡住了 docker stats查看cpu的状态 查看到es占用内存过多 导致Linux卡 赶紧关闭 增加内存的限制
[root@localhost ~]# docker stats
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
d0dcaee4e6ed elasticaeach 0.01% 1.08GiB / 1.934GiB 55.85% 656B / 0B 116MB / 0B 15
#增加内存的限制 ,修改配置文件 -e 环境配置修改 -e ES_JAVA_OPTS="-Xms64M -Xms512M" 指定占用内存的最大空间
[root@localhost ~]#docker run -d --name elasticsearch02 -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" -e ES_JAVA_OPTS="-Xms64M -Xms512M" elasticsearch:7.6.2
#查看限制了内存大小的es 可明显看到战表减少
[root@localhost ~]# docker stats 317bb9c437d5
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
317bb9c437d5 elasticsearch02 0.13% 696.2MiB / 1.934GiB 35.15% 656B / 0B 168MB / 0B 28
#一样能够就行访问
[root@localhost ~]# curl localhost:9200
{
"name" : "317bb9c437d5",
"cluster_name" : "docker-cluster",
"cluster_uuid" : "sqSb4TAxRVeiCw8bytyC8w",
"version" : {
"number" : "7.6.2",
"build_flavor" : "default",
"build_type" : "docker",
"build_hash" : "ef48eb35cf30adf4db14086e8aabd07ef6fb113f",
"build_date" : "2020-03-26T06:34:37.794943Z",
"build_snapshot" : false,
"lucene_version" : "8.4.0",
"minimum_wire_compatibility_version" : "6.8.0",
"minimum_index_compatibility_version" : "6.0.0-beta1"
},
"tagline" : "You Know, for Search"
}
docker run -d -p 8080:9000 \--restart=always -v /var/run/docker.sock:/var/run/docker.sock --privileged=true portainer/portainer
# 下载运行 portainer
#--restart-always 权限设置
# -v 卷技术 容器映射路径:宿主机映射路径
ocker run -d -p 8080:9000 \--restart=always -v /var/run/docker.sock:/var/run/docker.sock --privileged=true portainer/portainer
#查看镜像信息
[root@localhost ~]# docker inspect redis
[
{
........
},
"RootFS": {
"Type": "layers",
"Layers": [ #当前镜像分层文件系统的每一层
"sha256:d000633a56813933cb0ac5ee3246cf7a4c0205db6290018a169d7cb096581046",
"sha256:bdad86443e47c5665683ac41c1f24f28479d830d7e3cc47d0a337ee5166c7714",
"sha256:6a7992ac480029d82b7dbb757d16fe5d023aa283ed32b52267cd1fe9e6b73c49",
"sha256:be43d2475cf809c0f2ec31950e849d0f888f3121970fd99196a11a903f8c3820",
"sha256:be5818ef2907adfe19be14bf66647b5fb5a2029143f9297f8ce1ff1fd1d35753",
"sha256:c54e0c16ea22fa873c12f6a7f3fb4e021bb58d67c292156a6ce6e08637458b7c"
]
},
"Metadata": {
"LastTagTime": "0001-01-01T00:00:00Z"
}
}
]
# 命令和git原理类似
docker commit -m="描述信息" -a="作者" 容器id 目标镜像名:[TAG]
由于默认的Tomcat镜像的webapps文件夹中没有任何内容,需要从webapps.dist中拷贝文件到webapps文件夹。下面自己制作镜像:就是从webapps.dist中拷贝文件到webapps文件夹下,并提交该镜像作为一个新的镜像。使得该镜像默认的webapps文件夹下就有默认的tomcat文件。
# 1、启动Tomact 需要防止端口号冲突
[root@localhost ~]# docker run -it -p:8080:8080 tomcat
[root@localhost ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
848e8f4fd37f tomcat "catalina.sh run" About a minute ago Up About a minute 0.0.0.0:8080->8080/tcp, :::8080->8080/tcp jovial_galileo
# 2、进入容器中
[root@localhost ~]# docker exec -it 848e8f4fd37f /bin/bash
#查看当前文件
root@848e8f4fd37f:/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
#进入 webapps目录下
root@848e8f4fd37f:/usr/local/tomcat# cd webapps
#3、发现这个默认的tomcat 是没有webapps应用,官方的镜像默认webapps下面是没有文件的!
root@848e8f4fd37f:/usr/local/tomcat/webapps# ls
#进入 webapps.dist 目录下
root@848e8f4fd37f:/usr/local/tomcat/webapps# cd ../webapps.dist/
# 发现有默认的tomcat的配置
root@848e8f4fd37f:/usr/local/tomcat/webapps.dist# ls
ROOT docs examples host-manager manager
root@848e8f4fd37f:/usr/local/tomcat/webapps.dist# cd ..
#拷贝文件进去 拷贝 tomcat的配置 到webapps中
root@848e8f4fd37f:/usr/local/tomcat# cp -r webapps.dist/* webapps
#4、提交我们这个改变过的tomcat
[root@localhost ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
848e8f4fd37f tomcat "catalina.sh run" 11 minutes ago Up About a minute 0.0.0.0:8080->8080/tcp, :::8080->8080/tcp jovial_galileo
# 提交镜像
[root@localhost ~]# docker commit -a="pj" -m="增加了Tomact的默认配置" 848e8f4fd37f tomcat02:1.0
sha256:c8a6ea9187d36a44d2f09147feda1b3c74143e816bd076416ca921e7afe5bde0
#查看所有镜像 就可以查看到提交后的tomcat 比原本的稍大
#将操作过的容器通过commit**为一个镜像!我们以后就使用我们修改过的镜像即可,这就是我们自己的一个修改的镜像
[root@localhost ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
tomcat02 1.0 c8a6ea9187d3 4 seconds ago 684MB
tomcat 9.0 62146f8bda84 12 days ago 680MB
#查看home目录的结构
[root@localhost home]# ls
pj 安装包
#启动centOS镜像 映射 宿主机目录:到容器目录 -v /home/ceshi:/home
[root@localhost ~]# docker run -it -v /home/ceshi:/home centos /bin/bash
#Ctrl+q+p退出容器 再次查看home目录的结构 发现映射成功
[root@localhost home]# ls
ceshi pj 安装包
# 查看容器的详情
[root@localhost ceshi]# docker inspect ab60b4c10102
思考:MySQL的数据持久化的问题
下载MySQL镜像
[root@localhost ~]# docker pull mysql:5.7
5.7: Pulling from library/mysql
a330b6cecb98: Already exists
9c8f656c32b8: Pull complete
88e473c3f553: Pull complete
062463ea5d2f: Pull complete
daf7e3bdf4b6: Pull complete
1839c0b7aac9: Pull complete
cf0a0cfee6d0: Pull complete
fae7a809788c: Pull complete
dae5a82a61f0: Pull complete
7063da9569eb: Pull complete
51a9a9b4ef36: Pull complete
Digest: sha256:d9b934cdf6826629f8d02ea01f28b2c4ddb1ae27c32664b14867324b3e5e1291
Status: Downloaded newer image for mysql:5.7
docker.io/library/mysql:5.7
官方启动MySQL镜像的案例
#-e 配置参数 MYSQL_ROOT_PASSWORD 配置mysql的初始化密码
$ docker run --name some-mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:tag
自己启动MySQL(安装启动mysql,需要配置密码的,这是要注意点)
#运行容器,需要做数据挂载
#-d 后台运行
#-p 端口映射
#-v 卷挂载
#-e 环境配置 MYSQL_ROOT_PASSWORD 配置MySQL初始化密码
#-- name 容器名字
[root@localhost ~]# 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=123 --name mysql01 mysql:5.7
3645704371b8157d35cff3556e34dcf46bd199875b1dbe25aecf616f01f2d6b4
假设我们将容器删除。发现,我们挂载到本地的数据卷依旧没有丢失,这就实现了容器数据持久化功能!
#查看正在运行的容器
[root@localhost data]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
3645704371b8 mysql:5.7 "docker-entrypoint.s…" 9 minutes ago Up 9 minutes 33060/tcp, 0.0.0.0:3310->3306/tcp, :::3310->3306/tcp mysql01
#删除 mysql容器
[root@localhost data]# docker rm -f 3645704371b8
3645704371b8
#删除成功
[root@localhost data]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
再次启动镜像,映射到 /home/mysql/conf 和 /home/mysql/data 目录,就可实现数据持久化功能
# -d 后台运行
# -P 随机映射端口
#--name 给容器取名称
#-v /etc/nginx 匿名映射端口
[root@localhost data]# docker run -d -P --name nginx01 -v /etc/nginx nginx
133ceea8f5fa062c03d8a2a8aeb9831dbe31dad05b31d3ceb442bcc0837ec748
查看所有的volume的情况(可使用命令:docker volume --help 查看使用方式)
[root@localhost data]# docker volume ls
# VOLUME NAME就是挂载的卷名 使用的都是随机串 没有具体的名字 所以为匿名挂载
#每个卷名都映射了一个真实的路径
DRIVER VOLUME NAME
local 31e97fb797063258778239d55f1f1bb64d702d4b687c4ee057d69c483a9e7a22
local 6491eddb64a35d6827420e6d0eef23d91c1eed1ee543223cc8a0706efb1e5df6
这里发现,这种就是匿名挂载,我们在 -v 只写了容器内的路径,没有写容器外的路径!
# v juming:/etc/nginx 具名挂载
#加 /juming:/etc/nginx 这个属于指定目录挂载 宿主机/juming路径与容器路径/etc/nginx映射
#不加 / 就 juming:/etc/nginx 这个属于具名挂载 就是这个这个容器路径取了个具体名称
[root@localhost data]# docker run -d -P -v juming:/etc/nginx --name nginx02 nginx
6e98ad9f410f270bf9bfd799b10b95f6b67883431d62ea67a2059fad534a12a1
#查看卷名成 可看见自己定义的具名挂载路径
[root@localhost data]# docker volume ls
DRIVER VOLUME NAME
local 31e97fb797063258778239d55f1f1bb64d702d4b687c4ee057d69c483a9e7a22
local 6491eddb64a35d6827420e6d0eef23d91c1eed1ee543223cc8a0706efb1e5df6
local juming
#查看具名挂载的卷名映射的目录
[root@localhost data]# docker volume inspect juming
[
{
"CreatedAt": "2021-09-28T23:51:48+08:00",
"Driver": "local",
"Labels": null,
"Mountpoint": "/var/lib/docker/volumes/juming/_data", #映射到宿主的目录
"Name": "juming",
"Options": null,
"Scope": "local"
}
]
ro readonly # 只读
rw readwrite # 可读可写
docker run -d -P --name nginx03 -v juming:/etc/nginx:ro nginx
docker run -d -P --name nginx04 -v juming:/etc/nginx:rw nginx
# 进入home目录
[root@localhost ~]# cd /home/
#创建存放dockerfile文件的目录
[root@localhost home]# mkdir docker-test-volume
[root@localhost home]# ls
ceshi docker-test-volume mysql pj 安装包
[root@localhost home]# cd docker-test-volume/
#创建一个dockerfile文件,名字可以随机 建议 Dockerfile 指令必须全大写
[root@localhost docker-test-volume]# vim dockerfile1
#查看dockerfile文件内容(文件中的内容 指令(大写)参数)
#这里的每个命令,就是镜像的一层!
[root@localhost docker-test-volume]# cat dockerfile1
# 基镜像
FROM centos
# 挂载的卷位置 需要/ 以绝对位置开头
VOLUME ["/volume01",“/volume02”]
# 下载挂载完成后 输出
CMD echo "----end----"
# 打开控制台
CMD /bin/bash
#编译dockerfile文件
# -f dockerfile存放的文件目录
# -t 给当前dockerfile生成的进行取名称
[root@localhost docker-test-volume]# docker build -f dockerfile1 -t ph/centos:1.0 .
#是按照别写的dockerfile文件一步一步往下执行的
Sending build context to Docker daemon 2.048kB
Step 1/4 : FROM centos
---> 5d0da3dc9764
Step 2/4 : VOLUME ["volume01",“volume02”]
---> Running in 2c458fcdc8ae
Removing intermediate container 2c458fcdc8ae
---> 631358566fa1
Step 3/4 : CMD echo "----end----"
---> Running in 6a8f03bac65c
Removing intermediate container 6a8f03bac65c
---> de22d35e4d83
Step 4/4 : CMD /bin/bash
---> Running in bc7e3194d393
Removing intermediate container bc7e3194d393
---> 728356244f4f
Successfully built 728356244f4f
Successfully tagged ph/centos:1.0
[root@localhost docker-test-volume]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
ph/centos 1.0 728356244f4f 3 minutes ago 231MB
#启动dockerfile创建的镜像
[root@localhost docker-test-volume]# docker run -it 2b17f24d5ded /bin/bash
[root@localhost docker-test-volume]#docker inspect 6aa1775dfa5c
多个容器之间的同步数据!
通过我们刚才自己写的镜像启动,启动3个容器,实现三个容器之间的数据同步。
#启动第一个容器(通过创建的镜像名称来启动,必须携带版本号)
[root@localhost ~]# docker run -it --name centos01 pj/centos:latest
启动后,Ctrl+q+p 退出当前容器,启动第二个容器。通过 --volumes-from 容器名称 实现容器之间的数据共享(相当于java继承,一个父一子,centos01父,centos2子,子会拥有父的内容,父也会拥有子的内容)。
[root@localhost ~]#docker run -it --name centos02 --volumes-from centos01 pj/centos:latest
Ctrl+q+p 退出当前容器,进入centOS1中,在卷文件夹中创建文件,查看能否实现共享。
#进入当前容器的执行的命令窗口
[root@localhost ~]# docker attach centos01
#进入挂载卷 volumen01 目录
[root@48800552857b /]# cd volume01
#查看目录文件
[root@48800552857b volume01]# ls
#创建文件
[root@48800552857b volume01]# touch test.java
Ctrl+q+p 退出当前容器,进入centOS2中 ,查看看目录是否存在。
#进入当前容器的执行的命令窗口
[root@localhost ~]# docker attach centos02
#进入挂载卷 volumen01 目录
[root@b0700a8bdb77 /]# cd /volume01
#查看目录文件
[root@b0700a8bdb77 volume01]# ls
test.java
创建第三个容器。与centos01进行数据绑定。查看这个容器的数据状况。
[root@localhost ~]# docker run -it --name cenos03 --volumes-from centos01 pj/centos:latest
[root@bb6c760d96a4 /]# cd /volume01
[root@bb6c760d96a4 volume01]# ls
test.java
在centos03中创建一个文件
[root@bb6c760d96a4 /]# cd /volume01
[root@bb6c760d96a4 volume01]# ls
test.java
[root@bb6c760d96a4 volume01]# touch test03.java
Ctrl+q+p 退出当前容器,,进入centos01中查看数据情况。
[root@localhost ~]# docker attach centos01
[root@48800552857b volume01]# ls
test.java test03.java
都关联了 centos01 容器,如果删除了centos01 ,查看centos02、centos03的容器数据会不会丢失?答案不会。
# 查看当前运行的容器
[root@localhost ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
bb6c760d96a4 pj/centos:latest "/bin/sh -c /bin/bash" 5 minutes ago Up 5 minutes cenos03
b0700a8bdb77 pj/centos:latest "/bin/sh -c /bin/bash" 29 minutes ago Up 29 minutes centos02
48800552857b pj/centos:latest "/bin/sh -c /bin/bash" 30 minutes ago Up 30 minutes centos01
#停止centos01容器
[root@localhost ~]# docker stop 48800552857b
48800552857b
#删除centos01容器
[root@localhost ~]# docker rm -f 48800552857b
48800552857b
# 进入centos02容器 查看数据 依旧存在
[root@localhost ~]# docker attach centos02
[root@b0700a8bdb77 volume01]# ls
test.java test03.java
原理图。通过 docker inspect 容器id,查看两个容器的信息,可查看到,两个挂载的目录相同,实现了容器之间的数据的同步。
多个mysql实现数据共享
docker run -d -p 3306:3306 -v /home/mysql/conf:/etc/mysql/conf.d -v /home/mysql/data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=123456 --name mysql01 mysql:5.7
docker run -d -p 3307:3306 -e MYSQL_ROOT_PASSWORD=123456 --name mysql02 --volumes-from mysql01 mysql:5.7
结论:
FROM # 基础镜像,一切从这里开始构建。如:centos
MAINTAINER # 镜像是谁写的, 格式一般为:姓名+邮箱
RUN # 镜像构建的时候需要运行的命令
ADD # 添加内容 添加同目录
WORKDIR # 镜像的工作目录
VOLUME # 挂载的目录
EXPOSE # 保留端口配置
CMD # 指定这个容器启动的时候要运行的命令,只有最后一个会生效,可被替代。
ENTRYPOINT # 指定这个容器启动的时候要运行的命令,可以追加命令
ONBUILD # 当构建一个被继承 DockerFile 这个时候就会运行ONBUILD的指令,触发指令。
COPY # 类似ADD,将我们文件拷贝到镜像中
ENV # 构建的时候设置环境变量!(类似于定义变量)
Docker Hub中 99% 镜像都是从这个基础镜像过来的 FROM scratch , 然后配置需要的软件和配置来进行的构建。
启动官方centos镜像。发现有些命令没有,而且工作目录在 /目录 。所以我们可以在构建dockerfile时,添加这些命令,改变工作目录。
创建一个自己的centos
[root@localhost docker-test-volume]# vim dockerfile-centos
[root@localhost docker-test-volume]# cat dockerfile-centos
FROM centos #基于那个基础镜像
MAINTAINER pj<1464847406@qq.com> #设置创建人的信息
ENV MYPATH /use/local #定义一个环境变量
WORKDIR $MYPATH # 启动进入容器时,指定进入的目录
RUN yum -y install vim #下载vim命令
RUN yum -y install net-tools #下载网络命令
EXPOSE 80 #映射端口
CMD echo $MYPATH #构建完成时输出的信息
CMD echo "----end----"
CMD /bin/bash
#-f 指定目录 可以写绝对路径,也可以写相对路径
#-t 指定镜像的名称和版本
[root@localhost docker-test-volume]# docker build -f dockerfile-centos -t mycentos:1.0 .
[root@localhost docker-test-volume]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
mycentos 1.0 e161ddbc85bd 12 minutes ago 336MB
[root@localhost docker-test-volume]# docker run -it mycentos:1.0
#查看进入容器时,进入的工作目录。
[root@6808cd987360 local]# pwd
/use/local
#使用ifconfig命令查看网络ip
[root@6808cd987360 local]# ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 172.17.0.2 netmask 255.255.0.0 broadcast 172.17.255.255
ether 02:42:ac:11:00:02 txqueuelen 0 (Ethernet)
RX packets 7 bytes 586 (586.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
#使用vim命令
[root@6808cd987360 local]# vim test
我们平时拿到一个镜像,可以研究一下它的构建步骤。(通过命令:docker history 容器d)
[root@localhost docker-test-volume]# docker history e161ddbc85bd
IMAGE CREATED CREATED BY SIZE COMMENT
e161ddbc85bd 22 minutes ago /bin/sh -c #(nop) CMD ["/bin/sh" "-c" "/bin… 0B
133878824701 22 minutes ago /bin/sh -c #(nop) CMD ["/bin/sh" "-c" "echo… 0B
a9f18ff17cf5 22 minutes ago /bin/sh -c #(nop) CMD ["/bin/sh" "-c" "echo… 0B
da892c5507bf 22 minutes ago /bin/sh -c #(nop) EXPOSE 80 0B
8fd8be10dc75 22 minutes ago /bin/sh -c yum -y install net-tools 32.4MB
9ca584b2604f 22 minutes ago /bin/sh -c yum -y install vim 72.6MB
abba8c1df757 23 minutes ago /bin/sh -c #(nop) WORKDIR /use/local 0B
3b6c8d117836 24 minutes ago /bin/sh -c #(nop) ENV MYPATH=/use/local 0B
649cd09f75fd 24 minutes ago /bin/sh -c #(nop) MAINTAINER pj<1464847406@… 0B
5d0da3dc9764 2 weeks ago /bin/sh -c #(nop) CMD ["/bin/bash"] 0B
<missing> 2 weeks ago /bin/sh -c #(nop) LABEL org.label-schema.sc… 0B
<missing> 2 weeks ago /bin/sh -c #(nop) ADD file:805cb5e15fb6e0bb0… 231MB
CMD 和 ENTRYPOINT区别
#1、创建dockerfile文件
[root@localhost docker-test-volume]# vim dockerfile-test-cmd
#查看文件内容
[root@localhost docker-test-volume]# cat dockerfile-test-cmd
FROM centos
CMD ["ls","-a"]
#通过dockerfile构建镜像
[root@localhost docker-test-volume]# docker build -f dockerfile-test-cmd -t centos-cmd:1.0 .
Sending build context to Docker daemon 4.096kB
Step 1/2 : FROM centos
---> 5d0da3dc9764
Step 2/2 : CMD ["ls","-a"]
---> Running in 079c80bec940
Removing intermediate container 079c80bec940
---> 5a3ecce3a6ed
Successfully built 5a3ecce3a6ed
Successfully tagged centos-cmd:1.0
#运行dockerfile创建的镜像 会调用 CDM后面指定的命令
[root@localhost docker-test-volume]# docker run centos-cmd:1.0
.
..
.dockerenv
bin
dev
etc
home
# 想追加一个命令 -l 成为ls -al
[root@localhost docker-test-volume]# docker run centos-cmd:1.0 -l
docker: Error response from daemon: OCI runtime create failed: container_linux.go:380: starting container process caused: exec: "-l": executable file not found in $PATH: unknown.
ERRO[0000] error waiting for container: context canceled
#替换成 ls -al 就可成功
[root@localhost docker-test-volume]# docker run centos-cmd:1.0 ls -al
total 0
drwxr-xr-x. 1 root root 6 Sep 30 09:38 .
drwxr-xr-x. 1 root root 6 Sep 30 09:38 ..
-rwxr-xr-x. 1 root root 0 Sep 30 09:38 .dockerenv
lrwxrwxrwx. 1 root root 7 Nov 3 2020 bin -> usr/bin
drwxr-xr-x. 5 root root 340 Sep 30 09:38 dev
drwxr-xr-x. 1 root root 66 Sep 30 09:38 etc
drwxr-xr-x. 2 root root 6 Nov 3 2020 home
# 编写dockerfile文件
[root@localhost docker-test-volume]# vim dockerfile-test-entrypoint
#查看文件内容
[root@localhost docker-test-volume]# cat dockerfile-test-entrypoint
FROM centos
ENTRYPOINT ["ls","-a"]
#构建镜像
[root@localhost docker-test-volume]# docker build -f dockerfile-test-entrypoint -t centos-entrypoint:1.0 .
Sending build context to Docker daemon 5.12kB
Step 1/2 : FROM centos
---> 5d0da3dc9764
Step 2/2 : ENTRYPOINT ["ls","-a"]
---> Running in 51bee1c36204
Removing intermediate container 51bee1c36204
---> 4f76e105b1f2
Successfully built 4f76e105b1f2
Successfully tagged centos-entrypoint:1.0
#运行dockerfile创建的镜像 会调用 ENTRYPOINT 后面指定的命令
[root@localhost docker-test-volume]# docker run centos-entrypoint:1.0
.
..
.dockerenv
bin
dev
etc
home
# 我们的命令,是直接拼接在我们得ENTRYPOINT命令后面的
[root@localhost docker-test-volume]# docker run centos-entrypoint:1.0 -l
total 0
drwxr-xr-x. 1 root root 6 Sep 30 09:42 .
drwxr-xr-x. 1 root root 6 Sep 30 09:42 ..
-rwxr-xr-x. 1 root root 0 Sep 30 09:42 .dockerenv
lrwxrwxrwx. 1 root root 7 Nov 3 2020 bin -> usr/bin
drwxr-xr-x. 5 root root 340 Sep 30 09:42 dev
drwxr-xr-x. 1 root root 66 Sep 30 09:42 etc
drwxr-xr-x. 2 root root 6 Nov 3 2020 home
Dockerfile中很多命令都十分的相似,我们需要了解它们的区别,我们最好的学习就是对比他们然后测试效果!
2、编写dokerfile
[root@localhost tomcatImages]# vim dockerfile
#基镜像
FROM centos
#设置创建镜像的创建信息
MAINTAINER pj<1464847406@qq.com>
#拷贝当前目录下的READEME 到容器 /use/locat 目录下
COPY READEME /use/locat/README
#解压当前目录下的JDK 到容器 /use/locat 目录下
ADD jdk-8u301-linux-x64.tar.gz /usr/local/
#解压当前目录下的tomcat 到容器 /use/locat 目录下
ADD apache-tomcat-9.0.1.tar.gz /usr/local/
#安装 vim命令
RUN yum -y install vim
#设置环境变量
ENV MAPATH /usr/local
#设置工作目录
WORKDIR $MAPATH
#设置jdk环境变量
ENV JAVA_HOME /usr/local/jdk1.8.0_301
#设置tomcat环境变量
ENV CATALINA_HOME /usr/local/apache-tomcat-9.0.1
#设置两个环境变量 分隔符是:
ENV PATH $PATH:$JAVA_HOME/bin:$CATALINA_HOME/lib
#设置暴露的端口
EXPOSE 8080
# 设置默认命令 使用 &&符号拼接 /bin/startup.sh 进入容器启动tomcat tail -F 进入容器时显示日志
CMD /usr/local/apache-tomcat-9.0.1/bin/startup.sh && tail -F /usr/local/apache-tomcat-9.0.1/logs/catalina.out
3、构建镜像
[root@localhost tomcatImages]# docker build -t mytomcat:1.0 .
# -d 后台运行
# -p 端口映射
# --name 给容器起名称
# -v 挂载目录 Tomact的webapps目录映射到宿主机/home/tomcatImages/tomcat/test 目录
# -v 挂载目录 Tomact的logs 日志目录 映射到宿主机 /home/tomcatImages/tomcat/tomcatlogs/目录下
[root@localhost tomcatImages]# docker run -d -p 8080:8080 --name tomcat01 -v /home/tomcatImages/tomcat/test:/usr/local/apache-tomcat-9.0.1/webapps/test -v /home/tomcatImages/tomcat/tomcatlogs/:/usr/local/apache-tomcat-9.0.1/logs mytomcat:1.0
a34f1309026a8d27d8539af1422eb911f3b46de9ddda22265eb923543583fe19
[root@localhost tomcatImages]# docker exec -it a34f1309026a /bin/bash
[root@a34f1309026a local]# ls
apache-tomcat-9.0.1 bin etc games include jdk1.8.0_301 lib lib64 libexec sbin share src
[root@localhost tomcatImages]# cd tomcat/
[root@localhost tomcat]# cd test/
[root@localhost test]# mkdir WEB-INF
[root@localhost test]# cd WEB-INF/
[root@localhost WEB-INF]# vim web.xml
web.xml内容:
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
web-app>
[root@localhost WEB-INF]# cd ..
[root@localhost test]# vim index.jsp
index.jsp内容<%@ page contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
hello boy
欢迎光临~~
<%
System.out.println("----my test web 1ogs----");
%>
我们以后开发的步骤:需要掌握Dockerfile的编写!我们之后的一切都是使用docker镜像来发布运行!
dockerHub 地址: https://hub.docker.com/,登陆我们账号。
确定这个账号可以登录
在宿主机上登录我们的账号。(命令:docker login -u)
[root@localhost tomcatlogs]# docker login -u mypjdockerhub
Password:
WARNING! Your password will be stored unencrypted in /root/.docker/config.json.
Configure a credential helper to remove this warning. See
https://docs.docker.com/engine/reference/commandline/login/#credentials-store
Login Succeeded
登陆之后,就可以提交 push镜像。(命令:docker push 容器名,前提自己的仓库不能有这个同名的镜像)
[root@localhost tomcatlogs]# docker push mytomcat:1.0
The push refers to repository [docker.io/library/mytomcat]
177a8e243eb3: Preparing
543dbb3ab1c1: Preparing
c32594c622a9: Preparing
ddb8c68a9885: Preparing
74ddd0ec08fa: Preparing
denied: requested access to the resource is denied #请求被拒绝
会发现push不上去,因为如果没有前缀的话默认是push到 官方的library
解决方法
第一种 build的时候添加你的dockerhub用户名,然后在push就可以放到自己的仓库了
$ docker build -t mypjdockerhub/mytomcat:0.1 .
第二种 使用docker tag 然后再次push(命令:docker tag 容器id mypjdockerhub/mytomcat:1.0 )相当于取别名。
[root@localhost tomcatlogs]# docker tag bebc67471cfc mypjdockerhub/mytamcat:1.0
[root@localhost tomcatlogs]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
mytomcat 1.0 bebc67471cfc 14 hours ago 678MB
mypjdockerhub/mytamcat 1.0 bebc67471cfc 14 hours ago 678MB
再次push,push成功(提交的时候也是按照镜像的层级来进行提交的!)
[root@localhost tomcatlogs]# docker push mypjdockerhub/mytamcat:1.0
The push refers to repository [docker.io/mypjdockerhub/mytamcat]
177a8e243eb3: Pushing [=> ] 2.217MB/72.64MB
543dbb3ab1c1: Pushing [============================> ] 7.632MB/13.3MB
c32594c622a9: Pushing [> ] 4.422MB/361.2MB
ddb8c68a9885: Pushed
74ddd0ec08fa: Pushing [> ] 3.835MB/231.3MB
$ sudo docker login --username=zchengx registry.cn-shenzhen.aliyuncs.com
$ sudo docker tag [ImageId] registry.cn-shenzhen.aliyuncs.com/dsadxzc/cheng:[镜像版本号]
# 修改id 和 版本
sudo docker tag a5ef1f32aaae registry.cn-shenzhen.aliyuncs.com/dsadxzc/cheng:1.0
# 修改版本
$ sudo docker push registry.cn-shenzhen.aliyuncs.com/dsadxzc/cheng:[镜像版本号]
清除所有容器,和所有镜像
#删除所有容器
[root@localhost ~]# docker rm -f $(docker ps -aq)
#删除所有镜像
[root@localhost ~]# docker rmi -f $(docker images -aq)
下载启动一个tomcat容器。
[root@localhost ~]# docker run -d -P --name tomcat01 tomcat
查看tomcat容器内部网络地址 发现容器启动的时候会得到一个 ip地址,docker分配的!
[root@localhost ~]# docker exec -it tomcat01 /bin/bash
root@b2f4f64055c1:/usr/local/tomcat# 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.2 b2f4f64055c1
使用这个我会报错,请求指导
[root@localhost ~]# docker exec -it tomcat01 ip addr
OCI runtime exec failed: exec failed: container_linux.go:380: starting container process caused: exec: "ip": executable file not found in $PATH: unknown
[root@localhost ~]# ping 172.17.0.2
PING 172.17.0.2 (172.17.0.2) 56(84) bytes of data.
64 bytes from 172.17.0.2: icmp_seq=1 ttl=64 time=0.166 ms
64 bytes from 172.17.0.2: icmp_seq=2 ttl=64 time=0.076 ms
64 bytes from 172.17.0.2: icmp_seq=3 ttl=64 time=0.071 ms
^C
--- 172.17.0.2 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 1999ms
rtt min/avg/max/mdev = 0.071/0.104/0.166/0.044 ms
#让tomcat02 ping tomcat01
[root@localhost ~]# $docker exec -it tomcat02 ping 172.17.0.2
PING 172.17.0.2 (172.17.0.2) 56(84) bytes of data.
64 bytes from 172.17.0.2: icmp_seq=1 ttl=64 time=0.098 ms
64 bytes from 172.17.0.2: icmp_seq=2 ttl=64 time=0.071 ms
小结: Docker使用的是Linux的桥接,宿主机是一个Docker容器的网桥 docker0。Docker 中的所有的网络接口都是虚拟的。虚拟的转发效率高!而且只要容器删除,对应网桥一对就没了!
问题:思考一个场景,我们编写了一个微服务,数据库的配置,database url=ip: ,项目重启,数据库ip换了,我们希望可以处理这个问题,解决可以通过名字来进行访问容器?
使用容器名称ping,发现ping不通。
$ docker exec -it tomcat02 ping tomca01 # ping不通
ping: tomca01: Name or service not known
运行一个tomcat03,将tomcat03和tomcat02容器在运行时,就进行连接(通过 --link)
[root@localhost ~]# docker run -d -P --name tomcat03 --link tomcat02 tomcat
966ed0aba7d617be241ee10c2f27cb8a84e94229d136cfa82010c0f0749aa54a
再次通过容器名称进行ping。通过tomcat03 ping tomcat02,发现能ping通
$ docker exec -it tomcat03 ping tomcat02PING tomcat02
(172.17.0.3) 56(84) bytes of data.64 bytes from tomcat02
(172.17.0.3): icmp_seq=1 ttl=64 time=0.115 ms64 bytes from tomcat02
(172.17.0.3): icmp_seq=2 ttl=64 time=0.080 ms
用tomcat02 ping tomcat03 ping不通。因为没有配置tomcat02。
$ docker exec -it tomcat02 ping tomca03 # ping不通
ping: tomca03: Name or service not known
查看docker当前网卡状况。(命令: docker network ls,有几个容器运行就有几个)
[root@localhost ~]# docker network ls
NETWORK ID NAME DRIVER SCOPE
571a633beadd bridge bridge local
7b08625acf1f host host local
ee2556195442 none null local
查看某个网卡的具体信息。(命令:docker network inspect networkId)
[root@localhost ~]# docker network inspect 571a633beadd
[
{
"Name": "bridge", #默认docker0网卡信息
"Id": "571a633beadd5efd84e4feb4a11453d138045cea0bbecc6b5ecd13c441cd9cd5",
"Created": "2021-10-01T08:21:40.783074646+08:00",
"Scope": "local",
"Driver": "bridge",
"EnableIPv6": false,
"IPAM": {
"Driver": "default",
"Options": null,
"Config": [
{
"Subnet": "172.17.0.0/16",
"Gateway": "172.17.0.1"
}
]
},
"Internal": false,
"Attachable": false,
"Ingress": false,
"ConfigFrom": {
"Network": ""
},
"ConfigOnly": false,
"Containers": {
#容器网卡的信息
"60085eb44b1e81acd7516b78437da393d28a502bccba8c14804c99b58db25cd2": {
"Name": "tomcat01",
"EndpointID": "06aa11572f010e06ba3a9b05f9c46b17a5920554b7b0030a4bf4a20681546b4a",
"MacAddress": "02:42:ac:11:00:03",
"IPv4Address": "172.17.0.3/16",
"IPv6Address": ""
},
"966ed0aba7d617be241ee10c2f27cb8a84e94229d136cfa82010c0f0749aa54a": {
"Name": "tomcat03",
"EndpointID": "6cbb800c65450ce0f81aea40d54fc11ca051cdb6964cee90aa07ae17253ccfc6",
"MacAddress": "02:42:ac:11:00:04",
"IPv4Address": "172.17.0.4/16",
"IPv6Address": ""
},
"b2f4f64055c1efb5099847fa8786f4d883042836b2980bbb4014b9d2410550bd": {
"Name": "tomcat02",
"EndpointID": "aeefeceaef87d5cdf57e04f9ab9b48da62c635121b8bb0e24b61a5bcb2c93631",
"MacAddress": "02:42:ac:11:00:02",
"IPv4Address": "172.17.0.2/16",
"IPv6Address": ""
}
},
"Options": {
"com.docker.network.bridge.default_bridge": "true",
"com.docker.network.bridge.enable_icc": "true",
"com.docker.network.bridge.enable_ip_masquerade": "true",
"com.docker.network.bridge.host_binding_ipv4": "0.0.0.0",
"com.docker.network.bridge.name": "docker0",
"com.docker.network.driver.mtu": "1500"
},
"Labels": {
}
}
]
查看tomcat03容器中的hosts文件。就可发现为什么能够通过容器名就能够访问ping通它。在查看其他容器的hosts文件,进行对比,。
[root@localhost ~]# docker exec -it 966ed0aba7d6 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.2 tomcat02 b2f4f64055c1 #这个tomcat03容器就绑定了tomcat02的访问路径
172.17.0.4 966ed0aba7d6
原理:–link 本质就是在容器中的/etc/hosts 配置中添加映射(容器名和ip之间的映射),但是现在使用Docker已经不建议使用–link了!docker0存在问题,不支持容器名连接访问!所以,我们自定义网络,自定义的网络就可以通过容器名相互访问,不使用docker0!
查看网络的帮助命令
[root@localhost ~]# docker network --help
Usage: docker network COMMAND
Manage networks
Commands:
connect #将容器连接到网络
create #创建网络
disconnect #断开容器与网络的连接
inspect #显示一个或多个网络上的详细信息
ls #列表网络
prune #删除所有未使用的网络
rm #删除一个或多个网络
Run 'docker network COMMAND --help' for more information on a command.
查看所有的docker网络
[root@localhost ~]# docker network ls
NETWORK ID NAME DRIVER SCOPE
571a633beadd bridge bridge local
7b08625acf1f host host local
ee2556195442 none null local
网络模式
启动容器,配置网络。
# bridge就是docker0
$ docker run -d -P --name tomcat01 tomcat
等价于 =>
docker run -d -P --name tomcat01 --net bridge tomcat
自定义创建一个网络。
[root@localhost ~]# docker network create --help
Usage: docker network create [OPTIONS] NETWORK
Create a network
Options:
--attachable #启用手动容器附件
--aux-address map #网络驱动程序使用的辅助IPv4或IPv6地址(默认映射[])
--config-from string #要从中复制配置的网络
--config-only #创建仅配置的网络
-d, --driver string #管理网络的驱动程序(默认“网桥”)
--gateway strings #主子网的IPv4或IPv6网关
--ingress #创建群路由网状网络
--internal #限制对网络的外部访问
--ip-range strings #从子范围分配容器ip
--ipam-driver string #IP地址管理驱动程序(默认为“默认”)
--ipam-opt map #设置IPAM驱动程序特定选项(默认映射[])
--ipv6 #启用IPv6网络
--label list #在网络上设置元数据
-o, --opt map #设置特定于驱动程序的选项(默认映射[])
--scope string #控制网络的范围
--subnet strings #表示网段的CIDR格式的子网掩码
# --driver bridge
# --subnet 192.168.0.0/16 子网
# --gateway 192.168.0.1 网关
[root@localhost ~]# docker network create --driver bridge --subnet 192.168.0.0/16 --gateway 192.168.0.1 mynet
a81c8cc97a165235b52a7450c73e9fa65274b65d6544dceea05dfb854dccdb49
#查看所有的docker网络
[root@localhost ~]# docker network ls
NETWORK ID NAME DRIVER SCOPE
571a633beadd bridge bridge local
7b08625acf1f host host local
a81c8cc97a16 mynet bridge local
ee2556195442 none null local
#查看我们自定义的网络的详细信息
[root@localhost ~]# docker network inspect mynet
[
{
"Name": "mynet",
"Id": "a81c8cc97a165235b52a7450c73e9fa65274b65d6544dceea05dfb854dccdb49",
"Created": "2021-10-01T12:53:04.321088729+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": {
}
}
]
# --network mynet 指定使用我们自定义的网络配置
[root@localhost ~]# docker run -d -P --name tomcat-testnet01 --network mynet tomcat
354ea6571b510bd57eba300b4f75f49f03b703cf40fe155acee47ca98480074e
[root@localhost ~]# docker run -d -P --name tomcat-testnet02 --network mynet tomcat
fffc3dd4bc8f9edb01483ef61927378162d410c23ba1024d02a42cb88c518805
[root@localhost ~]# docker exec -it tomcat-testnet01 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.135 ms
64 bytes from 192.168.0.3: icmp_seq=2 ttl=64 time=0.099 ms
[root@localhost ~]# 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.095 ms
64 bytes from tomcat-net-02.mynet (192.168.0.3): icmp_seq=2 ttl=64 time=0.108 ms
64 bytes from tomcat-net-02.mynet (192.168.0.3): icmp_seq=3 ttl=64 time=0.093 ms~]
在自定义的网络下,服务可以互相ping通,不用使用–link。我们自定义的网络docker当我们维护好了对应的关系,推荐我们平时这样使用网络!
好处:
如果使用默认的网络(docker0)启动的tomcat01容器去ping使用mynet网络下的容器。发现ping不通。要将tomcat01 连通 tomcat—testnet01 ,连通就是将 tomcat01加到 mynet网络中。
实现方式。(命令:docker network connect)
[root@localhost ~]# docker network connect --help
Usage: docker network connect [OPTIONS] NETWORK(网络名) CONTAINER(容器名)
Connect a container to a network
Options:
--alias strings #为容器添加网络范围的别名
--driver-opt strings #网络的驱动程序选项
--ip string #IPv4地址(例如172.30.100.104)
--ip6 string #IPv6地址(例如,2001:db8::33)
--link list #添加指向另一个容器的链接
--link-local-ip strings #为容器添加链接本地地址
打通tomcat01 到mynet网络。即一个容器两个ip(tomcat03)(和阿里云是共有访问ip和私有访问IP类似)。
#将tomcat03容器添加到mynet网络中
[root@localhost ~]# docker network connect mynet tomcat03
#查看mynet网络的详细信息
[root@localhost ~]# docker network inspect mynet
测试,tomcat03 ping mynet网络下的容器,能够ping通。没有打通的网络依旧ping不通。
# tomcat03 连通ok
[root@localhost ~]# docker exec -it tomcat03 ping tomcat-testnet01
PING tomcat-net-01 (192.168.0.2) 56(84) bytes of data.
64 bytes from tomcat-net-01.mynet (192.168.0.2): icmp_seq=1 ttl=64 time=0.130 ms
64 bytes from tomcat-net-01.mynet (192.168.0.2): icmp_seq=2 ttl=64 time=0.097 ms
64 bytes from tomcat-net-01.mynet (192.168.0.2): icmp_seq=3 ttl=64 time=0.106 ms
64 bytes from tomcat-net-01.mynet (192.168.0.2): icmp_seq=4 ttl=64 time=0.109 ms
# tomcat02是依旧打不通的
[root@localhost ~]# docker exec -it tomcat02 ping tomcat-testnet01
ping: tomcat-net-01: Name or service not known
结论:假设要跨网络操作别人,就需要使用 docker network connect 连通!