Docker知识点整理
DocKerDocker组成:镜像(images):docker镜像就好比一个模板,tomcat镜像 == =>run==>tomcat容器(提供服务器),通过这个镜像可以创建多个容器(最终服务运行或者项目运行即使在容器中)。容器(container):Docker利用容器技术,独立运行一个或者一个组应用,通过镜像来创建。启动,停止,删除,基本命令!目前就可以把容器理解成一个linuk
DocKer
Docker组成:
镜像(images):
docker镜像就好比一个模板,tomcat镜像 == =>run==>tomcat容器(提供服务器),通过这个镜像可以创建多个容器(最终服务运行或者项目运行即使在容器中)。
容器(container):
Docker利用容器技术,独立运行一个或者一个组应用,通过镜像来创建。
启动,停止,删除,基本命令!
目前就可以把容器理解成一个linuk系统
仓库(respository):
仓库就是存放镜像的地方!
仓库分为公有和私有!
Docker Hub(默认是国外的)
阿里云…都有容器服务器(配置镜像加速!)
安装Docker
环境查看
#系统内核是3.10以上的
[root@iZ8vbcthzqpmrjj3vq8clgZ /]# uname -r
3.10.0-1062.18.1.el7.x86_64
#系统版本
[root@iZ8vbcthzqpmrjj3vq8clgZ /]# 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"
安装
地址:https://docs.docker.com/engine/install/centos/
帮助文档:
#1.卸载旧的版本
yum remove docker \
docker-client \
docker-client-latest \
docker-common \
docker-latest \
docker-latest-logrotate \
docker-logrotate \
docker-engine
#2.需要的安装包
yum install -y yum-utils
#3.设置镜像的仓库
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 #阿里云的 建议安装
#更新yum软件包索引
yum makecache fast
#4.安装docker相关的 docker-ce 社区版 ee企业版
yum install docker-ce docker-ce-cli containerd.io
#5.启动docker 查看docker是否安装成功 docker version
systemctl start docker
#6.测试hello-world
docker run hello-world
#7.查看下载的hello-world镜像
docker images
了解:卸载docker
#1、卸载依赖
yum remove docker-ce docker-ce-cli containerd.io
#2、删除资源 #/var/lib/docker 默认的工作路径
rm -rf /var/lib/docker
#卸载docker
systemctl stop docker
阿里云镜像加速
配置使用:
第一步 : sudo mkdir -p /etc/docker
第二步 : sudo tee /etc/docker/daemon.json <<-'EOF'
{
"registry-mirrors": ["https://75nxl19m.mirror.aliyuncs.com"]
}
EOF
第三步 : sudo systemctl daemon-reload
第四步 : sudo systemctl restart docker
回顾HelloWord流程
#6.测试hello-world
docker run hello-world
底层原理:
docker是什么工作的?
docker是一个Client -server结构的系统,docker的守护进程运行在主机上。通过Socket从客户端访问!
dockerServer接受到docker-Client的指令,就会执行这个命令!
Docker基本命令
帮助命令
docker version #显示docker的版本信息
docker info #显示docker的系统信息,也包括镜像的容器的数量
docker 命令 --help #帮助命令
帮助文档地址:https://docs.docker.com/reference/
镜像命令
docker images 查看所有本地的主机上的镜像
docker images -aq #查看所有镜像ID
docker search 搜索镜像
root@iZ8vbcthzqpmrjj3vq8clgZ /]# docker search mysql
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
mysql MySQL is a widely used, open-source relation… 9891 [OK]
mariadb MariaDB is a community-developed fork of MyS… 3619 [OK]
[root@iZ8vbcthzqpmrjj3vq8clgZ /]# docker search --help
Usage: docker search [OPTIONS] TERM
Search the Docker Hub for images
Options:
-f, --filter filter Filter output based on conditions provided
--format string Pretty-print search using a Go template
--limit int Max number of search results (default 25)
--no-trunc Don't truncate output
[root@iZ8vbcthzqpmrjj3vq8clgZ /]# docker search mysql -f=STARS=3000
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
mysql MySQL is a widely used, open-source relation… 9891 [OK]
mariadb MariaDB is a community-developed fork of MyS… 3619 [OK]
[root@iZ8vbcthzqpmrjj3vq8clgZ /]# docker search mysql -f=STARS=5000
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
mysql MySQL is a widely used, open-source relation… 9891 [OK]
docker pull 下载镜像
#下载镜像 docker pull 镜像名 [:tag]
【root @he /】# docker pull mysql
#指定版本下载
docker pull mysql:5.7
docker rmi 删除镜像
docker rmi -f 镜像ID #根据镜像ID删除指定镜像
docker rmi -f 镜像ID 镜像ID 镜像ID #根据镜像ID删除多个镜像
docker rmi -f $(docker images -aq) #删除所有镜像
列出本地镜像的变更历史
docker history 镜像ID
容器命令
说明:我们有了镜像才能创建容器,Linux,下载一个centos来学习
docker pull centos
新建容器并启动
docker run [可选参数] images
#参数说明
--name="Name" 容器的名字 例:tomcat01 tomcat02 ,用来区分容器
-d 后台方式运行
-it 使用交互方式运行,进入容器查看内容
-P 指定容器的端口 -p 8080:8080
-P ip:主机端口:容器端口
-P 主机端口:容器端口 (常用)
-P 容器端口
容器端口
-p 随机指定端口
#测试 启动并进入容器
[root@he /]# docker run -it centos /bin/bash
[root@e4eccc01b495 /]# ls #查看容器内的centos
[root@e4eccc01b495 /]#exit #退出容器
列出所有的运行的容器
# docker ps 命令
#查看当前正在运行的容器
-a #查看当前正在运行的容器+历史运行的容器
an=? #显示最近创建的容器
-q #只显示容器的编号
docker ps #查看当前正在运行的容器
docker ps -a #查看当前正在运行的容器+历史运行的容器
docker ps -a -n=1 #只显示一个
docker ps -aq #显示容器的编号
[root@iZ8vbcthzqpmrjj3vq8clgZ /]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
[root@iZ8vbcthzqpmrjj3vq8clgZ /]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
ed9984b3052a centos "/bin/bash" 4 minutes ago Exited (0) About a minute ago pensive_cerf
a18f252f83ee hello-world "/hello" 3 hours ago Exited (0) 3 hours ago youthful_margulis
[root@iZ8vbcthzqpmrjj3vq8clgZ /]#
退出容器
# exit #停止并退出
Ctrl + P + Q #不停止退出
删除容器
docker rm 容器ID #根据镜像ID删除指定容器,不能删除正在运行的容器 rm -f
docker rm -f $(docker ps -aq) #删除所有容器
docker -a -q|xargs docker rm #删除所有容器
启动和停止容器的操作
docker start 容器ID #启动容器
docker restart 容器ID #重启容器
docker stop 容器ID #停止当前正在运行的容器
docker kill 容器ID #杀死容器
常用的其他命令
后台启动容器
# 命令 docker run -d 镜像名!
docker run -d centos
#问题docker ps 发现centos停止了
#常见的坑,docker容器使用的后台,就必须要有一个前台的进程,docker发现没有应用,就会自动停止
#nginx, 容器启动后,发现自己没有提供程序服务,就会立刻停止,就没有程序了
查看日志
docker logs -f -t --tail 10 镜像ID
#编写shell脚本
docker run -d centos /bin/sh -c "while true;do echo helloWord;sleep 1;done"
docker ps #查看镜像id
#显示日志
-tf #显示日志
--tail number #显示日志的条数
docker logs -tf --tail 10 镜像ID
查看容器中的进程信息 ps
# docker top 容器id
[root@iZ8vbcthzqpmrjj3vq8clgZ /]# docker top 531e071abce5
UID PID PPID C STIME TTY TIME CMD
root 29838 29821 0 15:10 ? 00:00:00 /bin/sh -c while true;do echo helloWord;sleep 1;done
root 29967 29838 0 15:10 ? 00:00:00 /usr/bin/coreutils --coreutils-prog-shebang=sleep /usr/bin/sleep 1
docker镜像的元数据
docker ps -a 获取镜像id
# docker inspect 镜像id
[root@iZ8vbcthzqpmrjj3vq8clgZ /]# docker inspect 531e071abce5
[
{
"Id": "531e071abce53b7232515f5d91d860d972183de13af6ffa40d0fb411d4ffc7f0",
"Created": "2020-08-26T07:10:04.514965113Z",
"Path": "/bin/sh",
"Args": [
"-c",
"while true;do echo helloWord;sleep 1;done"
],
"State": {
"Status": "running",
"Running": true,
"Paused": false,
"Restarting": false,
"OOMKilled": false,
"Dead": false,
"Pid": 29838,
"ExitCode": 0,
"Error": "",
"StartedAt": "2020-08-26T07:10:04.865155748Z",
"FinishedAt": "0001-01-01T00:00:00Z"
},
"Image": "sha256:0d120b6ccaa8c5e149176798b3501d4dd1885f961922497cd0abef155c869566",
"ResolvConfPath": "/var/lib/docker/containers/531e071abce53b7232515f5d91d860d972183de13af6ffa40d0fb411d4ffc7f0/resolv.conf",
"HostnamePath": "/var/lib/docker/containers/531e071abce53b7232515f5d91d860d972183de13af6ffa40d0fb411d4ffc7f0/hostname",
"HostsPath": "/var/lib/docker/containers/531e071abce53b7232515f5d91d860d972183de13af6ffa40d0fb411d4ffc7f0/hosts",
"LogPath": "/var/lib/docker/containers/531e071abce53b7232515f5d91d860d972183de13af6ffa40d0fb411d4ffc7f0/531e071abce53b7232515f5d91d860d972183de13af6ffa40d0fb411d4ffc7f0-json.log",
"Name": "/jolly_jang",
"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/4fd91376594c318df8fb8b56748835b4c85d82e34a55c862708b1cd1f18c3444-init/diff:/var/lib/docker/overlay2/b4d571254e04ba19caaeefd3eb83e7881f553de13491488fa24bb71498a82973/diff",
"MergedDir": "/var/lib/docker/overlay2/4fd91376594c318df8fb8b56748835b4c85d82e34a55c862708b1cd1f18c3444/merged",
"UpperDir": "/var/lib/docker/overlay2/4fd91376594c318df8fb8b56748835b4c85d82e34a55c862708b1cd1f18c3444/diff",
"WorkDir": "/var/lib/docker/overlay2/4fd91376594c318df8fb8b56748835b4c85d82e34a55c862708b1cd1f18c3444/work"
},
"Name": "overlay2"
},
"Mounts": [],
"Config": {
"Hostname": "531e071abce5",
"Domainname": "",
"User": "",
"AttachStdin": false,
"AttachStdout": false,
"AttachStderr": false,
"Tty": false,
"OpenStdin": false,
"StdinOnce": false,
"Env": [
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
],
"Cmd": [
"/bin/sh",
"-c",
"while true;do echo helloWord;sleep 1;done"
],
"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": "818c6b1856cbc080e71add9e8943b24454cab1e2f035383e8a788958fe520cb4",
"HairpinMode": false,
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"Ports": {},
"SandboxKey": "/var/run/docker/netns/818c6b1856cb",
"SecondaryIPAddresses": null,
"SecondaryIPv6Addresses": null,
"EndpointID": "9a894a173d6c851ae031db7d898061f72d2a4a371ec2d342268c89f939d3d7b0",
"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": "6ffe87afd055ace6801086e069b9be535edb4aa4db40799c5abb9b8629b2823e",
"EndpointID": "9a894a173d6c851ae031db7d898061f72d2a4a371ec2d342268c89f939d3d7b0",
"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
#方式二:
docker attach 镜像id
#区别:
#exec 进入容器打开一个新的终端,可以在里面操作
#attach 进入容器正在执行的终端,
[root@iZ8vbcthzqpmrjj3vq8clgZ /]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
531e071abce5 centos "/bin/sh -c 'while t…" 5 minutes ago Up 5 minutes jolly_jang
[root@iZ8vbcthzqpmrjj3vq8clgZ /]# docker exec -it 531e071abce5 /bin/bash
[root@531e071abce5 /]# ls
bin dev etc home lib lib64 lost+found media mnt opt proc root run sbin srv sys tmp usr var
[root@531e071abce5 /]# ps -ef
UID PID PPID C STIME TTY TIME CMD
root 1 0 0 07:10 ? 00:00:00 /bin/sh -c while true;do echo helloWord;sleep 1;done
root 333 0 0 07:15 pts/0 00:00:00 /bin/bash
root 366 1 0 07:15 ? 00:00:00 /usr/bin/coreutils --coreutils-prog-shebang=sleep /usr/bin/sleep 1
root 367 333 0 07:15 pts/0 00:00:00 ps -ef
[root@531e071abce5 /]#
从容器上拷贝文件到主机上
#命令
docker cp 镜像id:/home/test.java /home
#容器上的文件路径 主机上的文件路径
目前拷贝是手动的 ,未来用 -v 数据卷的技术可以实现
#拷贝
cp -r webapps.dist/* webappa
新建一个文件
#命令
touch test.java
小结
安装Nginx
安装tomcat
#拷贝
cp -r webapps.dist/* webappa
部署es+kibana
#下载并启动elasticsearch
docker run -d --name elasticsearch -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" elasticsearch:7.6.2
#测试启动成功
[root@iZ8vbcthzqpmrjj3vq8clgZ /]# curl localhost:9200
{
"name" : "2c6ea68fda94",
"cluster_name" : "docker-cluster",
"cluster_uuid" : "uUemE3SDTsC7abl434dUJw",
"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 --name elasticsearch01 -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" -e ES_JAVA_OPTS="-Xms64m -Xmx512m" elasticsearch:7.6.2
docker stats #查看CPU状态
安装kibana
docker run -d --name kibana -p 5601:5601 kibana:7.6.2
可视化
- portainer(先用这个)
- Rancher(CI/CD再用)
docker run -d -p 8089:9000 \
--restart=always -v /var/run/docker.sock:/var/run/docker.sock --privileged=true portainer/portainer
commit镜像
docker commit 提交容器成为一个新的副本
#命令和git原理类似
docker commit -m="提交的描述信息" -a="作者" 容器id 目标镜像名:[TAG]
容器数据卷
总结一句话:容器的持久化和同步操作!容器间也是可以数据共享的!
使用数据卷
方式一 :直接使用命令来挂载 -v
#命令
docker run -it -v 主机目录:容器内目录
#测试
docker run -it -v /home/cesi:/home centos /bin/bash
测试文件的同步
总结: 停止容器,在宿主机上修改文件,再次启动容器,发现容器内的数据和主机是同步的。
实战:安装MySql
#获取镜像
#命令
docker pull mysql:5.7
#运行Mysql时进行数据挂载 #安装启动mysql需要设置密码
# 官方的测试 docker run --name some-mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:tag
#启动mysql命令
docker run -d -p 3344:3306
-v /home/docker/mysql/conf:/etc/mysql/cong.d
-v /home/docker/mysql/data:/var/lib/mysql
-e MYSQL_ROOT_PASSWORD=root
--name=mysql01 mysql:5.7
假设我们将容器删除,发现我们挂载本地的数据并没有丢失,这就实现了数据持久化功能!
具名挂载和匿名挂载
所有的docker容器内部卷,没有指定目录的情况下都是在/var/lib/docker/volumes/xxxx/_data
我们通过具名挂载可以方便的找到我们的一个卷,大多数情况下在使用具名挂载
#怎么确定是匿名挂载,还是具名挂载,还是指定路径挂载
-v 容器内路径 #匿名挂载
-v 卷名:容器内路径 #具名挂载
-v /宿主机路径:容器内路径 #指定路径挂载
拓展:
#通过 -v 容器路径:ro rw 改变读写路径
ro: readonly #只读
rw: readwrite #可读可写
docker run -d -P -v juming-nignx:/ect/nignx:ro --name nignx02 ngnix
docker run -d -P -v juming-nignx:/ect/nignx:rw --name nignx02 ngnix
初始DockerFile
DockerFile就是用来构建docker镜像的构建文件!命令脚本!
通过这个脚本可以生成一个镜像,镜像是一层层的,脚本是一个个的命令,每个命令都是一层!
在home文件夹下建一个docker-test-volume文件夹,以后脚本基本都写在这里
#创建一个DockerFile文件 ,名字随机,建议DockerFile
#文件中的内容 指令(大写)
FROM centos
VOLUME ["volume01","volume02"]
CMD echo "----end----"
CMD /bin/bash
#这里的每个命令,就是镜像一层
#生成镜像:
docker build -f /home/docker-test-volume/dockerfile1 -t he/centos:1.0 .
-f 文件的路径
-t 生成镜像的名称版本
[root@iZ8vbcthzqpmrjj3vq8clgZ docker-test-volume]# pwd
/home/docker/docker-test-volume
[root@iZ8vbcthzqpmrjj3vq8clgZ docker-test-volume]# vim dockerfile01
[root@iZ8vbcthzqpmrjj3vq8clgZ docker-test-volume]# cat dockerfile01
FROM centos
VOLUME ["volume01","volume02"]
CMD echo "---end---"
CMD /bin/bash
[root@iZ8vbcthzqpmrjj3vq8clgZ docker-test-volume]# pwd
/home/docker/docker-test-volume
[root@iZ8vbcthzqpmrjj3vq8clgZ docker-test-volume]# vim dockerfile01
[root@iZ8vbcthzqpmrjj3vq8clgZ docker-test-volume]# cat dockerfile01
FROM centos
VOLUME ["volume01","volume02"]
CMD echo "---end---"
CMD /bin/bash
[root@iZ8vbcthzqpmrjj3vq8clgZ docker-test-volume]# docker build -f /home/docker/docker-test-volume/dockerfile01 -t hqy/centos:1.0 .
Sending build context to Docker daemon 2.048kB
Step 1/4 : FROM centos
---> 0d120b6ccaa8
Step 2/4 : VOLUME ["volume01","volume02"]
---> Running in 8f9339331a46
Removing intermediate container 8f9339331a46
---> 89d5ddb6c104
Step 3/4 : CMD echo "---end---"
---> Running in 4ee9006a5d7a
Removing intermediate container 4ee9006a5d7a
---> 70be62a354eb
Step 4/4 : CMD /bin/bash
---> Running in 7e795004ca87
Removing intermediate container 7e795004ca87
---> e4e84d6dff97
Successfully built e4e84d6dff97
Successfully tagged hqy/centos:1.0
[root@iZ8vbcthzqpmrjj3vq8clgZ docker-test-volume]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
hqy/centos 1.0 e4e84d6dff97 9 seconds ago 215MB
数据卷容器
多个mysql 同步数据
#测试
docker run -it --name docker01 镜像id
docker run -it --name docker02 --volumes-from docker01 镜像id
docker run -it --name docker03 --volumes-from docker01 镜像id
#测试,可以删除docker01,查看docker02和docker03是否可以访问这个文件
#测试依旧可以访问
多个mysql实现数据共享
docker run -d -p 3344:3306
-v /home/mysql/conf:/etc/mysql/conf.d
-v /home/mysql/data:/var/lib/mysql
-e MYSQL_ROOT_PASSWORD=root
--name mysql01 mysql:5.7
docker run -d -p 3344:3306
-e MYSQL_ROOT_PASSWORD=123456
-v /home/mysql/conf:/etc/mysql/conf.d
-v /home/mysql/data:/var/lib/mysql
--volumes-from mysql01 --name mysql02 mysql:5.7
#这个时候可以实现两个容器数据同步
结论:
容器之间配置信息的传递,数据卷容器的生命周期一直持续到没有容器为止。
但是一旦你持久化到了本地,这个时候数据不会删除的!
DockerFile
docker file 是用来构建docker镜像的文件!命令参数脚本!
构建步骤:
1、编写一个docker file文件
2、docker build 构建成为一个镜像
3、docker run 运行镜像
4、docker push 发布镜像(dockerHub 、 阿里云)
看看官方是怎么发布的?
Docker File 构建过程
1、每个保留关键字(指令)都是大写字母。
2、执行从上到下顺序执行。
3、#表示注释。
4、每个指令都会创建提交一个新的镜像层,并提交。
docker file是面向开发的,我们以后要发布项目,做镜像,就需要编写docker file文件,这个文件十分简单!
docker镜像逐渐成为企业交付的标准,必须要掌握!
步骤:开发,部署,运维…缺一不可!
docker file :构建文件,定义了一切的步骤,源代码。
dockerimages:通过docker file构建生成镜像,最终发布和运行发布产品
docker容器:容器就是镜像运行起来提供服务
docker file的指令
FROM #基础镜像,一切从这里开始构建
MAINTAINER #镜像是谁写的,姓名+邮箱
RUN #镜像构建的时候需要运行的命令
ADD #步骤,tomcat镜像,这个tomcat压缩包!添加内容
WORKDIR #镜像的工作目录
VOLUME #挂载的目录
EXPOSE #暴露端口配置 和-p一个意思
CMD #指定这个容器启动的时候要运行的命令,只有最后一个生效,可被替代
ENTRYPOINT #指定这个容器启动的时候要运行的命令,可以追加命令
ONBUILD #当构建一个被继承DockerFile这个时候就会运行ONBUILD 的指令,触发指令
COPY #类似ADD,将我们文件拷贝到镜像中
ENV #构建的时候设置环境变量!
实战测试:
Docker Hub中99%的镜像都是从这个基础镜像过来的 FROM scratch ,然后配置需要的软件和配置来进行构建
创建一个自己的镜像
#1、编写自己的docker file文件
FROM centos
MAINTAINER hqy<2214946614@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 "---end---"
CMD /bin/bash
#2、通过这个文件构建镜像
#通过命令
dockerfile build -f dockerfile文件路径 -t 镜像名:[tag]
Successfully built d7900e8479cd
Successfully tagged mydockerfile:1.0
#3、测试运行
# docker history d7900e8479cd
[root@iZ8vbcthzqpmrjj3vq8clgZ dockerfile]# docker history d7900e8479cd
IMAGE CREATED CREATED BY SIZE COMMENT
d7900e8479cd 8 minutes ago /bin/sh -c #(nop) CMD ["/bin/sh" "-c" "/bin… 0B
f8d50f0a2f58 8 minutes ago /bin/sh -c #(nop) CMD ["/bin/sh" "-c" "\"--… 0B
42d41447179f 8 minutes ago /bin/sh -c #(nop) CMD ["/bin/sh" "-c" "echo… 0B
dd12e9135ee0 8 minutes ago /bin/sh -c #(nop) EXPOSE 80 0B
17a7586ca48d 8 minutes ago /bin/sh -c yum -y install net-tools 22.8MB
c281d99ee66f 9 minutes ago /bin/sh -c yum -y install vim 57.2MB
7d19008adaa1 9 minutes ago /bin/sh -c #(nop) WORKDIR /usr/local 0B
0c0a65dd6a7d 9 minutes ago /bin/sh -c #(nop) ENV MYPATH=/usr/local 0B
dd14db7752f9 9 minutes ago /bin/sh -c #(nop) MAINTAINER hqy<2214946614… 0B
0d120b6ccaa8 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:538afc0c5c964ce0d… 215MB
CMD 和 ENTRYPOINT 区别
CMD #指定这个容器启动的时候要运行的命令,只有最后一个生效,可被替代
ENTRYPOINT #指定这个容器启动的时候要运行的命令,可以追加命令
#CMD
FROM centos
CMD ["ls","-a"]
#ENTRYPOINT
FROM centos
ENTRYPOINT ["ls","-a"]
docker命令中基本上都很相似,我们需要了解他们,最好的效果就是对比着他们测试
实战docker file制作tomcat镜像
1、准备镜像文件 ,tomcat压缩包,jdk压缩包
2、编写docker file文件,官方命名Dockerfile ,build的时候就会自动寻找不用再-f
FROM centos
MAINTAINER hqy<2214946614@qq.com>
COPY readme.txt /usr/local/readme.txt
ADD apache-tomcat-9.0.37.tar.gz /usr/local/
ADD jdk-8u261-linux-x64.tar.gz /usr/local/
RUN yum -y install vim
ENV MYPATH /usr/local
WORKDIR $MYPATH
ENV JAVA_HOME /usr/local/jdk1.8.0_261
ENV CLASSPATH $JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
ENV CATALIAN_HOME /usr/local/apache-tomcat-9.0.37
ENV CATALIAN_BASH /usr/local/apache-tomcat-9.0.37
ENV PATH $PATH:$JAVA_HOME/bin:$CATALIAN_HOME/lib:$CATALIAN_HOME/bin
EXPOSE 8080
CMD /usr/local/apache-tomcat-9.0.37/bin/startup.sh && tail -F /url/local/apache-tomcat-9.0.37/bin/logs/catalina.out
#生成镜像
docker build -t diytomcat .
启动tomcat:
docker run -d -p 3355:8080 --name Dockerfile-tomcat -v /home/docker/tomcat/test:/usr/local/apache-tomcat-9.0.37/webapps/test -v /home/docker/tomcat/mylogs/:/usr/local/apache-tomcat-9.0.37/logs diytomcat
[root@iZ8vbcthzqpmrjj3vq8clgZ tar]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
cf312e3aa6b7 diytomcat "/bin/sh -c '/usr/lo…" 7 seconds ago Up 5 seconds 0.0.0.0:3355->8080/tcp Dockerfile-tomcat
[root@iZ8vbcthzqpmrjj3vq8clgZ tar]# curl localhost:3355
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Apache Tomcat/9.0.37</title>
<link href="favicon.ico" rel="icon" type="image/x-icon" />
<link href="favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link href="tomcat.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="wrapper">
<div id="navigation" class="curved container">
<span id="nav-home"><a href="https://tomcat.apache.org/">Home</a></span>
<span id="nav-hosts"><a href="/docs/">Documentation</a></span>
<span id="nav-config"><a href="/docs/config/">Configuration</a></span>
<span id="nav-examples"><a href="/examples/">Examples</a></span>
<span id="nav-wiki"><a href="https://wiki.apache.org/tomcat/FrontPage">Wiki</a></span>
<span id="nav-lists"><a href="https://tomcat.apache.org/lists.html">Mailing Lists</a></span>
<span id="nav-help"><a href="https://tomcat.apache.org/findhelp.html">Find Help</a></span>
<br class="separator" />
</div>
<div id="asf-box">
<h1>Apache Tomcat/9.0.37</h1>
</div>
<div id="upper" class="curved container">
<div id="congrats" class="curved container">
<h2>If you're seeing this, you've successfully installed Tomcat. Congratulations!</h2>
</div>
<div id="notice">
<img src="tomcat.png" alt="[tomcat logo]" />
<div id="tasks">
<h3>Recommended Reading:</h3>
<h4><a href="/docs/security-howto.html">Security Considerations How-To</a></h4>
<h4><a href="/docs/manager-howto.html">Manager Application How-To</a></h4>
<h4><a href="/docs/cluster-howto.html">Clustering/Session Replication How-To</a></h4>
</div>
</div>
<div id="actions">
<div class="button">
<a class="container shadow" href="/manager/status"><span>Server Status</span></a>
</div>
<div class="button">
<a class="container shadow" href="/manager/html"><span>Manager App</span></a>
</div>
<div class="button">
<a class="container shadow" href="/host-manager/html"><span>Host Manager</span></a>
</div>
</div>
<br class="separator" />
</div>
<div id="middle" class="curved container">
<h3>Developer Quick Start</h3>
<div class="col25">
<div class="container">
<p><a href="/docs/setup.html">Tomcat Setup</a></p>
<p><a href="/docs/appdev/">First Web Application</a></p>
</div>
</div>
<div class="col25">
<div class="container">
<p><a href="/docs/realm-howto.html">Realms & AAA</a></p>
<p><a href="/docs/jndi-datasource-examples-howto.html">JDBC DataSources</a></p>
</div>
</div>
<div class="col25">
<div class="container">
<p><a href="/examples/">Examples</a></p>
</div>
</div>
<div class="col25">
<div class="container">
<p><a href="https://wiki.apache.org/tomcat/Specifications">Servlet Specifications</a></p>
<p><a href="https://wiki.apache.org/tomcat/TomcatVersions">Tomcat Versions</a></p>
</div>
</div>
<br class="separator" />
</div>
<div id="lower">
<div id="low-manage" class="">
<div class="curved container">
<h3>Managing Tomcat</h3>
<p>For security, access to the <a href="/manager/html">manager webapp</a> is restricted.
Users are defined in:</p>
<pre>$CATALINA_HOME/conf/tomcat-users.xml</pre>
<p>In Tomcat 9.0 access to the manager application is split between
different users. <a href="/docs/manager-howto.html">Read more...</a></p>
<br />
<h4><a href="/docs/RELEASE-NOTES.txt">Release Notes</a></h4>
<h4><a href="/docs/changelog.html">Changelog</a></h4>
<h4><a href="https://tomcat.apache.org/migration.html">Migration Guide</a></h4>
<h4><a href="https://tomcat.apache.org/security.html">Security Notices</a></h4>
</div>
</div>
<div id="low-docs" class="">
<div class="curved container">
<h3>Documentation</h3>
<h4><a href="/docs/">Tomcat 9.0 Documentation</a></h4>
<h4><a href="/docs/config/">Tomcat 9.0 Configuration</a></h4>
<h4><a href="https://wiki.apache.org/tomcat/FrontPage">Tomcat Wiki</a></h4>
<p>Find additional important configuration information in:</p>
<pre>$CATALINA_HOME/RUNNING.txt</pre>
<p>Developers may be interested in:</p>
<ul>
<li><a href="https://tomcat.apache.org/bugreport.html">Tomcat 9.0 Bug Database</a></li>
<li><a href="/docs/api/index.html">Tomcat 9.0 JavaDocs</a></li>
<li><a href="https://github.com/apache/tomcat/tree/master">Tomcat 9.0 Git Repository at GitHub</a></li>
</ul>
</div>
</div>
<div id="low-help" class="">
<div class="curved container">
<h3>Getting Help</h3>
<h4><a href="https://tomcat.apache.org/faq/">FAQ</a> and <a href="https://tomcat.apache.org/lists.html">Mailing Lists</a></h4>
<p>The following mailing lists are available:</p>
<ul>
<li id="list-announce"><strong><a href="https://tomcat.apache.org/lists.html#tomcat-announce">tomcat-announce</a><br />
Important announcements, releases, security vulnerability notifications. (Low volume).</strong>
</li>
<li><a href="https://tomcat.apache.org/lists.html#tomcat-users">tomcat-users</a><br />
User support and discussion
</li>
<li><a href="https://tomcat.apache.org/lists.html#taglibs-user">taglibs-user</a><br />
User support and discussion for <a href="https://tomcat.apache.org/taglibs/">Apache Taglibs</a>
</li>
<li><a href="https://tomcat.apache.org/lists.html#tomcat-dev">tomcat-dev</a><br />
Development mailing list, including commit messages
</li>
</ul>
</div>
</div>
<br class="separator" />
</div>
<div id="footer" class="curved container">
<div class="col20">
<div class="container">
<h4>Other Downloads</h4>
<ul>
<li><a href="https://tomcat.apache.org/download-connectors.cgi">Tomcat Connectors</a></li>
<li><a href="https://tomcat.apache.org/download-native.cgi">Tomcat Native</a></li>
<li><a href="https://tomcat.apache.org/taglibs/">Taglibs</a></li>
<li><a href="/docs/deployer-howto.html">Deployer</a></li>
</ul>
</div>
</div>
<div class="col20">
<div class="container">
<h4>Other Documentation</h4>
<ul>
<li><a href="https://tomcat.apache.org/connectors-doc/">Tomcat Connectors</a></li>
<li><a href="https://tomcat.apache.org/connectors-doc/">mod_jk Documentation</a></li>
<li><a href="https://tomcat.apache.org/native-doc/">Tomcat Native</a></li>
<li><a href="/docs/deployer-howto.html">Deployer</a></li>
</ul>
</div>
</div>
<div class="col20">
<div class="container">
<h4>Get Involved</h4>
<ul>
<li><a href="https://tomcat.apache.org/getinvolved.html">Overview</a></li>
<li><a href="https://tomcat.apache.org/source.html">Source Repositories</a></li>
<li><a href="https://tomcat.apache.org/lists.html">Mailing Lists</a></li>
<li><a href="https://wiki.apache.org/tomcat/FrontPage">Wiki</a></li>
</ul>
</div>
</div>
<div class="col20">
<div class="container">
<h4>Miscellaneous</h4>
<ul>
<li><a href="https://tomcat.apache.org/contact.html">Contact</a></li>
<li><a href="https://tomcat.apache.org/legal.html">Legal</a></li>
<li><a href="https://www.apache.org/foundation/sponsorship.html">Sponsorship</a></li>
<li><a href="https://www.apache.org/foundation/thanks.html">Thanks</a></li>
</ul>
</div>
</div>
<div class="col20">
<div class="container">
<h4>Apache Software Foundation</h4>
<ul>
<li><a href="https://tomcat.apache.org/whoweare.html">Who We Are</a></li>
<li><a href="https://tomcat.apache.org/heritage.html">Heritage</a></li>
<li><a href="https://www.apache.org">Apache Home</a></li>
<li><a href="https://tomcat.apache.org/resources.html">Resources</a></li>
</ul>
</div>
</div>
<br class="separator" />
</div>
<p class="copyright">Copyright ©1999-2020 Apache Software Foundation. All Rights Reserved</p>
</div>
</body>
</html>
#web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
</web-app>
#index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>欢迎来到此页面</title>
</head>
<body>
Hello World!<br/>
<%
out.println("奥利给");
%>
</body>
</html>
发布镜像到DockerHub上
1、创建一个自己的dockerHub账号
2、登录dockerHub
[root@iZ8vbcthzqpmrjj3vq8clgZ mylogs]# docker login --help
Usage: docker login [OPTIONS] [SERVER]
Log in to a Docker registry.
If no server is specified, the default is defined by the daemon.
Options:
-p, --password string Password
--password-stdin Take the password from stdin
-u, --username string Username
#命令
docker login -u hyq121 -p www5211258
[root@iZ8vbcthzqpmrjj3vq8clgZ mylogs]# docker login -u hqy121
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
3、提交
#命令
docker push hqy/dirtomcat:1.0
[root@iZ8vbcthzqpmrjj3vq8clgZ tomcat]# docker tag 29d10d9c2740 hqy/tomcat:1.0
[root@iZ8vbcthzqpmrjj3vq8clgZ tomcat]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
hqy/tomcat 1.0 29d10d9c2740 About an hour ago 640MB
diytomcat latest 29d10d9c2740 About an hour ago 640MB
[root@iZ8vbcthzqpmrjj3vq8clgZ tomcat]# docker push hqy/tomcat:1.0
The push refers to repository [docker.io/hqy/tomcat]
e265b92b47af: Preparing
3e17b3b1b523: Preparing
14ed54501674: Preparing
07cf60fb981b: Preparing
291f6e44771a: Preparing
denied: requested access to the resource is denied #拒绝
[root@iZ8vbcthzqpmrjj3vq8clgZ tomcat]#
[root@iZ8vbcthzqpmrjj3vq8clgZ ~]# docker tag diytomcat:latest hqy121/tomcat:java
[root@iZ8vbcthzqpmrjj3vq8clgZ ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
diytomcat latest 29d10d9c2740 3 hours ago 640MB
hqy121/tomcat java 29d10d9c2740 3 hours ago 640MB
[root@iZ8vbcthzqpmrjj3vq8clgZ ~]# docker push hqy121/tomcat:java
The push refers to repository [docker.io/hqy121/tomcat]
e265b92b47af: Pushing [=> ] 1.664MB/57.23MB
3e17b3b1b523: Pushing [> ] 1.629MB/352.4MB
14ed54501674: Pushing [=======> ] 2.211MB/15.63MB
发布镜像到阿里云容器服务
1、登录阿里云
2、找到容器镜像服务
3、创建命名空间
4、创建容器镜像
5、上传镜像
[root@iZ8vbcthzqpmrjj3vq8clgZ ~]# docker login --username=蜗蜗牛牛蜗 registry.cn-hangzhou.aliyuncs.com
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
[root@iZ8vbcthzqpmrjj3vq8clgZ ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
hqy121/tomcat java 29d10d9c2740 6 hours ago 640MB
diytomcat latest 29d10d9c2740 6 hours ago 640MB
mydockerfile 1.0 d7900e8479cd 22 hours ago 295MB
hqy/centos 1.0 e4e84d6dff97 26 hours ago 215MB
tomcat01 1.0 009125e8f6ac 30 hours ago 652MB
nginx latest 4bb46517cac3 2 weeks ago 133MB
centos latest 0d120b6ccaa8 2 weeks ago 215MB
tomcat 9.0 2ae23eb477aa 3 weeks ago 647MB
tomcat latest 2ae23eb477aa 3 weeks ago 647MB
mysql 5.7 718a6da099d8 3 weeks ago 448MB
portainer/portainer latest 62771b0b9b09 5 weeks ago 79.1MB
kibana 7.6.2 f70986bc5191 5 months ago 1.01GB
elasticsearch 7.6.2 f29a1ee41030 5 months ago 791MB
[root@iZ8vbcthzqpmrjj3vq8clgZ ~]# docker push hqy121/tomcat:java
小结:
Docker网络
理解Docker0
第一步:清空所有环境
测试
[root@iZ8vbcthzqpmrjj3vq8clgZ ~]# 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
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether 00:16:3e:04:72:30 brd ff:ff:ff:ff:ff:ff
inet 172.26.185.175/20 brd 172.26.191.255 scope global dynamic eth0
valid_lft 312748100sec preferred_lft 312748100sec
3: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default
link/ether 02:42:55:26:28:5b brd ff:ff:ff:ff:ff:ff
inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
valid_lft forever preferred_lft forever
linux获取IP地址的命令:ip addr
[root@iZ8vbcthzqpmrjj3vq8clgZ ~]# docker run -d -p 3344:8080 --name tomcat01 tomcat
Unable to find image 'tomcat:latest' locally
latest: Pulling from library/tomcat
d6ff36c9ec48: Pull complete
c958d65b3090: Pull complete
edaf0a6b092f: Pull complete
80931cf68816: Pull complete
bf04b6bbed0c: Pull complete
8bf847804f9e: Pull complete
fa776a6e7e37: Pull complete
586534165c2f: Pull complete
0f6d126a6962: Pull complete
9f3317edffb3: Pull complete
Digest: sha256:9de2415ccf10fe8e5906e4b72eda21649a7a1d0b88e9111f8409062599f3728e
Status: Downloaded newer image for tomcat:latest
9cb7649f1f3833c0a8dd623cec80c39b76a67d8d72cab0b13157cafbe491f6bd
[root@iZ8vbcthzqpmrjj3vq8clgZ ~]# docker exec -it tomcat01 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
124: eth0@if125: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff link-netnsid 0
inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0
valid_lft forever preferred_lft forever
[root@iZ8vbcthzqpmrjj3vq8clgZ ~]# 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.100 ms
64 bytes from 172.17.0.2: icmp_seq=2 ttl=64 time=0.083 ms
64 bytes from 172.17.0.2: icmp_seq=3 ttl=64 time=0.059 ms
64 bytes from 172.17.0.2: icmp_seq=4 ttl=64 time=0.070 ms
^C
--- 172.17.0.2 ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 2999ms
rtt min/avg/max/mdev = 0.059/0.078/0.100/0.015 ms
我们每启动一个docker容器,docker就会给docker容器分配一个IP,我们只要安装了docker就会有一个网卡docker0,桥接模式,使用的技术是evth-pair技术!
[root@iZ8vbcthzqpmrjj3vq8clgZ ~]# 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
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether 00:16:3e:04:72:30 brd ff:ff:ff:ff:ff:ff
inet 172.26.185.175/20 brd 172.26.191.255 scope global dynamic eth0
valid_lft 312747152sec preferred_lft 312747152sec
3: docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
link/ether 02:42:55:26:28:5b brd ff:ff:ff:ff:ff:ff
inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
valid_lft forever preferred_lft forever
125: veth9ba0066@if124: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master docker0 state UP group default
link/ether 56:a4:70:5c:fb:bf brd ff:ff:ff:ff:ff:ff link-netnsid 0
#我们发现这个容器带来网卡,都是一对对的
#evth-pair 就是一对的虚拟设备接口,他们都是成对出来的,一端连着协议,一端彼此相逢
#正因为有这个特性,evth-pair 充当一个桥梁,
#OpenStac,Docker容器之间的连接,OVS的连接,都是使用evth-pair技术
测试tomcat01能否ping通tomcat02
[root@iZ8vbcthzqpmrjj3vq8clgZ ~]# docker run -d -p 3355:8080 --name tomcat02 tomcat
b3722b8c94066b9dc2723cb4fe3c8605e2b7c58e021f850b709f28455b83a6aa
[root@iZ8vbcthzqpmrjj3vq8clgZ ~]# 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
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether 00:16:3e:04:72:30 brd ff:ff:ff:ff:ff:ff
inet 172.26.185.175/20 brd 172.26.191.255 scope global dynamic eth0
valid_lft 312746887sec preferred_lft 312746887sec
3: docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
link/ether 02:42:55:26:28:5b brd ff:ff:ff:ff:ff:ff
inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
valid_lft forever preferred_lft forever
125: veth9ba0066@if124: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master docker0 state UP group default
link/ether 56:a4:70:5c:fb:bf brd ff:ff:ff:ff:ff:ff link-netnsid 0
127: vethdb2f076@if126: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master docker0 state UP group default
link/ether c2:e7:87:be:5a:0b brd ff:ff:ff:ff:ff:ff link-netnsid 1
[root@iZ8vbcthzqpmrjj3vq8clgZ ~]# docker exec -it tomcat01 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.055 ms
64 bytes from 172.17.0.2: icmp_seq=2 ttl=64 time=0.062 ms
64 bytes from 172.17.0.2: icmp_seq=3 ttl=64 time=0.064 ms
64 bytes from 172.17.0.2: icmp_seq=4 ttl=64 time=0.057 ms
64 bytes from 172.17.0.2: icmp_seq=5 ttl=64 time=0.057 ms
^C
--- 172.17.0.2 ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 4ms
rtt min/avg/max/mdev = 0.055/0.059/0.064/0.003 ms
[root@iZ8vbcthzqpmrjj3vq8clgZ ~]#
#结论:容器和容器之间是可以ping通的
结论:tomcat01和tomcat02是公用的一个路由器,docker0
所有的容器不指定网络的情况下,都是由docker0路由的,docker会给我们的容器分配一个默认的可用的IP 0~255
小结
docker使用的是Linux的桥接,宿主机中是一个docker容器的网桥 docker0
docker中所有的网络接口都是虚拟的,虚拟的网络转发效率高!(内网传递文件)
只要容器删除,对应的网桥一对,就会没了
# docker network inspect 容器id
现在玩docker基本上都不使用–link
自定义网络
容器互联
#查看所有的docker网络命令
[root@iZ8vbcthzqpmrjj3vq8clgZ docker]# docker network --help
Usage: docker network COMMAND
Manage networks
Commands:
connect Connect a container to a network
create Create a network
disconnect Disconnect a container from a network
inspect Display detailed information on one or more networks
ls List networks
prune Remove all unused networks
rm Remove one or more networks
Run 'docker network COMMAND --help' for more information on a command.
#显示所有网卡
[root@iZ8vbcthzqpmrjj3vq8clgZ ~]# docker network ls
NETWORK ID NAME DRIVER SCOPE
6ffe87afd055 bridge bridge local
43d9526e27b3 host host local
1477450a63d8 none null local
网络模式
bridge:桥接 docker(默认,自己创建也是用bridge模式)
none:不配置网络
host:和宿主机共享网络
container:容器网络连通!(用的少,局限很大)
测试
[root@iZ8vbcthzqpmrjj3vq8clgZ ~]# docker network --help
Usage: docker network COMMAND
Manage networks
Commands:
connect Connect a container to a network
create Create a network #创建一个网卡
disconnect Disconnect a container from a network
inspect Display detailed information on one or more networks
ls List networks #显示所有网卡
prune Remove all unused networks
rm Remove one or more #删除网卡
Run 'docker network COMMAND --help' for more information on a command.
#我们发现直接启动命令,默认有-net bridge,而这个就是docker0
docker run -d -P --name tomcat01 tomcat
docker run -d -P --name tomcat01 -net bridge tomcat
#docker0特点:默认的,域名是不能访问的,--link可以打开链接
#我们可以自定义一个网络
#--driver bridge 桥接
#--sumnet 192.168.0.0/16 子网地址
#--gateway 192.168.0.1 网管 相似加了的路由
[root@iZ8vbcthzqpmrjj3vq8clgZ ~]
# docker network create --driver bridge --subnet 192.168.0.0/16 --gateway 192.168.0.1 mynet
00d7975ae0d5287d4e125021a58b46514582d42e8c68ac6c71806c5c6633dc74
[root@iZ8vbcthzqpmrjj3vq8clgZ ~]# docker network ls
NETWORK ID NAME DRIVER SCOPE
6ffe87afd055 bridge bridge local
43d9526e27b3 host host local
00d7975ae0d5 mynet bridge local
1477450a63d8 none null local
#查看自定义的网卡
[root@iZ8vbcthzqpmrjj3vq8clgZ ~]# docker network inspect mynet
[
{
"Name": "mynet",
"Id": "00d7975ae0d5287d4e125021a58b46514582d42e8c68ac6c71806c5c6633dc74",
"Created": "2020-08-31T09:14:14.49000388+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": {}
}
]
#自定义网络创建
docker run -d --name tomcat-net-01 --net mynet tomcat
docker run -d --name tomcat-net-02 --net mynet tomcat
[root@iZ8vbcthzqpmrjj3vq8clgZ ~]# docker inspect mynet
[
{
"Name": "mynet",
"Containers": {
"0d4d932b611fa5c1f9a6a493cd3834973f60bcb8035c123f018f418d2c9cf52c": {
"Name": "tomcat-net-02",
"EndpointID": "45c985015edd845b1e63654634a5be7139c19aba2481906f376ea07765131354",
"MacAddress": "02:42:c0:a8:00:03",
"IPv4Address": "192.168.0.3/16",
"IPv6Address": ""
},
"43e51707f37dc9081312ef03028d7b0104df12118e80c5f31d2c498a3827ec66": {
"Name": "tomcat-net-01",
"EndpointID": "1671d85c0544e6a3ba5d75551589db21f17185e748601cb779121121a8c90f15",
"MacAddress": "02:42:c0:a8:00:02",
"IPv4Address": "192.168.0.2/16",
"IPv6Address": ""
}
},
"Options": {},
"Labels": {}
}
]
docker exec -it tomcat-net-01 ping tomcat-net-02 可以ping通
[root@iZ8vbcthzqpmrjj3vq8clgZ ~]# docker exec -it 43e51707f37d ping 0d4d932b611f
PING 0d4d932b611f (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.138 ms
64 bytes from tomcat-net-02.mynet (192.168.0.3): icmp_seq=2 ttl=64 time=0.113 ms
64 bytes from tomcat-net-02.mynet (192.168.0.3): icmp_seq=3 ttl=64 time=0.103 ms
64 bytes from tomcat-net-02.mynet (192.168.0.3): icmp_seq=4 ttl=64 time=0.118 ms
^C
--- 0d4d932b611f ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3ms
rtt min/avg/max/mdev = 0.103/0.118/0.138/0.012 ms
docker exec -it tomcat-net-01 ping ip 可以ping通
[root@iZ8vbcthzqpmrjj3vq8clgZ ~]# docker exec -it tomcat-net-01 ping 192.168.0.02
PING 192.168.0.02 (192.168.0.2) 56(84) bytes of data.
64 bytes from 192.168.0.2: icmp_seq=1 ttl=64 time=0.055 ms
64 bytes from 192.168.0.2: icmp_seq=2 ttl=64 time=0.061 ms
64 bytes from 192.168.0.2: icmp_seq=3 ttl=64 time=0.055 ms
^C
--- 192.168.0.02 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 0.055/0.057/0.061/0.003 ms
我们自定义的网络docker都已经帮我们维护好了对应的关系,推荐我们平时这样使用网络!
好处:
redis:不同的集群使用不同的网络,可以保证集群是安全和健康的
mysql:不同的集群使用不同的网络,可以保证集群是安全和健康的
网络连通
[root@iZ8vbcthzqpmrjj3vq8clgZ ~]# docker network --help
Usage: docker network COMMAND
Manage networks
Commands:
connect Connect a container to a network #连接一个容器到一个网络
create Create a network
disconnect Disconnect a container from a network
inspect Display detailed information on one or more networks
ls List networks
prune Remove all unused networks
rm Remove one or more networks
[root@iZ8vbcthzqpmrjj3vq8clgZ ~]# docker network connect --help
Usage: docker network connect [OPTIONS] NETWORK CONTAINER
#网络 容器
Connect a container to a network
Options:
--alias strings Add network-scoped alias for the container
--driver-opt strings driver options for the network
--ip string IPv4 address (e.g., 172.30.100.104)
--ip6 string IPv6 address (e.g., 2001:db8::33)
--link list Add link to another container
--link-local-ip strings Add a link-local address for the container
#测试打通 容器和mynet
#命令:docker network connect mynet tomcat01
#连通之后就是将tomcat01 放到 mynet网络下
[root@iZ8vbcthzqpmrjj3vq8clgZ ~]# docker network inspect mynet
[
{
"Name": "mynet",
"Containers": {
"0d4d932b611fa5c1f9a6a493cd3834973f60bcb8035c123f018f418d2c9cf52c": {
"Name": "tomcat-net-02",
"EndpointID": "45c985015edd845b1e63654634a5be7139c19aba2481906f376ea07765131354",
"MacAddress": "02:42:c0:a8:00:03",
"IPv4Address": "192.168.0.3/16",
"IPv6Address": ""
},
"180499cb69d9b0908b607d522755e92b171761a02f907c787df2a086bda0977f": {
"Name": "tomcat01",
"EndpointID": "d7fe7d134e44e50697260ae4c101f69f3a03368028afe4deb00bc7b7f922b29d",
"MacAddress": "02:42:c0:a8:00:04",
"IPv4Address": "192.168.0.4/16",
"IPv6Address": ""
},
"43e51707f37dc9081312ef03028d7b0104df12118e80c5f31d2c498a3827ec66": {
"Name": "tomcat-net-01",
"EndpointID": "1671d85c0544e6a3ba5d75551589db21f17185e748601cb779121121a8c90f15",
"MacAddress": "02:42:c0:a8:00:02",
"IPv4Address": "192.168.0.2/16",
"IPv6Address": ""
}
},
"Options": {},
"Labels": {}
}
]
#再次可以发现能ping通
[root@iZ8vbcthzqpmrjj3vq8clgZ ~]# docker exec -it tomcat01 ping tomcat-net-01
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.144 ms
64 bytes from tomcat-net-01.mynet (192.168.0.2): icmp_seq=2 ttl=64 time=0.094 ms
64 bytes from tomcat-net-01.mynet (192.168.0.2): icmp_seq=3 ttl=64 time=0.113 ms
^C
--- tomcat-net-01 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2ms
rtt min/avg/max/mdev = 0.094/0.117/0.144/0.020 ms
#一个容器两个IP
#好比阿里云 公网 私网
结论:假设要跨网络操作别人的,就需要使用 docker network connect 连通!
实战 部署redis集群
#创建网卡
docker network create redis --subnet 172.38.0.0/16
for port in $(seq 1 6); \
do \
mkdir -p /home/docker/redis/node-${port}/conf #创建redis的配置文件
touch /home/docker/redis/node-${port}/conf/redis.conf
cat << EOF >/home/docker/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} #连接具体的IP
cluster-announce-port 6379
cluster-announce-bus-port 16379
appendonly yes
EOF
done
#启动
docker run -p 6371:6379 -p 16371:16379 --name redis-1 \
-v /home/docker/redis/node-1/data:/data \
-v /home/docker/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 exec -it redis-1 /bin/sh
#连接 搭建集群
redis-cli --cluster create 172.38.0.11:6379 172.38.0.12:6379 172.38.0.13:6379 172.38.0.14:6379 172.38.0.15:6379 172.38.0.16:6379 --cluster-replicas 1
/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: 46dc0223b5cbe751ec223c1d602ad9a6d00538b2 172.38.0.11:6379
slots:[0-5460] (5461 slots) master
M: 6df6355f258de190be1e325166a6278da565030d 172.38.0.12:6379
slots:[5461-10922] (5462 slots) master
M: caed472f5e138b6470726bcce2cd3e08aae01b97 172.38.0.13:6379
slots:[10923-16383] (5461 slots) master
S: 2774d3653f1dfa251b829fb6c48255150be707c0 172.38.0.14:6379
replicates caed472f5e138b6470726bcce2cd3e08aae01b97
S: b184c41a8e54bc5ce0420294d0184c79a08abb51 172.38.0.15:6379
replicates 46dc0223b5cbe751ec223c1d602ad9a6d00538b2
S: c295e467528b28549d4100c7cf8f94ce14ae99a4 172.38.0.16:6379
replicates 6df6355f258de190be1e325166a6278da565030d
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: 46dc0223b5cbe751ec223c1d602ad9a6d00538b2 172.38.0.11:6379
slots:[0-5460] (5461 slots) master
1 additional replica(s)
M: caed472f5e138b6470726bcce2cd3e08aae01b97 172.38.0.13:6379
slots:[10923-16383] (5461 slots) master
1 additional replica(s)
S: c295e467528b28549d4100c7cf8f94ce14ae99a4 172.38.0.16:6379
slots: (0 slots) slave
replicates 6df6355f258de190be1e325166a6278da565030d
M: 6df6355f258de190be1e325166a6278da565030d 172.38.0.12:6379
slots:[5461-10922] (5462 slots) master
1 additional replica(s)
S: 2774d3653f1dfa251b829fb6c48255150be707c0 172.38.0.14:6379
slots: (0 slots) slave
replicates caed472f5e138b6470726bcce2cd3e08aae01b97
S: b184c41a8e54bc5ce0420294d0184c79a08abb51 172.38.0.15:6379
slots: (0 slots) slave
replicates 46dc0223b5cbe751ec223c1d602ad9a6d00538b2
[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:210
cluster_stats_messages_pong_sent:220
cluster_stats_messages_sent:430
cluster_stats_messages_ping_received:215
cluster_stats_messages_pong_received:210
cluster_stats_messages_meet_received:5
cluster_stats_messages_received:430
127.0.0.1:6379># cluster nodes
caed472f5e138b6470726bcce2cd3e08aae01b97 172.38.0.13:6379@16379 master - 0 1598842464426 3 connected 10923-16383
c295e467528b28549d4100c7cf8f94ce14ae99a4 172.38.0.16:6379@16379 slave 6df6355f258de190be1e325166a6278da565030d 0 1598842462522 6 connected
6df6355f258de190be1e325166a6278da565030d 172.38.0.12:6379@16379 master - 0 1598842463525 2 connected 5461-10922
46dc0223b5cbe751ec223c1d602ad9a6d00538b2 172.38.0.11:6379@16379 myself,master - 0 1598842464000 1 connected 0-5460
2774d3653f1dfa251b829fb6c48255150be707c0 172.38.0.14:6379@16379 slave caed472f5e138b6470726bcce2cd3e08aae01b97 0 1598842463424 4 connected
b184c41a8e54bc5ce0420294d0184c79a08abb51 172.38.0.15:6379@16379 slave 46dc0223b5cbe751ec223c1d602ad9a6d00538b2 0 1598842462924 5 connected
127.0.0.1:6379> set a he
-> Redirected to slot [15495] located at 172.38.0.13:6379
OK
[root@iZ8vbcthzqpmrjj3vq8clgZ ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
5fdee38437a6 redis:5.0.9-alpine3.11 "docker-entrypoint.s…" 10 minutes ago Up 10 minutes 0.0.0.0:6376->6379/tcp, 0.0.0.0:16376->16379/tcp redis-6
582d15a58052 redis:5.0.9-alpine3.11 "docker-entrypoint.s…" 11 minutes ago Up 11 minutes 0.0.0.0:6375->6379/tcp, 0.0.0.0:16375->16379/tcp redis-5
4f4d758b5462 redis:5.0.9-alpine3.11 "docker-entrypoint.s…" 11 minutes ago Up 11 minutes 0.0.0.0:6374->6379/tcp, 0.0.0.0:16374->16379/tcp redis-4
a23de14023f1 redis:5.0.9-alpine3.11 "docker-entrypoint.s…" 12 minutes ago Up 12 minutes 0.0.0.0:6373->6379/tcp, 0.0.0.0:16373->16379/tcp redis-3
f2b5cacaeb23 redis:5.0.9-alpine3.11 "docker-entrypoint.s…" 12 minutes ago Up 12 minutes 0.0.0.0:6372->6379/tcp, 0.0.0.0:16372->16379/tcp redis-2
de466b930976 redis:5.0.9-alpine3.11 "docker-entrypoint.s…" 21 minutes ago Up 21 minutes 0.0.0.0:6371->6379/tcp, 0.0.0.0:16371->16379/tcp redis-1
[root@iZ8vbcthzqpmrjj3vq8clgZ ~]# docker stop redis-3
redis-3
127.0.0.1:6379> get a
-> Redirected to slot [15495] located at 172.38.0.14:6379
"he"
172.38.0.14:6379> cluster nodes
c295e467528b28549d4100c7cf8f94ce14ae99a4 172.38.0.16:6379@16379 slave 6df6355f258de190be1e325166a6278da565030d 0 1598842903580 2 connected
6df6355f258de190be1e325166a6278da565030d 172.38.0.12:6379@16379 master - 0 1598842904182 2 connected 5461-10922
caed472f5e138b6470726bcce2cd3e08aae01b97 172.38.0.13:6379@16379 master,fail - 1598842735958 1598842735000 3 connected
46dc0223b5cbe751ec223c1d602ad9a6d00538b2 172.38.0.11:6379@16379 master - 0 1598842905185 1 connected 0-5460
2774d3653f1dfa251b829fb6c48255150be707c0 172.38.0.14:6379@16379 myself,master - 0 1598842904000 7 connected 10923-16383
b184c41a8e54bc5ce0420294d0184c79a08abb51 172.38.0.15:6379@16379 slave 46dc0223b5cbe751ec223c1d602ad9a6d00538b2 0 1598842904000 5 connected
172.38.0.14:6379>
springboot微服务打包成docker镜像
1、构架springboot项目
2、打包应用
3、编写dockerfile
4、构建镜像
5、发布运行
FROM java:8
COPY *.jar /app.jar
CMD ["--server.port=8080"]
EXPOSE 8080
ENTRYPOINT ["java","-jar","/app.jar"]
上传dockerfile和jar包
#生成镜像
[root@iZ8vbcthzqpmrjj3vq8clgZ idea]# docker build -t ideatest .
Sending build context to Docker daemon 16.52MB
Step 1/5 : FROM java:8
8: Pulling from library/java
5040bd298390: Pull complete
fce5728aad85: Pull complete
76610ec20bf5: Pull complete
60170fec2151: Pull complete
e98f73de8f0d: Pull complete
11f7af24ed9c: Pull complete
49e2d6393f32: Pull complete
bb9cdec9c7f3: Pull complete
Digest: sha256:c1ff613e8ba25833d2e1940da0940c3824f03f802c449f3d1815a66b7f8c0e9d
Status: Downloaded newer image for java:8
---> d23bdf5b1b1b
Step 2/5 : COPY *.jar /app.jar
---> 4126b6fc5a8e
Step 3/5 : CMD ["--server.port=8080"]
---> Running in a3d0a275c097
Removing intermediate container a3d0a275c097
---> 5ebc420cf852
Step 4/5 : EXPOSE 8080
---> Running in 1be24402cdb6
Removing intermediate container 1be24402cdb6
---> ae67dddf7fad
Step 5/5 : ENTRYPOINT ["java","-jar","/app.jar"]
---> Running in f646f7199914
Removing intermediate container f646f7199914
---> 1f2e67661f7d
Successfully built 1f2e67661f7d
Successfully tagged ideatest:latest
#运行镜像
docker run -d -P --name springBoot-web ideatest
[root@iZ8vbcthzqpmrjj3vq8clgZ idea]# docker run -d -P --name idea666 ideatest
fa0c07d9a432e0dbaea1539b223908b3c5748567be8ab75d0a64a2a7ae7609dd
[root@iZ8vbcthzqpmrjj3vq8clgZ idea]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
fa0c07d9a432 ideatest "java -jar /app.jar …" 4 seconds ago Up 3 seconds 0.0.0.0:32768->8080/tcp idea666
#测试
curl localhost:端口号
#测试
curl localhost:端口号/地址
[root@iZ8vbcthzqpmrjj3vq8clgZ idea]# curl localhost:32768
{"timestamp":"2020-08-31T03:42:49.141+00:00","status":404,"error":"Not Found","message":"","path":"/"}[root@iZ8vbcthzqpmrjj3vq8clgZ idea]#
[root@iZ8vbcthzqpmrjj3vq8clgZ idea]# curl localhost:32768/hello
你好![root@iZ8vbcthzqpmrjj3vq8clgZ idea]#
Docker Compose
简介:
Docker
DockerFile build run 手动操作 单个容器!
微服务。100个服务!依赖关系。
Docker Compost来轻松高效的管理容器。定义运行多个容器!
官方介绍
Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file to configure your application’s services. Then, with a single command, you create and start all the services from your configuration. To learn more about all the features of Compose, see the list of features.
Compose works in all environments: production, staging, development, testing, as well as CI workflows. You can learn more about each case in Common Use Cases.
Using Compose is basically a three-step process:
- Define your app’s environment with a
Dockerfile
so it can be reproduced anywhere. - Define the services that make up your app in
docker-compose.yml
so they can be run together in an isolated environment. - Run
docker-compose up
and Compose starts and runs your entire app.
翻译:
Compose是用于定义和运行多容器Docker应用程序的工具。通过Compose,您可以使用YAML文件来配置应用程序的服务。然后,使用一个命令,就可以从配置中创建并启动所有服务。要了解有关Compose的所有功能的更多信息,请参阅功能列表。
Compose可在所有环境中工作:生产,登台,开发,测试以及CI工作流。您可以在“ 常见用例”中了解有关每种情况的更多信息。
使用Compose基本上是一个三步过程:
- 使用定义您的应用环境,
Dockerfile
以便可以在任何地方运行。 - 定义组成应用程序的服务,
docker-compose.yml
以便它们可以在隔离的环境中一起运行。 - Run
docker-compose up
and Compose启动并运行您的整个应用程序。
理解:
Compose是Docker官方的开源项目。需要安装!
Dockerfile
可以让程序在任何地方运行。web服务。redis、mysql、Nginx…多个容器。
Compose
version: '2.0'
services:
web:
build: .
ports:
- "5000:5000"
volumes:
- .:/code
- logvolume01:/var/log
links:
- redis
redis:
image: redis
volumes:
logvolume01: {}
docker-compose up
可以同时启动100个服务。
Compose:重要概念。
- 服务services,容器。应用。(redis、mysql、Nginx…)
- 最终生成一个项目 project。一组关联的容器。
安装
1、下载
# 官方
sudo curl -L "https://github.com/docker/compose/releases/download/1.26.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
# 这个会快一点
curl -L https://get.daocloud.io/docker/compose/releases/download/1.25.5/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose
[root@iZ8vbcthzqpmrjj3vq8clgZ idea]# curl -L https://get.daocloud.io/docker/compose/releases/download/1.25.5/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 423 100 423 0 0 631 0 --:--:-- --:--:-- --:--:-- 631
100 16.7M 100 16.7M 0 0 9126k 0 0:00:01 0:00:01 --:--:-- 22.2M
[root@iZ8vbcthzqpmrjj3vq8clgZ idea]# cd /usr/local/bin
[root@iZ8vbcthzqpmrjj3vq8clgZ bin]# ls
chardetect cloud-init docker-compose easy_install-3.6 jemalloc-config jeprof jsonpatch jsonschema luajit mcrypt
cloud-id cloud-init-per easy_install easy_install-3.8 jemalloc.sh jsondiff jsonpointer libmcrypt-config luajit-2.0.4 mdecrypt
授权
sudo chmod +x /usr/local/bin/docker-compose
[root@iZ8vbcthzqpmrjj3vq8clgZ bin]# docker-compose version
docker-compose version 1.25.5, build 8a1c60f6
docker-py version: 4.1.0
CPython version: 3.7.5
OpenSSL version: OpenSSL 1.1.0l 10 Sep 2019
体验
地址:https://docs.docker.com/compose/gettingstarted/
Python应用 。 计数器 redis。
官方的步骤:
1、应用app.py
2、Dockerfile 应用打包镜像
3、Docker-compose yaml 文件(定义整个服务,需要的环境web redis )完整的上线服务
4、启动compose项目(docker-compose up)
流程:
1、创建网络。
2、执行Docker-compose yaml
3、启动服务
第一步:
mkdir composetest
cd composetest
第二步:
vim app.py
import time
import redis
from flask import Flask
app = Flask(__name__)
cache = redis.Redis(host='redis', port=6379)
def get_hit_count():
retries = 5
while True:
try:
return cache.incr('hits')
except redis.exceptions.ConnectionError as exc:
if retries == 0:
raise exc
retries -= 1
time.sleep(0.5)
@app.route('/')
def hello():
count = get_hit_count()
return 'Hello World! I have been seen {} times.\n'.format(count)
if __name__ == "__main__":
app.run(host="0.0.0.0", debug=True)
第三步:
vim requirements.txt
flask
redis
第四步:
vim Dockerfile
FROM python:3.6-alpine
ADD . /code
WORKDIR /code
RUN pip install -r requirements.txt
CMD ["python","app.py"]
第五步:
vim docker-compose.yml
version: '3.8'
services:
web:
build: .
ports:
- "5000:5000"
volumes:
- .:/code
redis:
image: "redis:alpine"
docker-compose up
#查看服务
[root@iZ8vbcthzqpmrjj3vq8clgZ composetest]# docker service ls
Error response from daemon: This node is not a swarm manager. Use "docker swarm init" or "docker swarm join" to connect this node to swarm and try again.
默认服务名 文件名_服务名 _num
多个服务器。集群 。A B 。_num 副本数量
网络规则:
项目中的内容都在同一个网络下面,可以通过域名访问。
docker-compose:
以前都是单个 docker run 启动容器。
docker-compose 。通过docker-compose 编写yaml配置文件、可以通过compose一键启动,停止 。
yaml配置规则
地址:https://docs.docker.com/compose/compose-file/
#3层
#第一层
version: '' # 版本
#第二层
services: # 服务
#第一个服务
web
#服务配置
images
build
...
#第二个服务
redis
...
#第三层
其他配置: 网络/卷、全局规则
volumes:
network:
config:
开源项目
博客
https://docs.docker.com/compose/wordpress/
之前:下载程序。安装数据库。配置…
compose 应用 。-》一键启动
1、下载项目(docker-compose.yml)
version: '3.3'
services:
db:
image: mysql:5.7
volumes:
- db_data:/var/lib/mysql
restart: always
environment:
MYSQL_ROOT_PASSWORD: somewordpress
MYSQL_DATABASE: wordpress
MYSQL_USER: wordpress
MYSQL_PASSWORD: wordpress
wordpress:
depends_on:
- db
image: wordpress:latest
ports:
- "8000:80"
restart: always
environment:
WORDPRESS_DB_HOST: db:3306
WORDPRESS_DB_USER: wordpress
WORDPRESS_DB_PASSWORD: wordpress
WORDPRESS_DB_NAME: wordpress
volumes:
db_data: {}
2、如果需要文件 (Dockerfile)
3、文件准备齐全直接启动 (docker-compose up)
前台启动:
docker-compose up
后台启动:
docker-compose up -d
[root@iZ8vbcthzqpmrjj3vq8clgZ my_wordpress]# docker-compose up -d
Starting my_wordpress_db_1 ... done
Starting my_wordpress_wordpress_1 ... done
[root@iZ8vbcthzqpmrjj3vq8clgZ my_wordpress]#
停止:
[root@iZ8vbcthzqpmrjj3vq8clgZ my_wordpress]# docker-compose down
Stopping my_wordpress_wordpress_1 ... done
Stopping my_wordpress_db_1 ... done
实战
1、编写项目微服务
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author 小鸵鸟
* @date 2020/9/1 10:29
*/
@RestController
public class HelloController {
@Autowired
StringRedisTemplate redisTemplate;
@RequestMapping("/hello")
public String hello(){
Long views = redisTemplate.opsForValue().increment("views");
return "hello word views"+views;
}
}
2、构建dockerfile镜像
FROM java:8
COPY *.jar /app.jar
CMD ["--server.post:8080"]
EXPOSE 8000 #外部访问接口
ENTRYPOINT ["java","-jar","/app.jar"]
3、docker-compose.yml 编排项目
version: '3.8'
services:
hqyapp:
build: .
image: hqyapp
depends_on:
- redis
ports:
- "8000:8080"
redis:
image: "library/redis:alpine"
4、放到服务器 docker-compose up
[root@iZ8vbcthzqpmrjj3vq8clgZ hqyapp]# docker-compose up
Creating network "hqyapp_default" with the default driver
Pulling redis (library/redis:alpine)...
alpine: Pulling from library/redis
df20fa9351a1: Pull complete
9b8c029ceab5: Pull complete
e983a1eb737a: Pull complete
660ad543c5fc: Pull complete
823cbe4f5025: Pull complete
e3dd0c30e1c8: Pull complete
Digest: sha256:6972ee00fd35854dd2925904e23cb047faa004df27c62cba842248c7db6bd99d
Status: Downloaded newer image for redis:alpine
Building hqyapp
Step 1/5 : FROM java:8
8: Pulling from library/java
5040bd298390: Pull complete
fce5728aad85: Pull complete
76610ec20bf5: Pull complete
60170fec2151: Pull complete
e98f73de8f0d: Pull complete
11f7af24ed9c: Pull complete
49e2d6393f32: Pull complete
bb9cdec9c7f3: Pull complete
Digest: sha256:c1ff613e8ba25833d2e1940da0940c3824f03f802c449f3d1815a66b7f8c0e9d
Status: Downloaded newer image for java:8
---> d23bdf5b1b1b
Step 2/5 : COPY *.jar /app.jar
---> 3baf71dd0aff
Step 3/5 : CMD ["--server.post:8080"]
---> Running in 6742cb03e27d
Removing intermediate container 6742cb03e27d
---> 459cd9c2c7be
Step 4/5 : EXPOSE 8000
---> Running in 9fc7f07335e2
Removing intermediate container 9fc7f07335e2
---> 17cff829d0d7
Step 5/5 : ENTRYPOINT ["java","-jar","/app.jar"]
---> Running in 66804d8335c3
Removing intermediate container 66804d8335c3
---> 3c84d02b58ce
Successfully built 3c84d02b58ce
Successfully tagged hqyapp:latest
WARNING: Image for service hqyapp was built because it did not already exist. To rebuild this image you must use `docker-compose build` or `docker-compose up --build`.
Creating hqyapp_redis_1 ... done
Creating hqyapp_hqyapp_1 ... done
Attaching to hqyapp_redis_1, hqyapp_hqyapp_1
redis_1 | 1:C 01 Sep 2020 03:03:14.773 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
redis_1 | 1:C 01 Sep 2020 03:03:14.773 # Redis version=6.0.6, bits=64, commit=00000000, modified=0, pid=1, just started
redis_1 | 1:C 01 Sep 2020 03:03:14.773 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
redis_1 | 1:M 01 Sep 2020 03:03:14.774 * Running mode=standalone, port=6379.
redis_1 | 1:M 01 Sep 2020 03:03:14.774 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
redis_1 | 1:M 01 Sep 2020 03:03:14.774 # Server initialized
redis_1 | 1:M 01 Sep 2020 03:03:14.774 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
redis_1 | 1:M 01 Sep 2020 03:03:14.774 # WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled.
redis_1 | 1:M 01 Sep 2020 03:03:14.775 * Ready to accept connections
hqyapp_1 |
hqyapp_1 | . ____ _ __ _ _
hqyapp_1 | /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
hqyapp_1 | ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
hqyapp_1 | \\/ ___)| |_)| | | | | || (_| | ) ) ) )
hqyapp_1 | ' |____| .__|_| |_|_| |_\__, | / / / /
hqyapp_1 | =========|_|==============|___/=/_/_/_/
hqyapp_1 | :: Spring Boot :: (v2.3.3.RELEASE)
hqyapp_1 |
hqyapp_1 | 2020-09-01 03:03:16.953 INFO 1 --- [ main] com.he.DockercomposeApplication : Starting DockercomposeApplication v0.0.1-SNAPSHOT on 0dd0009a99b9 with PID 1 (/app.jar started by root in /)
hqyapp_1 | 2020-09-01 03:03:16.959 INFO 1 --- [ main] com.he.DockercomposeApplication : No active profile set, falling back to default profiles: default
hqyapp_1 | 2020-09-01 03:03:18.234 INFO 1 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
hqyapp_1 | 2020-09-01 03:03:18.237 INFO 1 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data Redis repositories in DEFAULT mode.
hqyapp_1 | 2020-09-01 03:03:18.280 INFO 1 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 23ms. Found 0 Redis repository interfaces.
hqyapp_1 | 2020-09-01 03:03:19.109 INFO 1 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
hqyapp_1 | 2020-09-01 03:03:19.133 INFO 1 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
hqyapp_1 | 2020-09-01 03:03:19.133 INFO 1 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.37]
hqyapp_1 | 2020-09-01 03:03:19.298 INFO 1 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
hqyapp_1 | 2020-09-01 03:03:19.298 INFO 1 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2171 ms
hqyapp_1 | 2020-09-01 03:03:20.236 INFO 1 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
hqyapp_1 | 2020-09-01 03:03:20.761 INFO 1 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
hqyapp_1 | 2020-09-01 03:03:20.781 INFO 1 --- [ main] com.he.DockercomposeApplication : Started DockercomposeApplication in 4.697 seconds (JVM running for 5.391)
假设项目要重新部署打包
docker-compose up --build #重新构建
DockerSwarm
1、购买4台服务器
2、安装docker
工作模式
Docker Engine 1.12 introduces swarm mode that enables you to create a cluster of one or more Docker Engines called a swarm. A swarm consists of one or more nodes: physical or virtual machines running Docker Engine 1.12 or later in swarm mode.
There are two types of nodes: managers and workers.
If you haven’t already, read through the swarm mode overview and key concepts.
[root@iZ8vbcthzqpmrjj3vq8clgZ hqyapp]# docker swarm --help
Usage: docker swarm COMMAND
Manage Swarm
Commands:
ca Display and rotate the root CA
init Initialize a swarm #搭建一个集群
join Join a swarm as a node and/or manager #加入一个集群
join-token Manage join tokens #创建token
leave Leave the swarm #离开集群
unlock Unlock swarm #解锁
unlock-key Manage the unlock key
update Update the swarm #更新集群
Run 'docker swarm COMMAND --help' for more information on a command.
[root@iZ8vbcthzqpmrjj3vq8clgZ hqyapp]# docker swarm init --help
Usage: docker swarm init [OPTIONS]
Initialize a swarm
Options: #地址
--advertise-addr string Advertised address (format: <ip|interface>[:port])
地址 :
-
私网
-
公网
#IP地址
docker swarm init --advertise-addr 172.26.185.175
初始化一个节点 docker swarm init
加入一个节点 docker swarm join
#获取令牌
docker swarm join-token manager
docker swarm join-token worker
docker swarm join-token manager
docker node ls
Raft协议
双主双从 : 假设一个节点挂了!其他节点是否可以用?
Raft协议 : 保证大多数节点存活才能用。只要大于1 。集群至少大于3台!
测试:
1、将docker-1机器停止,双主,另外一个主节点也不能用了!
2、 docker swarm leave
离开一个集群
3、work就是工作的。管理节点的操作!3台机器设置为了管理节点
Raft协议 :保证大多数节点存活,才可以使用,高可用!
docker service --help
[root@iZ8vbcthzqpmrjj3vq8clgZ hqyapp]# docker service --help
Usage: docker service COMMAND
Manage services
Commands:
create Create a new service # 创建
inspect Display detailed information on one or more services # 查看
logs Fetch the logs of a service or task # 日志
ls List services
ps List the tasks of one or more services
rm Remove one or more services
rollback Revert changes to a service's configuration # 回滚一个节点
scale Scale one or multiple replicated services # 动态的扩缩容
update Update a service # 更新一个服务
Run 'docker service COMMAND --help' for more information on a command.
#
docker run #启动一个容器,不具有扩缩容
#
docker service # 启动一个服务,具有扩缩容,滚动跟新!
#创建一个服务
docker service create -p 8888:80 --name my-nginx nginx
服务名
# docker service ps my-nginx
#查看服务
docker service ls
查看服务
现在只创建了一个副本
访问从100到10000需要创建多个副本
动态扩缩容
副本个数 服务名
docker service update --relipcas 3 my-nginx
docker service scale my-nginx=5
服务,集群中任意的节点都可以访问。服务可以有多个副本,动态扩缩容实现高可用!
移除一个服务
docker service rm my-ngnix
更多推荐
所有评论(0)