Docker学习

Docker概述

Docker为什么出现

环境配置是十分的麻烦,每一个机器都要部署环境

发布一个项目,jar,war(Redis,Mysql,jdk,ES),项目能不能带上环境安装打包

Docker的思想来自于集装箱

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

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

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

文档地址:https://docs.docker.com/超级详细

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

Docker能干吗

虚拟机技术缺点

  • 资源占用十分多
  • 冗余步骤多
  • 启动很慢

容器化技术:不是模拟的一个完整的操作系统

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

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

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

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

DevOps(开发运维)

更快速的交付和部署

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

更便捷的升级和扩缩容

更简单的系统运维

更高效的计算资源利用

Docker安装

Docker的组成

镜像(image):

docker镜像就好比一个模板,可以通过这个模板来创建容器服务,tomcat->run->tomcat容器1(提供服务器),通过镜像可以创建多个容器

容器(container):

利用容器技术,独立运行一个或者一个组应用,通过镜像来创建的

启动,停止,删除,基本命令

仓库(repository):

仓库就是存放镜像的地方

仓库分为公有仓库和私有仓库

Docker Hub(默认是国外的)

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

安装Docker

环境准备

  • 需要一点点的Linux基础
  • CentOS 7
  • 我们使用Xshell连接远程服务器进行操作

环境查看

#系统内核是3.10以上的
[root@ming ming]# uname -r
4.18.0-193.14.2.el8_2.x86_64
[root@ming ming]# cat /etc/os-release
NAME="CentOS Linux"
VERSION="8 (Core)"
ID="centos"
ID_LIKE="rhel fedora"
VERSION_ID="8"
PLATFORM_ID="platform:el8"
PRETTY_NAME="CentOS Linux 8 (Core)"
ANSI_COLOR="0;31"
CPE_NAME="cpe:/o:centos:centos:8"
HOME_URL="https://www.centos.org/"
BUG_REPORT_URL="https://bugs.centos.org/"

CENTOS_MANTISBT_PROJECT="CentOS-8"
CENTOS_MANTISBT_PROJECT_VERSION="8"
REDHAT_SUPPORT_PRODUCT="centos"
REDHAT_SUPPORT_PRODUCT_VERSION="8"

安装

帮助文档:https://docs.docker.com/engine/install/centos/

#卸载旧版本
$ sudo yum remove docker \
                  docker-client \
                  docker-client-latest \
                  docker-common \
                  docker-latest \
                  docker-latest-logrotate \
                  docker-logrotate \
                  docker-engine
 
 yum install gcc
 yum install gcc-c++
 yum install zlib*
# 需要的安装包
$ sudo yum install -y yum-utils

#设置镜像的仓库
$ sudo yum-config-manager \
    --add-repo \
    https://download.docker.com/linux/centos/docker-ce.repo     #默认的是国外的,很慢
    
    
    #使用阿里云http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
    
# 更新yum软件包索引
 yum makecache fast
#安装最新版本
$ sudo yum install docker-ce docker-ce-cli containerd.io
containerd.io最新版本下载 
下载地址:https://mirrors.aliyun.com/docker-ce/linux/centos/8/x86_64/stable/Packages/

yum install containerd.io-1.3.7-3.1.el8.x86_64.rpm 

yum install docker-ce   #默认安装最新版本
yum install docker-ce
# 启动docker
systemctl start docker

#使用docker version查看是否安装成功
docker  version



#测试
docker  run  hello-world
第一次本地没有,从远程拉取并运行

# 查看镜像
docker imagers
[root@ming ming]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
hello-world         latest              bf756fb1ae65        9 months ago        13.3kB

卸载
#卸载依赖
$ sudo yum remove docker-ce docker-ce-cli containerd.io
#删除资源
$ sudo rm -rf /var/lib/docker

阿里云镜像加速

登录阿里云->找到容器镜像服务,

镜像加速器,镜像加速地址

有操作文档,修改即可

#配置使用
sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF'
{
	"registry-mirrors":["https://xxx"]
}
EOF
sudo systemctl daemon-reload
sudo systemctl restart docker

腾讯镜像加速:https://mirror.ccs.tencentyun.com

RUN的流程和Docker的原理

开始
Docker会在本机寻找镜像  ->判断本机是否有这个镜像,有则使用这个镜像运行,否则去DockerHub上下载
DockerHub是否可以找到  找不到,返回错误,找到则下载镜像到本地,运行

底层原理

Docker是怎么工作的

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

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

Docker为什么比VM快

  • docker有着比虚拟机更少的抽象层
  • docker利用的是宿主机的内核,vm需要是Guest OS
  • 新建一个容器的时候,dcker不需要像虚拟机一样重新加载一个操作系统内核,避免引导操作,虚拟机是加载Guest OS,分钟级别的,而docker是利用宿主机的操作系统,省略了这个过程,秒级

Docker的常用命令

帮助命令

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

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

镜像命令

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

#可选项
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 numeric IDs

docker search   搜索镜像
[root@ming ming]# docker search mysql
NAME                              DESCRIPTION                                     STARS               OFFICIAL            AUTOMATED
mysql                             MySQL is a widely used, open-source relation…   10040               [OK]                
mariadb                           MariaDB is a community-developed fork of MyS…   3678                [OK]                
mysql/mysql-server                Optimized MySQL Server Docker images. Create…   735     
docker pull   下载镜像

#默认下载最新的         可以加版本号  docker pull[:tag]
[root@ming ming]# docker pull mysql
Using default tag: latest
latest: Pulling from library/mysql
d121f8d1c412: Pull complete    #分层下载,docker image 的核心  联合文件系统
f3cebc0b4691: Pull complete 
1862755a0b37: Pull complete 
489b44f3dbb4: Pull complete 
690874f836db: Pull complete 
baa8be383ffb: Pull complete 
55356608b4ac: Pull complete 
dd35ceccb6eb: Pull complete 
429b35712b19: Pull complete 
162d8291095c: Pull complete 
5e500ef7181b: Pull complete 
af7528e958b6: Pull complete 
Digest: sha256:e1bfe11693ed2052cb3b4e5fa356c65381129e87e38551c6cd6ec532ebe0e808      #签名
Status: Downloaded newer image for mysql:latest
docker.io/library/mysql:latest   #真实地址

#等价
docker pull mysql
docker pull docker.io/library/mysql:latest

#指定版本下载
[root@ming ming]# docker pull mysql:5.7
5.7: Pulling from library/mysql
d121f8d1c412: Already exists 
f3cebc0b4691: Already exists 
1862755a0b37: Already exists 
489b44f3dbb4: Already exists 
690874f836db: Already exists 
baa8be383ffb: Already exists 
55356608b4ac: Already exists 
277d8f888368: Pull complete 
21f2da6feb67: Pull complete 
2c98f818bcb9: Pull complete 
031b0a770162: Pull complete 
Digest: sha256:14fd47ec8724954b63d1a236d2299b8da25c9bbb8eacc739bb88038d82da4919
Status: Downloaded newer image for mysql:5.7
docker.io/library/mysql:5.7

docker rmi   删除镜像
docker rmi  -f    删除指定的镜像
[root@ming ming]# docker rmi ef08065b0a30 
Untagged: mysql:5.7
Untagged: mysql@sha256:14fd47ec8724954b63d1a236d2299b8da25c9bbb8eacc739bb88038d82da4919
Deleted: sha256:ef08065b0a302111b56966aa92c89fa0bacdfc537741cbca88a15b10f14332ca
Deleted: sha256:c8c81ac92392c394197759ca3d50f5f843d85ac1550d8c0bb2b21adc7334100d
Deleted: sha256:2dc86a1b9b92e7c946c684bd349e448d7c4fbb3236686e1a48ddfe5adb86a425
Deleted: sha256:97b541df82456d38e987b630870fcd4e39f05f016717652466b3466841f4162e
Deleted: sha256:aded9a11fc54761c770a9075cfc2d0bb72c72b59171a56cfa4322ab2b2d416e7

docker rmi  -f $(docker images -aq)  #全部删除
[root@ming ming]# docker rmi -f $(docker images -aq)
Untagged: mysql:latest
Untagged: mysql@sha256:e1bfe11693ed2052cb3b4e5fa356c65381129e87e38551c6cd6ec532ebe0e808
Deleted: sha256:e1d7dc9731daa2c79858307d65ef35f543daf97457b9c11b681f78bb86f7a158
Deleted: sha256:303dd82484b7080d07af8ab7f383755d8b4d723a2ade8c2e3a516ae59fbc1d63
Deleted: sha256:6346e1a264e283de286e399bc798b8e6a910176180aa1ef1acc54dbace18111a
Deleted: sha256:6c7a3d83131ddf3414e34e14826cbfb8f01a6d6486cd41d9a7a2bcc84350b4f0
Deleted: sha256:79b91792bcadd6668ab861a83623dedcc38574c5f033d2f8336671588a1c4de0
Deleted: sha256:00bdff03938c98e1fee710e8c447a1c30e7365859dd28e2a166792d7cd343fa9
Deleted: sha256:3fc742b087b51753835895403bd70b649bf2e4e32c5eb5f2f15c2b7d22409964
Deleted: sha256:00d53c8dcb5c8fd12fbfd2b3b25afcbc3a044e73f1fd395af231f86827238fcf
Deleted: sha256:007d9a78de83bec432afb0e4e847072a6943e853456fe21b70488d25c1c96bf4
Deleted: sha256:31fd54b7e8a4e80375cbfd9ead44c37e0ee03d8c4ca7ace27cc1896e9d40e2a2
Deleted: sha256:22d626b2851ecf92af46f616ce1ff0ef0879ef23b68be2fb92be3311f2308763
Deleted: sha256:5da80bf7a61d70d69c153f015cd2a5aa96594f36f3835ef6dbcd4da41da374f2
Deleted: sha256:07cab433985205f29909739f511777a810f4a9aff486355b71308bb654cdc868
Untagged: hello-world:latest
Untagged: hello-world@sha256:4cf9c47f86df71d48364001ede3a4fcd85ae80ce02ebad74156906caff5378bc
Deleted: sha256:bf756fb1ae65adf866bd8c456593cd24beb6a0a061dedf42b26a993176745f6b

容器命令

说明:我们有了镜像才可以创建容器。linux,下载centOS镜像来测试学习

docker pull centos
[root@ming ~]# docker pull centos
Using default tag: latest
latest: Pulling from library/centos
3c72a8ed6814: Pull complete 
Digest: sha256:76d24f3ba3317fa945743bb3746fbaf3a0b752f10b10376960de01da70685fbd
Status: Downloaded newer image for centos:latest
docker.io/library/centos:latest

新建容器并启动

docker run [可选参数] image
# 参数说明
--name="Name"    容器名字      tomcat01    tomcat02   用来区分容器
-d      后台方式运行
-it   使用交互方式运行,进入容器查看内容
-p   指定容器端口    -p 8080:8080
   -p  ip:主机端口:容器端口
  -p  主机端口:容器端口  (常用)
  -p   容器端口
-P   随机指定端口(大P)


#测试 ,启动并进入容器
[root@ming ~]# docker run -it centos /bin/bash
[root@a0cc2266d3ad /]# 
[root@ming ~]# docker run -it centos /bin/bash
[root@a0cc2266d3ad /]# ls   #查看容器内的centos,基础版本,很多命令是不完善的
bin  etc   lib	  lost+found  mnt  proc  run   srv  tmp  var
dev  home  lib64  media       opt  root  sbin  sys  usr
[root@a0cc2266d3ad /]# 

#退出,从容器中退回主机
[root@a0cc2266d3ad /]# exit
exit
[root@ming ~]# 


#列出所有的运行的容器
[root@ming /]# docker ps    当前正在运行的容器
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
[root@ming /]# docker ps -a   #当前正在运行的容器+带出历史运行过的容器
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                     PORTS               NAMES
a0cc2266d3ad        centos              "/bin/bash"         4 minutes ago       Exited (0) 2 minutes ago                       optimistic_dirac
5287fd549b07        bf756fb1ae65        "/hello"            3 hours ago         Exited (0) 3 hours ago                         elated_ganguly
[root@ming /]# 

docker ps 
-n=?   显示最近创建的容器   
-q     只显示容器的编号
退出容器
exit     直接容器停止并退出
ctrl +P +Q  容器不停止退出
删除容器
docker rm  容器id     #删除指定的容器  ,不能删除正在运行的容器,如果要强制删除   rm  -f
docker rm -f $(docker ps -aq)  #删除所有的容器

docker ps -a -q|xargs docker rm  #删除所有的容器

启动和停止容器的操作


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

常用其他命令

后台启动容器
# 命令  docker run -d 镜像名
问题:docker ps   发现centos停止了
#常见的坑,docker 容器使用后台运行,就必须要有一个前台进程,docker发现没有应用,就会自动停止
#nginx,容器启动后,发现自己没有提供服务,就会立刻停止,就是没有程序了


查看日志命令
docker logs -tf --tail 容器,没有日志
#自己编写一段shell脚本
"while true;do echo ming;sleep 1;done"
[root@ming ~]# docker run -d centos /bin/sh -c "while true;do echo ming;sleep 1;done"

[root@ming ~]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
d63f96c8ba57        centos              "/bin/sh -c 'while t…"   59 seconds ago      Up 58 seconds                           eager_northcutt
# 显示日志

-tf    #显示日志
--tail  number  #显示日志的条数

docker logs -tf --tail 10 d63f96c8ba57
查看容器中的进程信息

docker top 容器id


查看镜像的元数据
docker inspect  容器id
[root@ming ~]# docker inspect d63f96c8ba57 
[
    {
        "Id": "d63f96c8ba570086a9b9e51803d34335c8d612a7c29486d500bb7847af19de1a",
        "Created": "2020-10-12T07:52:41.802683817Z",
        "Path": "/bin/sh",
        "Args": [
            "-c",
            "while true;do echo ming;sleep 1;done"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 54058,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2020-10-12T07:52:42.16255385Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:0d120b6ccaa8c5e149176798b3501d4dd1885f961922497cd0abef155c869566",
        "ResolvConfPath": "/var/lib/docker/containers/d63f96c8ba570086a9b9e51803d34335c8d612a7c29486d500bb7847af19de1a/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/d63f96c8ba570086a9b9e51803d34335c8d612a7c29486d500bb7847af19de1a/hostname",
        "HostsPath": "/var/lib/docker/containers/d63f96c8ba570086a9b9e51803d34335c8d612a7c29486d500bb7847af19de1a/hosts",
        "LogPath": "/var/lib/docker/containers/d63f96c8ba570086a9b9e51803d34335c8d612a7c29486d500bb7847af19de1a/d63f96c8ba570086a9b9e51803d34335c8d612a7c29486d500bb7847af19de1a-json.log",
        "Name": "/eager_northcutt",
        "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/6f952f7252c8f65533b691bd848c520df66890c23d1622e3e6a8ff5bcbd87c52-init/diff:/var/lib/docker/overlay2/cce3cbf047e3cd1fde4d1931103098c5514fd23f0f783e0b117a318ecc77a15a/diff",
                "MergedDir": "/var/lib/docker/overlay2/6f952f7252c8f65533b691bd848c520df66890c23d1622e3e6a8ff5bcbd87c52/merged",
                "UpperDir": "/var/lib/docker/overlay2/6f952f7252c8f65533b691bd848c520df66890c23d1622e3e6a8ff5bcbd87c52/diff",
                "WorkDir": "/var/lib/docker/overlay2/6f952f7252c8f65533b691bd848c520df66890c23d1622e3e6a8ff5bcbd87c52/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "d63f96c8ba57",
            "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 ming;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": "a58c7cc66b71a0be5888c98cf1cc3d2d7685b38582e85042f7f2c49729cbaf57",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {},
            "SandboxKey": "/var/run/docker/netns/a58c7cc66b71",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "e2ed873846a13edccc43699bd33c112072a4bd321d632e77fa1650773f6eeeb4",
            "Gateway": "172.17.0.1",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "172.17.0.3",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "MacAddress": "02:42:ac:11:00:03",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "bf8c129390ae2e027c6632ab9f27dd9fe9f26c0c6ae60cd4f13b555542271aa5",
                    "EndpointID": "e2ed873846a13edccc43699bd33c112072a4bd321d632e77fa1650773f6eeeb4",
                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.3",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:11:00:03",
                    "DriverOpts": null
                }
            }
        }
    }
]

进入容器的命令和拷贝命令

# 我们通常容器都是使用后台方式运行的,需要进入容器,修改一些配置
# 命令
docker exec -it 容器id bashshell
[root@ming ~]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
d63f96c8ba57        centos              "/bin/sh -c 'while t…"   18 minutes ago      Up 18 minutes                           eager_northcutt
[root@ming ~]# docker exec -it d63f96c8ba57  /bin/bash
[root@d63f96c8ba57 /]# ls
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
[root@d63f96c8ba57 /]# ps -ef
UID          PID    PPID  C STIME TTY          TIME CMD
root           1       0  0 07:52 ?        00:00:00 /bin/sh -c while true;do echo ming;sleep 1;done
root        1131       0  1 08:11 pts/0    00:00:00 /bin/bash
root        1156       1  0 08:11 ?        00:00:00 /usr/bin/coreutils --coreutils-prog-shebang=sleep /usr/bin/sleep 1
root        1157    1131  0 08:11 pts/0    00:00:00 ps -ef
[root@d63f96c8ba57 /]# 




# 方式二
docker  attach 容器id

正在执行当前的代码。。

#docker exec  进入容器后开启一个新的终端,可以在里面操作(常用)
#docker attach  进入容器正在执行的终端,不会启动新的进程

从容器内拷贝文件到主机上

docker  cp  容器id:容器内路径    目的的主机路径
[root@ming home]# docker cp 5db853166182:/home/ming.java /home
[root@ming home]# ls
ming  ming.java

作业练习

Docker 安装Nginx

# 搜索镜像   search   可以去dockerhub搜索,可以看到帮助文档
# 下载镜像  docker pull
[root@ming home]# docker pull nginx
Using default tag: latest
latest: Pulling from library/nginx
d121f8d1c412: Pull complete 
66a200539fd6: Pull complete 
e9738820db15: Pull complete 
d74ea5811e8a: Pull complete 
ffdacbba6928: Pull complete 
Digest: sha256:fc66cdef5ca33809823182c9c5d72ea86fd2cef7713cf3363e1a0b12a5d77500
Status: Downloaded newer image for nginx:latest
docker.io/library/nginx:latest
[root@ming home]# 


运行测试
# -d  后台运行
# --name   给容器命名
# -p  宿主机端口:容器内部端口     暴露端口
[root@ming home]# docker run -d --name nginx01 -p 3344:80 nginx
994ec81d94554f4181ad5a8abc4a87c1aca5ac21de09a19406b7c98104279192
[root@ming home]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                  NAMES
994ec81d9455        nginx               "/docker-entrypoint.…"   4 seconds ago       Up 3 seconds        0.0.0.0:3344->80/tcp   nginx01
[root@ming home]# 
[root@ming home]# curl localhost:3344
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>
[root@ming home]# 

进入容器
[root@ming ~]# docker exec -it nginx01 /bin/bash

部署Tomcat

#官方使用
docker run -it --rm tomcat:9.0

# 我们之前的启动都是后台,停止了容器之后,容器还是可以查到     一般用来测试用完即删


#下载再启动
docker pull tomcat:9.0
[root@ming ~]# docker pull tomcat:9.0
9.0: Pulling from library/tomcat
Digest: sha256:1bab37d5d97bd8c74a474b2c1a62bbf1f1b4b62f151c8dcc472c7d577eb3479d
Status: Image is up to date for tomcat:9.0
docker.io/library/tomcat:9.0

#启动运行
[root@ming ~]# docker run -d -p 3355:8080 --name tomcat01 tomcat
# 测试访问没问题
[root@ming ~]# docker exec -it tomcat01 /bin/bash
# 发现问题:linux 命令少了,没有webapps  阿里云镜像的原因:默认是最小的镜像,所有不必要的都剔除掉
#保证最小的可运行的环境

解决方法
root@9d20bc68e0d6:/usr/local/tomcat# cp -r webapps.dist/* webapps/
可以访问

有没有一种技术,可以在容器外部提供一个映射路径,达到在容器外部防止项目,自动同步到内部 -v 数据卷

部署ES+kibana

# es  暴露的端口多
# es  十分耗内存
# es 的数据一般需要放到安全目录  挂载
# --net somenetwork  ? 网络配置
--net somenetwork 

$ docker run -d --name elasticsearch -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" elasticsearch:7.9.2


# 启动了   linux就卡住了   docker  stats 查看cpu的状态

# es是十分耗内存的 1.xG   1核2G很卡

#可以考虑停止其他服务

#查看 docker stats  
#测试一下是否成功了

[root@ming ~]# docker ps
CONTAINER ID        IMAGE                 COMMAND                  CREATED             STATUS              PORTS                                            NAMES
3813b3690981        elasticsearch:7.9.2   "/tini -- /usr/local…"   7 minutes ago       Up 7 minutes        0.0.0.0:9200->9200/tcp, 0.0.0.0:9300->9300/tcp   elasticsearch
[root@ming ~]# curl localhost:9200
{
  "name" : "3813b3690981",
  "cluster_name" : "docker-cluster",
  "cluster_uuid" : "ShTdbaGnSI6B7zT5V6yIGA",
  "version" : {
    "number" : "7.9.2",
    "build_flavor" : "default",
    "build_type" : "docker",
    "build_hash" : "d34da0ea4a966c4e49417f2da2f244e3e97b4e6e",
    "build_date" : "2020-09-23T00:45:33.626720Z",
    "build_snapshot" : false,
    "lucene_version" : "8.6.2",
    "minimum_wire_compatibility_version" : "6.8.0",
    "minimum_index_compatibility_version" : "6.0.0-beta1"
  },
  "tagline" : "You Know, for Search"
}
[root@ming ~]# 
#赶紧关闭,增加内存的限制
docker stats
CONTAINER ID        NAME                CPU %               MEM USAGE / LIMIT    MEM %               NET I/O             BLOCK I/O           PIDS
3813b3690981        elasticsearch       0.31%               1.237GiB / 3.55GiB   34.86%              1.95kB / 984B       1.23MB / 1.48MB     50


#修改配置文件  -e  环境配置修改
$ docker run -d --name elasticsearch01 -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" -e ES_JAVA-OPTS="-Xms64m -Xmx512m" elasticsearch:7.9.2
#使用kibana  连接es

可视化

portainer 


docker run -d -p 8000:8000 -p 9000:9000 --name=portainer --restart=always -v /var/run/docker.sock:/var/run/docker.sock -v portainer_data:/data portainer/portainer-ce

什么是portainer

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

docker run -d -p 8000:8000 -p 9000:9000 --name=portainer --restart=always -v /var/run/docker.sock:/var/run/docker.sock --privileged=true portainer/portainer


#访问测试:外网:9000   

登录页面   设置密码

镜像原理之联合文件系统

镜像是什么

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

所有的应用,直接打包docker镜像,就可以直接跑起来

如何得到镜像

  • 从远程仓库下载
  • 朋友拷贝给你
  • 自己制作一个镜像DocerFile

Docker镜像加载原理

UnionFS (联合文件系统)

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

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

Docker镜像加载原理

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

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

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

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

所以Docker的虚拟机才200m左右

分册理解

分层的镜像

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

[root@ming ~]# docker pull redis
Using default tag: latest
latest: Pulling from library/redis
d121f8d1c412: Already exists 
2f9874741855: Pull complete 
d92da09ebfd4: Pull complete 
bdfa64b72752: Pull complete 
e748e6f663b9: Pull complete 
eb1c8b66e2a1: Pull complete 
Digest: sha256:1cfb205a988a9dae5f025c57b92e9643ec0e7ccff6e66bc639d8a5f95bba928c
Status: Downloaded newer image for redis:latest
docker.io/library/redis:latest
[root@ming ~]# 

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

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

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

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

特点:

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

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

Commit镜像

docker commit 提交容器成为一个新的副本

#命令和git原理类似
docker commit -m="提交的信息" -a="作者"  容器id  目标镜像名:[TAG]



#实战测试

# 启动一个默认的tomcat
#发现这个默认的tomcat时没有webapps应用,镜像的原因,官方的镜像webapps下面是没有文件的
#我自己拷贝进去了基本的文件
 docker run -it --name tomcat02 -p 8080:8080 tomcat
[root@ming ~]# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                    NAMES
b90cc7d362c4        tomcat              "catalina.sh run"   39 seconds ago      Up 38 seconds       0.0.0.0:8080->8080/tcp   tomcat02
[root@ming ~]# docker exec -it tomcat02 /bin/bash
root@b90cc7d362c4:/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
root@b90cc7d362c4:/usr/local/tomcat# cp -r webapps.dist/* webapps/    拷贝文件到webapps目录
root@b90cc7d362c4:/usr/local/tomcat# cd webapps
root@b90cc7d362c4:/usr/local/tomcat/webapps# ls
ROOT  docs  examples  host-manager  manager
root@b90cc7d362c4:/usr/local/tomcat/webapps# 


#提交       
[root@ming ~]# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                    NAMES
b90cc7d362c4        tomcat              "catalina.sh run"   9 minutes ago       Up 9 minutes        0.0.0.0:8080->8080/tcp   tomcat02
[root@ming ~]# docker commit -a="ming" -m="add webapps app" tomcat02 tomcat1:1.0
sha256:fd0160f59e6034e87230f0d86cc12f062fa9b1f561477c85df26ffce9c171559
[root@ming ~]# docker images
REPOSITORY            TAG                 IMAGE ID            CREATED             SIZE
tomcat1               1.0                 fd0160f59e60        8 seconds ago       652MB  ##自己修改的镜像
nginx                 latest              992e3b7be046        6 days ago          133MB
elasticsearch         7.9.2               caa7a21ca06e        2 weeks ago         763MB
tomcat                9.0                 f796d3d2c195        3 weeks ago         647MB
tomcat                latest              f796d3d2c195        3 weeks ago         647MB
redis                 latest              84c5f6e03bf0        4 weeks ago         104MB
centos                latest              0d120b6ccaa8        2 months ago        215MB
portainer/portainer   latest              62771b0b9b09        2 months ago        79.1MB
[root@ming ~]# 


容器数据卷

什么是容器数据卷

docker的理念

将应用和环境打包成一个镜像

数据?如果数据都在容器中,那么容器删除,数据就会丢失

需求:数据可以存储在本地

容器之间可以有一个数据共享的技术,Docker容器中产生的数据,同步到本地

这就是卷技术,目录的挂载,将我们容器内的目录,挂载到linux上面

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

使用数据卷

#方式一   直接使用命令挂载
docker run -it  -v  宿主机目录:容器目录  


测试
#启动
docker run -it -v /home/ceshi:/home centos /bin/bash
#dockers inspect  容器id   查看信息

docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED              STATUS              PORTS               NAMES
d47febce95db        centos              "/bin/bash"         About a minute ago   Up About a minute                       fervent_payne
[root@ming ceshi]# docker inspect d47febce95db 
[
    {
        "Id": "d47febce95dbe150082d3b1fd58d50bcf3aa9b00f546c6b8bac4958635d7e195",
        "Created": "2020-10-12T11:38:25.959033449Z",
        "Path": "/bin/bash",
        "Args": [],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 60386,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2020-10-12T11:38:26.342199542Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:0d120b6ccaa8c5e149176798b3501d4dd1885f961922497cd0abef155c869566",
        "ResolvConfPath": "/var/lib/docker/containers/d47febce95dbe150082d3b1fd58d50bcf3aa9b00f546c6b8bac4958635d7e195/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/d47febce95dbe150082d3b1fd58d50bcf3aa9b00f546c6b8bac4958635d7e195/hostname",
        "HostsPath": "/var/lib/docker/containers/d47febce95dbe150082d3b1fd58d50bcf3aa9b00f546c6b8bac4958635d7e195/hosts",
        "LogPath": "/var/lib/docker/containers/d47febce95dbe150082d3b1fd58d50bcf3aa9b00f546c6b8bac4958635d7e195/d47febce95dbe150082d3b1fd58d50bcf3aa9b00f546c6b8bac4958635d7e195-json.log",
        "Name": "/fervent_payne",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "",
        "ExecIDs": null,
        "HostConfig": {
            "Binds": [
                "/home/ceshi:/home"
            ],
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "default",
            "PortBindings": {},
            "RestartPolicy": {
                "Name": "no",
                "MaximumRetryCount": 0
            },
            "AutoRemove": false,
            "VolumeDriver": "",
            "VolumesFrom": null,
            "CapAdd": null,
            "CapDrop": null,
            "Capabilities": null,
            "Dns": [],
            "DnsOptions": [],
            "DnsSearch": [],
            "ExtraHosts": null,
            "GroupAdd": null,
            "IpcMode": "private",
            "Cgroup": "",
            "Links": null,
            "OomScoreAdj": 0,
            "PidMode": "",
            "Privileged": false,
            "PublishAllPorts": false,
            "ReadonlyRootfs": false,
            "SecurityOpt": null,
            "UTSMode": "",
            "UsernsMode": "",
            "ShmSize": 67108864,
            "Runtime": "runc",
            "ConsoleSize": [
                0,
                0
            ],
            "Isolation": "",
            "CpuShares": 0,
            "Memory": 0,
            "NanoCpus": 0,
            "CgroupParent": "",
            "BlkioWeight": 0,
            "BlkioWeightDevice": [],
            "BlkioDeviceReadBps": null,
            "BlkioDeviceWriteBps": null,
            "BlkioDeviceReadIOps": null,
            "BlkioDeviceWriteIOps": null,
            "CpuPeriod": 0,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": [],
            "DeviceCgroupRules": null,
            "DeviceRequests": null,
            "KernelMemory": 0,
            "KernelMemoryTCP": 0,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": null,
            "OomKillDisable": false,
            "PidsLimit": null,
            "Ulimits": null,
            "CpuCount": 0,
            "CpuPercent": 0,
            "IOMaximumIOps": 0,
            "IOMaximumBandwidth": 0,
            "MaskedPaths": [
                "/proc/asound",
                "/proc/acpi",
                "/proc/kcore",
                "/proc/keys",
                "/proc/latency_stats",
                "/proc/timer_list",
                "/proc/timer_stats",
                "/proc/sched_debug",
                "/proc/scsi",
                "/sys/firmware"
            ],
            "ReadonlyPaths": [
                "/proc/bus",
                "/proc/fs",
                "/proc/irq",
                "/proc/sys",
                "/proc/sysrq-trigger"
            ]
        },
        "GraphDriver": {
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/2e10846d182f7a8a2f548ae9bdd8485822dcfeba24119fb0f6b26f1477cd289f-init/diff:/var/lib/docker/overlay2/cce3cbf047e3cd1fde4d1931103098c5514fd23f0f783e0b117a318ecc77a15a/diff",
                "MergedDir": "/var/lib/docker/overlay2/2e10846d182f7a8a2f548ae9bdd8485822dcfeba24119fb0f6b26f1477cd289f/merged",
                "UpperDir": "/var/lib/docker/overlay2/2e10846d182f7a8a2f548ae9bdd8485822dcfeba24119fb0f6b26f1477cd289f/diff",
                "WorkDir": "/var/lib/docker/overlay2/2e10846d182f7a8a2f548ae9bdd8485822dcfeba24119fb0f6b26f1477cd289f/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [                         ##挂载成功
            {
                "Type": "bind",
                "Source": "/home/ceshi",
                "Destination": "/home",
                "Mode": "",
                "RW": true,
                "Propagation": "rprivate"
            }
        ],
        "Config": {
            "Hostname": "d47febce95db",
            "Domainname": "",
            "User": "",
            "AttachStdin": true,
            "AttachStdout": true,
            "AttachStderr": true,
            "Tty": true,
            "OpenStdin": true,
            "StdinOnce": true,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
            ],
            "Cmd": [
                "/bin/bash"
            ],
            "Image": "centos",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {
                "org.label-schema.build-date": "20200809",
                "org.label-schema.license": "GPLv2",
                "org.label-schema.name": "CentOS Base Image",
                "org.label-schema.schema-version": "1.0",
                "org.label-schema.vendor": "CentOS"
            }
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "daa9b8fec45a6727c8e92d15392f313105b8f3aeae53a63c7c0a1d19e5b35b0e",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {},
            "SandboxKey": "/var/run/docker/netns/daa9b8fec45a",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "b103eeaef74c5667d0dc30bd6192934345802d8ce4c805f451cb83f91874813e",
            "Gateway": "172.17.0.1",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "172.17.0.3",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "MacAddress": "02:42:ac:11:00:03",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "bf8c129390ae2e027c6632ab9f27dd9fe9f26c0c6ae60cd4f13b555542271aa5",
                    "EndpointID": "b103eeaef74c5667d0dc30bd6192934345802d8ce4c805f451cb83f91874813e",
                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.3",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:11:00:03",
                    "DriverOpts": null
                }
            }
        }
    }
]


建立映射,双向绑定,同步数据

实战:Mysql数据同步

Mysql数据的持久化问题 data

# 下载mysql镜像
[root@ming ceshi]# docker pull mysql
Using default tag: latest
latest: Pulling from library/mysql
d121f8d1c412: Already exists 
f3cebc0b4691: Pull complete 
1862755a0b37: Pull complete 
489b44f3dbb4: Pull complete 
690874f836db: Pull complete 
baa8be383ffb: Pull complete 
55356608b4ac: Pull complete 
dd35ceccb6eb: Pull complete 
429b35712b19: Pull complete 
162d8291095c: Pull complete 
5e500ef7181b: Pull complete 
af7528e958b6: Pull complete 
Digest: sha256:e1bfe11693ed2052cb3b4e5fa356c65381129e87e38551c6cd6ec532ebe0e808
Status: Downloaded newer image for mysql:latest
docker.io/library/mysql:latest


#运行容器,需要做数据挂载,  #安装启动mysql,需要配置密码的,这是要注意的一点

##官方测试
docker run --name some-mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:tag


-d 后台运行
-p 端口映射
-v 卷挂载
-e 环境配置
--name  容器名字
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



mysql> use mysql;
Database changed

mysql> SELECT Host, User, plugin from user;
+-----------+------------------+-----------------------+
| Host      | User             | plugin                |
+-----------+------------------+-----------------------+
| %         | root             | caching_sha2_password |
| localhost | mysql.infoschema | caching_sha2_password |
| localhost | mysql.session    | caching_sha2_password |
| localhost | mysql.sys        | caching_sha2_password |
| localhost | root             | caching_sha2_password |
+-----------+------------------+-----------------------+

mysql 8.0登录时遇到的问题解决
ALTER USER root@localhost IDENTIFIED WITH mysql_native_password BY 'xxxxx';
mysql> ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY '123456';
Query OK, 0 rows affected (0.00 sec)

mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '123456';
Query OK, 0 rows affected (0.01 sec)

mysql> FLUSH PRIVILEGES;



#启动成功之后,我们在本地使用sqlyog 来测试

#在本地测试创建一个数据库,映射路径ok

容器删掉后数据不会丢失,实现容器数据持久化

具名挂载和匿名挂载

# 匿名挂载
-v  容器路径
-P 大P随机端口
docker run -d -P   --name  nginx01  -v /etc/nginx nginx

#查看所有的volume的信息
# docker  volume ls
[root@ming data]# docker volume ls
DRIVER              VOLUME NAME
local               62c026d31aad29d30d7e9ef224764a1a2b944616d29cfa8e3bd0f68bff507a38

这里发现,这种就是匿名挂载,我们在-v只写了容器内的路径,没有写容器外的路径

docker run -d -P --name nginx02 -v juming-nginx:/etc/nginx nginx
具名挂载
docker volume ls
root@ming home]# docker volume ls
DRIVER              VOLUME NAME
local               62c026d31aad29d30d7e9ef224764a1a2b944616d29cfa8e3bd0f68bff507a38
local               a1f46af659aa1f7f147c69aa1d93872210f7ea625af39ed7b875656806927f3f
local               juming
# 通过-v  卷名:容器路径

docker volume inspect juming
查看信息
[root@ming home]# docker volume inspect juming
[
    {
        "CreatedAt": "2020-10-12T20:31:53+08:00",
        "Driver": "local",
        "Labels": null,
        "Mountpoint": "/var/lib/docker/volumes/juming/_data",
        "Name": "juming",
        "Options": null,
        "Scope": "local"
    }
]

所有的docker容器内的卷,没有指定目录的情况下都是在/var/lib/docker/volumes/xxx/_data

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

如何确定是具名挂载还是匿名挂载,还是指定路径挂载
-v  容器内路径   #匿名挂载
-v  卷名:容器内路径  #具名挂载
-v  /宿主机路径:容器内路径   #指定路径挂载


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

#一旦对这个设置了容器权限,容器对我们挂载出来的内容就有了限定了
docker  run  -d  -P --name nginx04 -v juming01:/etc/nginx:ro nginx
docker  run  -d  -P --name nginx04 -v juming01:/etc/nginx:rw nginx

ro  只能通过宿主机来操作

初识Dockerfile

Dockerfile就是用来构建docker镜像的构建文件,命令脚本

通过这个脚本可以生成镜像

#创建一个docfile文件,名字可以随机,建议Dockerfile
#文件中的内容 指令(大写) 参数
FROM centos
VOLUME ["volume01","volume02"]

CMD echo "----end-----"
CMD /bin/bash
              
[root@ming docker-test-volume]# docker build -f /home/docker-test-volume/docfile1 -t ming/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 d56780f18bb9
Removing intermediate container d56780f18bb9
 ---> 7adab0879ec1
Step 3/4 : CMD echo "----end-----"
 ---> Running in 9a2f302da5fe
Removing intermediate container 9a2f302da5fe
 ---> cd45ed923c4f
Step 4/4 : CMD /bin/bash
 ---> Running in 6027b838c47b
Removing intermediate container 6027b838c47b
 ---> d5e1b0037018
Successfully built d5e1b0037018
Successfully tagged ming/centos:1.0
[root@ming docker-test-volume]# 


启动自己写的镜像
docker run -it --name docker01 ming/centos:1.0
[root@ming docker-test-volume]# docker images
REPOSITORY            TAG                 IMAGE ID            CREATED              SIZE
ming/centos           1.0                 d5e1b0037018        About a minute ago   215MB
tomcat1               1.0                 fd0160f59e60        2 hours ago          652MB
nginx                 latest              992e3b7be046        6 days ago           133MB
elasticsearch         7.9.2               caa7a21ca06e        2 weeks ago          763MB
tomcat                9.0                 f796d3d2c195        3 weeks ago          647MB
tomcat                latest              f796d3d2c195        3 weeks ago          647MB
redis                 latest              84c5f6e03bf0        4 weeks ago          104MB
mysql                 latest              e1d7dc9731da        4 weeks ago          544MB
centos                latest              0d120b6ccaa8        2 months ago         215MB
portainer/portainer   latest              62771b0b9b09        2 months ago         79.1MB
[root@ming docker-test-volume]# docker run -it ming/centos /bin/bash
Unable to find image 'ming/centos:latest' locally
docker: Error response from daemon: pull access denied for ming/centos, repository does not exist or may require 'docker login': denied: requested access to the resource is denied.
See 'docker run --help'.
[root@ming docker-test-volume]# docker run -it d5e1b0037018 /bin/bash
[root@49c41e6c1a06 /]# ls -l
total 0
lrwxrwxrwx   1 root root   7 May 11  2019 bin -> usr/bin
drwxr-xr-x   5 root root 360 Oct 12 13:00 dev
drwxr-xr-x   1 root root  66 Oct 12 13:00 etc
drwxr-xr-x   2 root root   6 May 11  2019 home
lrwxrwxrwx   1 root root   7 May 11  2019 lib -> usr/lib
lrwxrwxrwx   1 root root   9 May 11  2019 lib64 -> usr/lib64
drwx------   2 root root   6 Aug  9 21:40 lost+found
drwxr-xr-x   2 root root   6 May 11  2019 media
drwxr-xr-x   2 root root   6 May 11  2019 mnt
drwxr-xr-x   2 root root   6 May 11  2019 opt
dr-xr-xr-x 130 root root   0 Oct 12 13:00 proc
dr-xr-x---   2 root root 162 Aug  9 21:40 root
drwxr-xr-x  11 root root 163 Aug  9 21:40 run
lrwxrwxrwx   1 root root   8 May 11  2019 sbin -> usr/sbin
drwxr-xr-x   2 root root   6 May 11  2019 srv
dr-xr-xr-x  13 root root   0 Oct 12 13:00 sys
drwxrwxrwt   7 root root 145 Aug  9 21:40 tmp
drwxr-xr-x  12 root root 144 Aug  9 21:40 usr
drwxr-xr-x  20 root root 262 Aug  9 21:40 var
drwxr-xr-x   2 root root   6 Oct 12 13:00 volume01         //生成镜像自动挂载的   容器内的目录,匿名挂载
drwxr-xr-x   2 root root   6 Oct 12 13:00 volume02


查看卷挂载路径
docker  inspect  容器id


这种方式我们未来使用的十分多,因为我们通常会构建自己的镜像
假设构建镜像时候没有挂载卷,要手动镜像挂载  -v  容器内路径



数据卷容器

多个mysql同步数据



启动三个容器

docker run -it --name docker01 ming/centos:1.0
docker run -it --name docker02 --volumes-from docker01 ming/centos:1.0    #数据同步
docker run -it --name docker03 --volumes-from docker01 ming/centos:1.0


多个mysql实现数据共享

结论:
容器之间配置信息的传递,数据卷容器的声明周期一直持续到容器使用为止
但是一旦持久化到了本地,这个时候,本地的数据是不会删除的

DockerFile 介绍

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

构建步骤:

  • 编写一个dockerfile文件
  • docker build构建成为一个镜像
  • docker run 运行镜像
  • docker push 发布镜像(DockerHub,阿里云镜像仓库)

查看一下官方怎么做的,点击版本信息,到docfile 文件

Dockerfile构建

基础知识:

  • 每个保留关键字(指令)都必须是大写字母
  • 执行从上到下顺序执行
  • ‘#’标识注释
  • 每一个指令都会创建提交一个新的镜像层,并提交

dockerfile是面向开发的,我们以后要发布项目,做镜像,就需要编写dockerfile文件,这个文件十分简单

Docker镜像逐渐成为企业交付的标准,必须要掌握

开发,部署,运维

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

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

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

DockerFile指令

FROM    								#指定基础镜像
MAINTAINER							 	#镜像是谁写的
RUN
ADD                                    #步骤,比如tomcat镜像,这个tomcat压缩包
WORKDIR                                 #镜像工作目录
VOLUME                                  #挂载卷
EXPOSE                                  #指定暴露端口 配置
RUN                                     #构建镜像需要运行的命令


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

ONBUILD                       #当构建一个被继承  DockerFile  这个时候就会运行ONBUILD指令,触发指令
COPY                 #类似ADD     ,将我们的文件拷贝到镜像中
ENV                   #构建的时候设置环境变量

构建自己的Centos

官方

centos 7

FROM scratch
ADD centos-7-x86_64-docker.tar.xz /

LABEL \
    org.label-schema.schema-version="1.0" \
    org.label-schema.name="CentOS Base Image" \
    org.label-schema.vendor="CentOS" \
    org.label-schema.license="GPLv2" \
    org.label-schema.build-date="20200809" \
    org.opencontainers.image.title="CentOS Base Image" \
    org.opencontainers.image.vendor="CentOS" \
    org.opencontainers.image.licenses="GPL-2.0-only" \
    org.opencontainers.image.created="2020-08-09 00:00:00+01:00"

CMD ["/bin/bash"]

Docker Hub中99%的镜像都是从这个基础镜像过来的FROM scratch,然后配置需要的软件和配置来进行构建

创建自己的centos

#编写dockerfile文件     mydockerfile
FROM centos
MAINTAINER ming<996287487@qq.com>



ENV MYPATH /usr/local


WORKDIR $MYPATH


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

CMD echo $MYPATH

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


#通过这个文件构建镜像

#命令  docker build -f  dockersfile文件路径  -t  镜像名:[tag]

docker build -f /home/docfile/mydockerfile -t mycentos:0.1 .       #别忘了后面一个点  .    

[root@ming docfile]# docker build -f /home/docfile/dockerfile -t mycentos:0.1 .
Sending build context to Docker daemon  2.048kB
Step 1/10 : FROM centos
 ---> 0d120b6ccaa8
Step 2/10 : MAINTAINER ming<996287487@qq.com>
 ---> Running in ba6f245d538e
Removing intermediate container ba6f245d538e
 ---> 93dc6baf07ab
Step 3/10 : ENV MYPATH /usr/local
 ---> Running in 07f175a92551
Removing intermediate container 07f175a92551
 ---> fe1497588e86
Step 4/10 : WORKDIR $MYPATH
 ---> Running in 344cab39f800
Removing intermediate container 344cab39f800
 ---> fded8a9f95bd
Step 5/10 : RUN yum -y install vim
 ---> Running in 08e7d1657673
CentOS-8 - AppStream                            1.2 MB/s | 5.8 MB     00:04    
CentOS-8 - Base                                  24 kB/s | 2.2 MB     01:33    
CentOS-8 - Extras                               2.6 kB/s | 8.1 kB     00:03    
Dependencies resolved.
================================================================================
 Package             Arch        Version                   Repository      Size
================================================================================
Installing:
 vim-enhanced        x86_64      2:8.0.1763-13.el8         AppStream      1.4 M
Installing dependencies:
 gpm-libs            x86_64      1.20.7-15.el8             AppStream       39 k
 vim-common          x86_64      2:8.0.1763-13.el8         AppStream      6.3 M
 vim-filesystem      noarch      2:8.0.1763-13.el8         AppStream       48 k
 which               x86_64      2.21-12.el8               BaseOS          49 k

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

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

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

Complete!
Removing intermediate container 08e7d1657673
 ---> 4ec2e24c83f6
Step 6/10 : RUN yum -y install net-tools
 ---> Running in 7803a01a2a85
Last metadata expiration check: 0:00:11 ago on Tue Oct 13 07:21:34 2020.
Dependencies resolved.
================================================================================
 Package         Architecture Version                        Repository    Size
================================================================================
Installing:
 net-tools       x86_64       2.0-0.51.20160912git.el8       BaseOS       323 k

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

Total download size: 323 k
Installed size: 1.0 M
Downloading Packages:
net-tools-2.0-0.51.20160912git.el8.x86_64.rpm    15 kB/s | 323 kB     00:21    
--------------------------------------------------------------------------------
Total                                            15 kB/s | 323 kB     00:21     
Running transaction check
Transaction check succeeded.
Running transaction test
Transaction test succeeded.
Running transaction
  Preparing        :                                                        1/1 
  Installing       : net-tools-2.0-0.51.20160912git.el8.x86_64              1/1 
  Running scriptlet: net-tools-2.0-0.51.20160912git.el8.x86_64              1/1 
  Verifying        : net-tools-2.0-0.51.20160912git.el8.x86_64              1/1 

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

Complete!
Removing intermediate container 7803a01a2a85
 ---> 19df7ecb5476
Step 7/10 : EXPOSE 80
 ---> Running in 0d2c6f225a96
Removing intermediate container 0d2c6f225a96
 ---> 5b480093c134
Step 8/10 : CMD echo $MYPATH
 ---> Running in beba54233ba8
Removing intermediate container beba54233ba8
 ---> 1f95f7bb4b16
Step 9/10 : CMD echo "-----end-------"
 ---> Running in b48e7019212e
Removing intermediate container b48e7019212e
 ---> 341554bfffd2
Step 10/10 : CMD /bin/bash
 ---> Running in 06432a8e746b
Removing intermediate container 06432a8e746b
 ---> 8aa00459feec
Successfully built 8aa00459feec
Successfully tagged mycentos:0.1



#测试
[root@ming docfile]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
mycentos            0.1                 8aa00459feec        38 seconds ago      295MB
mysql               latest              e1d7dc9731da        4 weeks ago         544MB
centos              latest              0d120b6ccaa8        2 months ago        215MB
[root@ming docfile]# docker run -it mycentos:0.1                  #记得添加版本号,不然会去仓库找最新的
[root@9aae2fdbfd49 local]# ls
bin  etc  games  include  lib  lib64  libexec  sbin  share  src
[root@9aae2fdbfd49 local]# pwd
/usr/local
[root@9aae2fdbfd49 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 23  bytes 1880 (1.8 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

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

[root@9aae2fdbfd49 local]# vim test







#对比原先的,工作目录默认为根目录,没有vim。。。等命令



docker history 镜像id          查看镜像怎么生成的

[root@ming docfile]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
mycentos            0.1                 8aa00459feec        4 minutes ago       295MB
mysql               latest              e1d7dc9731da        4 weeks ago         544MB
centos              latest              0d120b6ccaa8        2 months ago        215MB
[root@ming docfile]# docker history 8aa00459feec
IMAGE               CREATED             CREATED BY                                      SIZE                COMMENT
8aa00459feec        4 minutes ago       /bin/sh -c #(nop)  CMD ["/bin/sh" "-c" "/bin…   0B                  
341554bfffd2        4 minutes ago       /bin/sh -c #(nop)  CMD ["/bin/sh" "-c" "echo…   0B                  
1f95f7bb4b16        4 minutes ago       /bin/sh -c #(nop)  CMD ["/bin/sh" "-c" "echo…   0B                  
5b480093c134        4 minutes ago       /bin/sh -c #(nop)  EXPOSE 80                    0B                  
19df7ecb5476        4 minutes ago       /bin/sh -c yum -y install net-tools             22.8MB              
4ec2e24c83f6        5 minutes ago       /bin/sh -c yum -y install vim                   57.3MB              
fded8a9f95bd        6 minutes ago       /bin/sh -c #(nop) WORKDIR /usr/local            0B                  
fe1497588e86        6 minutes ago       /bin/sh -c #(nop)  ENV MYPATH=/usr/local        0B                  
93dc6baf07ab        6 minutes ago       /bin/sh -c #(nop)  MAINTAINER ming<996287487…   0B                  
0d120b6ccaa8        2 months ago        /bin/sh -c #(nop)  CMD ["/bin/bash"]            0B                  
<missing>           2 months ago        /bin/sh -c #(nop)  LABEL org.label-schema.sc…   0B                  
<missing>           2 months ago        /bin/sh -c #(nop) ADD file:538afc0c5c964ce0d…   215MB       

CMD和ENTRYPOINT的区别

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



#测试

创建文件dockerfile-cmd-test
FROM centos

CMD ["ls","-a"]



#创建镜像
[root@ming docfile]# docker build -f dockerfile-cmd-test -t cmdtest:1.0 .
Sending build context to Docker daemon  3.072kB
Step 1/2 : FROM centos
 ---> 0d120b6ccaa8
Step 2/2 : CMD ["ls","-a"]
 ---> Running in 4d226dfe0d99
Removing intermediate container 4d226dfe0d99
 ---> 07e95d65dd67
Successfully built 07e95d65dd67
Successfully tagged cmdtest:1.0
[root@ming docfile]# docker run 07e95d65dd67
.
..
.dockerenv
bin
dev
etc
home
lib
lib64
lost+found
media
mnt
opt
proc
root
run
sbin
srv
sys
tmp
usr
var

#想追加一个命令 -l    ls   -al

[root@ming docfile]#  docker run 07e95d65dd67 -l
docker: Error response from daemon: OCI runtime create failed: container_linux.go:349: starting container process caused "exec: \"-l\": executable file not found in $PATH": unknown.
ERRO[0000] error waiting for container: context canceled 

#cmd的情况下,-l替换了CMD ["ls","-a"]命令,-l不是命令所以报错






#ENTRYPOINT   

[root@ming docfile]# docker build -f dockerfile-entrypoint -t entrypoint:1.0 .
Sending build context to Docker daemon  4.096kB
Step 1/2 : FROM centos
 ---> 0d120b6ccaa8
Step 2/2 : ENTRYPOINT ["ls","-a"]
 ---> Running in 21aa510e8b75
Removing intermediate container 21aa510e8b75
 ---> c7d06534b96f
Successfully built c7d06534b96f
Successfully tagged entrypoint:1.0
[root@ming docfile]# docker run c7d06534b96f
.
..
.dockerenv
bin
dev
etc
home
lib
lib64
lost+found
media
mnt
opt
proc
root
run
sbin
srv
sys
tmp
usr
var
[root@ming docfile]# docker run c7d06534b96f -l
total 0
drwxr-xr-x   1 root root   6 Oct 13 07:45 .
drwxr-xr-x   1 root root   6 Oct 13 07:45 ..
-rwxr-xr-x   1 root root   0 Oct 13 07:45 .dockerenv
lrwxrwxrwx   1 root root   7 May 11  2019 bin -> usr/bin
drwxr-xr-x   5 root root 340 Oct 13 07:45 dev
drwxr-xr-x   1 root root  66 Oct 13 07:45 etc
drwxr-xr-x   2 root root   6 May 11  2019 home
lrwxrwxrwx   1 root root   7 May 11  2019 lib -> usr/lib
lrwxrwxrwx   1 root root   9 May 11  2019 lib64 -> usr/lib64
drwx------   2 root root   6 Aug  9 21:40 lost+found
drwxr-xr-x   2 root root   6 May 11  2019 media
drwxr-xr-x   2 root root   6 May 11  2019 mnt
drwxr-xr-x   2 root root   6 May 11  2019 opt
dr-xr-xr-x 121 root root   0 Oct 13 07:45 proc
dr-xr-x---   2 root root 162 Aug  9 21:40 root
drwxr-xr-x  11 root root 163 Aug  9 21:40 run
lrwxrwxrwx   1 root root   8 May 11  2019 sbin -> usr/sbin
drwxr-xr-x   2 root root   6 May 11  2019 srv
dr-xr-xr-x  13 root root   0 Oct 13 07:45 sys
drwxrwxrwt   7 root root 145 Aug  9 21:40 tmp
drwxr-xr-x  12 root root 144 Aug  9 21:40 usr
drwxr-xr-x  20 root root 262 Aug  9 21:40 var


直接在后面追加

实战:Tomcat镜像

准备镜像文件压缩包,jdk的压缩包

编写docfile文件 官方命名 Dockerfile build会自动寻找这个文件,就不需要-f指定了

FROM centos

MAINTAINER ming<996287487@qq.com>


COPY readme.txt /usr/local/readme.txt

ADD apache-tomcat-9.0.38.tar.gz /usr/local
ADD jdk-8u261-linux-i586.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 CATALINA_HOME  /usr/local/apache-tomcat-9.0.38

ENV CATALINA_BASH  /usr/local/apache-tomcat-9.0.38

ENV PATH $PATH:$JAVA_HOME/bin:$CATALINA_HOME/lib:$CATALINA_HOME/bin

EXPOSE 8080

CMD /usr/local/apache-tomcat-9.0.38/bin/startup.sh && tail -F /url/local/apache-tomcat-9.0.38/bin/logs/catalina.out



#构建镜像

[root@ming tomcat]# docker build -t diytomcat .


#如果失败,关闭防火墙,重启docker

[root@ming tomcat]# docker build -t diytomcat .


[root@ming tomcat]# docker build -t diytomcat .
Sending build context to Docker daemon  154.7MB
Step 1/15 : FROM centos
 ---> 0d120b6ccaa8
Step 2/15 : MAINTAINER ming<996287487@qq.com>
 ---> Using cache
 ---> 93dc6baf07ab
Step 3/15 : COPY readme.txt /usr/local/readme.txt
 ---> e25e788f7787
Step 4/15 : ADD apache-tomcat-9.0.38.tar.gz /usr/local
 ---> b74166b1b970
Step 5/15 : ADD jdk-8u261-linux-i586.tar.gz /usr/local
 ---> c3086fb74414
Step 6/15 : RUN yum -y install vim
 ---> Running in aa2a8bd004e5
CentOS-8 - AppStream                            3.1 MB/s | 5.8 MB     00:01    
CentOS-8 - Base                                 278 kB/s | 2.2 MB     00:08    
CentOS-8 - Extras                               2.3 kB/s | 8.1 kB     00:03    
Dependencies resolved.
================================================================================
 Package             Arch        Version                   Repository      Size
================================================================================
Installing:
 vim-enhanced        x86_64      2:8.0.1763-13.el8         AppStream      1.4 M
Installing dependencies:
 gpm-libs            x86_64      1.20.7-15.el8             AppStream       39 k
 vim-common          x86_64      2:8.0.1763-13.el8         AppStream      6.3 M
 vim-filesystem      noarch      2:8.0.1763-13.el8         AppStream       48 k
 which               x86_64      2.21-12.el8               BaseOS          49 k

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

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

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

Complete!
Removing intermediate container aa2a8bd004e5
 ---> 7e8fc8d25ab9
Step 7/15 : ENV MYPATH /usr/local
 ---> Running in b9612a19463d
Removing intermediate container b9612a19463d
 ---> 388826c1c738
Step 8/15 : WORKDIR  $MYPATH
 ---> Running in 8f1b443117fd
Removing intermediate container 8f1b443117fd
 ---> e399e06a4943
Step 9/15 : ENV JAVA_HOME /usr/local/jdk1.8.0_261
 ---> Running in 5579b655d538
Removing intermediate container 5579b655d538
 ---> 7b0c985fdf30
Step 10/15 : ENV CLASSPATH $JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
 ---> Running in 9f5b4292a3e7
Removing intermediate container 9f5b4292a3e7
 ---> 4e1c291bfee4
Step 11/15 : ENV CATALINA_HOME  /usr/local/apache-tomcat-9.0.38
 ---> Running in d9bc6d5a58b4
Removing intermediate container d9bc6d5a58b4
 ---> 297d665517f2
Step 12/15 : ENV CATALINA_BASH  /usr/local/apache-tomcat-9.0.38
 ---> Running in da7b34a23b46
Removing intermediate container da7b34a23b46
 ---> 1ffdd2d92cc5
Step 13/15 : ENV PATH $PATH:$JAVA_HOME/bin:$CATALINA_HOME/lib:$CATALINA_HOME/bin
 ---> Running in c13968d735ee
Removing intermediate container c13968d735ee
 ---> f1aa2df1c272
Step 14/15 : EXPOSE 8080
 ---> Running in 4929e5c73984
Removing intermediate container 4929e5c73984
 ---> 6995f5a1c22c
Step 15/15 : CMD /usr/local/apache-tomcat-9.0.38/bin/startup.sh && tail -F /url/local/apache-tomcat-9.0.38/bin/logs/catalina.out
 ---> Running in a072de3af82f
Removing intermediate container a072de3af82f
 ---> 4a92a8296c2b
Successfully built 4a92a8296c2b
Successfully tagged diytomcat:latest


#出现容器内java路径错误
#容器内需要安装依赖库[root@e852954d1f89 bin]# yum install glibc.i686



[root@ming tomcat]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
diytomcat           latest              4a92a8296c2b        54 seconds ago      633MB
entrypoint          1.0                 c7d06534b96f        4 hours ago         215MB
cmdtest             1.0                 07e95d65dd67        4 hours ago         215MB
mycentos            0.1                 8aa00459feec        4 hours ago         295MB
redis               latest              84c5f6e03bf0        4 weeks ago         104MB
mysql               latest              e1d7dc9731da        4 weeks ago         544MB
centos              latest              0d120b6ccaa8        2 months ago        215MB


#新建容器
docker run -d -p 8080:8080 --name mingtomcat -v /home/ming/build/tomcat/test:/usr/local/apache-tomcat-9.0.38/webapps/test -v /home/ming/build/tomcat/tomcatlogs/:/usr/local/apache-tomcat-9.0.38/logs diytomcat



#测试访问

#发布项目(由于做了卷挂载,我们直接在本地编写项目就可以发布了)



<?xml version="1.0" encoding="UTF-8"?>
 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
 
 </web-app>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
Hello World!<br/>
<%
out.println("你的 IP 地址 " + request.getRemoteAddr());
%>
</body>
</html>

发布,项目部署搞定

发布自己的镜像

DockHub

注册自己的账号https://hub.docker.com/

确定这个账号可以登录

在服务器上提交自己的镜像

docker login -u 
[root@ming ~]# docker login -u uxquan
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@ming ~]# 


登录完毕就可以提交镜像了,docker push

docker tag 镜像id  用户id/仓库名:tag
docker push 用户id/仓库名:tag

docker logout

发布镜像到阿里云服务

登录阿里云

容器镜像服务

创建命名空间

创建容器镜像仓库

浏览阿里云 有详细教程

Docker0网络详解

理解网络

[root@ming ~]# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:16:3e:06:fd:ce brd ff:ff:ff:ff:ff:ff
    inet 172.24.9.54/20 brd 172.24.15.255 scope global dynamic noprefixroute eth0
       valid_lft 315338797sec preferred_lft 315338797sec
    inet6 fe80::216:3eff:fe06:fdce/64 scope link 
       valid_lft forever preferred_lft forever
3: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default 
    link/ether 02:42:2a:c6:36:b6 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
    inet6 fe80::42:2aff:fec6:36b6/64 scope link 
       valid_lft forever preferred_lft forever

三个网络

问题:docker  是如何处理容器网络访问的


测试

[root@ming ~]# docker run -d -P --name tomcat01 tomcat
Unable to find image 'tomcat:latest' locally
latest: Pulling from library/tomcat
57df1a1f1ad8: Pull complete 
71e126169501: Pull complete 
1af28a55c3f3: Pull complete 
03f1c9932170: Pull complete 
881ad7aafb13: Pull complete 
9c0ffd4062f3: Pull complete 
bd62e479351a: Pull complete 
48ee8bc64dbc: Pull complete 
07cb85cca4f0: Pull complete 
6a78fac8d191: Pull complete 
Digest: sha256:1bab37d5d97bd8c74a474b2c1a62bbf1f1b4b62f151c8dcc472c7d577eb3479d
Status: Downloaded newer image for tomcat:latest
c388ff4ce845f35eb4451ab5c4f219a8bf32c96a30b0a2b101890f37b1278c2d

#查看容器的内部网络地址  ip addr     发现容器启动的时候会有一个  eht0@if65 ip地址,docker分配的

[root@ming ~]# 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
64: eth0@if65: <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



#思考,linux能不能ping通容器内部
[root@ming ~]# 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.080 ms
64 bytes from 172.17.0.2: icmp_seq=2 ttl=64 time=0.053 ms
64 bytes from 172.17.0.2: icmp_seq=3 ttl=64 time=0.043 ms


#Linux可以ping通docker容器内部
#
#原理

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

再次测试,在本机执行,多了一个ip
[root@ming ~]# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:16:3e:06:fd:ce brd ff:ff:ff:ff:ff:ff
    inet 172.24.9.54/20 brd 172.24.15.255 scope global dynamic noprefixroute eth0
       valid_lft 315338114sec preferred_lft 315338114sec
    inet6 fe80::216:3eff:fe06:fdce/64 scope link 
       valid_lft forever preferred_lft forever
3: docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default 
    link/ether 02:42:2a:c6:36:b6 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
    inet6 fe80::42:2aff:fec6:36b6/64 scope link 
       valid_lft forever preferred_lft forever
65: vethef4217a@if64: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master docker0 state UP group default 
    link/ether aa:af:05:11:db:59 brd ff:ff:ff:ff:ff:ff link-netnsid 0
    inet6 fe80::a8af:5ff:fe11:db59/64 scope link 
       valid_lft forever preferred_lft forever




#再启动一个容器测试,又多了一个网卡

[root@ming ~]# docker run -d -P --name tomcat02 tomcat
fd42c1c7a987541a5e81df09c57f9648d5d009b674fbc5df7ece91224bb4dea8
[root@ming ~]# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:16:3e:06:fd:ce brd ff:ff:ff:ff:ff:ff
    inet 172.24.9.54/20 brd 172.24.15.255 scope global dynamic noprefixroute eth0
       valid_lft 315337946sec preferred_lft 315337946sec
    inet6 fe80::216:3eff:fe06:fdce/64 scope link 
       valid_lft forever preferred_lft forever
3: docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default 
    link/ether 02:42:2a:c6:36:b6 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
    inet6 fe80::42:2aff:fec6:36b6/64 scope link 
       valid_lft forever preferred_lft forever
65: vethef4217a@if64: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master docker0 state UP group default 
    link/ether aa:af:05:11:db:59 brd ff:ff:ff:ff:ff:ff link-netnsid 0
    inet6 fe80::a8af:5ff:fe11:db59/64 scope link 
       valid_lft forever preferred_lft forever
67: veth2c9be9a@if66: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master docker0 state UP group default 
    link/ether 2e:68:f3:c2:f2:ff brd ff:ff:ff:ff:ff:ff link-netnsid 1
    inet6 fe80::2c68:f3ff:fec2:f2ff/64 scope link 
       valid_lft forever preferred_lft forever

我们发现这个容器带来网卡,都是一对一对的

veth-pair 就是一对的虚拟设备接口,他们都是成对出现的,一端连着协议,一端彼此相连

正因为这个特性,veth-pair充当一个桥梁,连接各种虚拟网络设备的

OpenStack,Docker容器之间的连接,OVS的连接,都是使用veth-pair 技术

#测试tomcat01和tomcat02是否能ping通

[root@ming ~]# docker exec 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.091 ms
64 bytes from 172.17.0.2: icmp_seq=2 ttl=64 time=0.057 ms
64 bytes from 172.17.0.2: icmp_seq=3 ttl=64 time=0.059 ms
#结论,容器之间可以互相ping通

结论:tomat01和tomcat02都是公用的一个路由器,docker0

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

docker 使用的是Linux的桥接,宿主机中是一个Docker容器的网桥,docker0

docker中的所有网络接口都是虚拟的,虚拟的转发效率高(内网传递文件)

容器互联 --link

[root@ming ~]# docker run -it -d -P --name tomcat01 tomcat
f1e2f3e3c98e255361a18f729035cb755fbadc9d9dae1230b87ca95714bfbc60
[root@ming ~]# docker run -it -d -P --name tomcat02 tomcat
b5a4b2f1f1e2aee73c998026e71be701a8135e6efc75582af90abbab3ddcc351
[root@ming ~]# docker exec -it tomcat01 ping tomcat02
ping: tomcat02: Name or service not known


#如何解决,可以通过名字访问容器

[root@ming ~]# docker run -it -d -P --name tomcat03 --link tomcat02 tomcat      #--link   连通
2edf7d200c751c9b107ab9165754433dbcfd870e2d54729cf54a359669c950d9
[root@ming ~]# docker exec -it tomcat03 ping tomcat02
PING 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.088 ms
64 bytes from tomcat02 (172.17.0.3): icmp_seq=2 ttl=64 time=0.056 ms
64 bytes from tomcat02 (172.17.0.3): icmp_seq=3 ttl=64 time=0.057 ms

#通过--link 可以解决网络连通问题

#反向连不通



docker network  inspect  容器id



#查看hosts配置,在这里原理发现   --link 就是在hosts配置中增加了一个ip地址映射
docker exec -it  tomcat03 cat /etc/hosts


自定义网络,不适用docker0
docker0问题,他不支持容器名连接访问



自定义网络

#查看所有的docker网络
[root@ming ~]# docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
00019b2773ac        bridge              bridge              local
e3241bcb00e8        host                host                local
104f10b59310        none                null                local


#网络模式
bridge:桥接docker
none:不配置网络
host:和宿主机共享网络
container:容器网络互通,(用的少)


#测试

# docker  run -d -P --name tomcat01
# docker run -d -P tomcat01 --net bridge tomcat

#docker0特点:默认,域名不能访问,--link可以打通连接

#我们可以自定义一个网络

[root@ming ~]# docker network create --driver bridge --subnet 192.168.0.0/16 --gateway 192.168.0.1 mynet
1b08d9b162842f1aa7ead437518410fa8fb1e4fe28e7755a80ed54d6288971fe

[root@ming ~]# docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
00019b2773ac        bridge              bridge              local
e3241bcb00e8        host                host                local
1b08d9b16284        mynet               bridge              local
104f10b59310        none                null                local


[root@ming ~]# docker network inspect mynet
[
    {
        "Name": "mynet",
        "Id": "1b08d9b162842f1aa7ead437518410fa8fb1e4fe28e7755a80ed54d6288971fe",
        "Created": "2020-10-15T19:20:32.948691747+08:00",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": {},
            "Config": [
                {
                    "Subnet": "192.168.0.0/16",
                    "Gateway": "192.168.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {},
        "Options": {},
        "Labels": {}
    }
]




[root@ming ~]# docker run  -d -P --name tomcat01-net --net mynet tomcat 
327d40e53e3467287b8a53a474353e66dbce8df25270d3cc69035315bba128c6
[root@ming ~]# docker run  -d -P --name tomcat02-net --net mynet tomcat 
5e1af58d43dc8e86637613257a38a45308c914d2ba7a1902b0cca656f4645de2
[root@ming ~]# docker network inspect mynet
[
    {
        "Name": "mynet",
        "Id": "1b08d9b162842f1aa7ead437518410fa8fb1e4fe28e7755a80ed54d6288971fe",
        "Created": "2020-10-15T19:20:32.948691747+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": {
            "327d40e53e3467287b8a53a474353e66dbce8df25270d3cc69035315bba128c6": {
                "Name": "tomcat01-net",
                "EndpointID": "2633c94ffb5bb3159c4893d0c5b9b72fd0cedbb731aa312024c40811d9d22a67",
                "MacAddress": "02:42:c0:a8:00:02",
                "IPv4Address": "192.168.0.2/16",
                "IPv6Address": ""
            },
            "5e1af58d43dc8e86637613257a38a45308c914d2ba7a1902b0cca656f4645de2": {
                "Name": "tomcat02-net",
                "EndpointID": "2c9117b299f2f607784e536eb4a35a81ba2da17b85c80bb284405931e49807f3",
                "MacAddress": "02:42:c0:a8:00:03",
                "IPv4Address": "192.168.0.3/16",
                "IPv6Address": ""
            }
        },
        "Options": {},
        "Labels": {}
    }
]

[root@ming ~]# docker exec -it tomcat01-net ping tomcat02-net
PING tomcat02-net (192.168.0.3) 56(84) bytes of data.
64 bytes from tomcat02-net.mynet (192.168.0.3): icmp_seq=1 ttl=64 time=0.076 ms
64 bytes from tomcat02-net.mynet (192.168.0.3): icmp_seq=2 ttl=64 time=0.062 ms
64 bytes from tomcat02-net.mynet (192.168.0.3): icmp_seq=3 ttl=64 time=0.062 ms
64 bytes from tomcat02-net.mynet (192.168.0.3): icmp_seq=4 ttl=64 time=0.060 ms


#再次测试ping连接

不使用--link也可以ping名字
自定义网络docker已经帮我们维护好了对应的关系,推荐平时使用这样的网络

网络连通


[root@ming ~]# docker run -d -P --name tomcat01 tomcat
4c1558019d2a64e6de048adeaea3cb8032c9d35a6070dbd060bf18ed2e553db4


测试打通tomcat01到mynet

[root@ming ~]# docker network connect mynet tomcat01
[root@ming ~]# docker network inspect mynet
[
    {
        "Name": "mynet",
        "Id": "1b08d9b162842f1aa7ead437518410fa8fb1e4fe28e7755a80ed54d6288971fe",
        "Created": "2020-10-15T19:20:32.948691747+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": {
            "327d40e53e3467287b8a53a474353e66dbce8df25270d3cc69035315bba128c6": {
                "Name": "tomcat01-net",
                "EndpointID": "2633c94ffb5bb3159c4893d0c5b9b72fd0cedbb731aa312024c40811d9d22a67",
                "MacAddress": "02:42:c0:a8:00:02",
                "IPv4Address": "192.168.0.2/16",
                "IPv6Address": ""
            },
            "4c1558019d2a64e6de048adeaea3cb8032c9d35a6070dbd060bf18ed2e553db4": {
                "Name": "tomcat01",
                "EndpointID": "c1699527c0f7216efca12944a9a703e8788934b7a5ab460ec1780919352fadeb",
                "MacAddress": "02:42:c0:a8:00:04",
                "IPv4Address": "192.168.0.4/16",
                "IPv6Address": ""
            },
            "5e1af58d43dc8e86637613257a38a45308c914d2ba7a1902b0cca656f4645de2": {
                "Name": "tomcat02-net",
                "EndpointID": "2c9117b299f2f607784e536eb4a35a81ba2da17b85c80bb284405931e49807f3",
                "MacAddress": "02:42:c0:a8:00:03",
                "IPv4Address": "192.168.0.3/16",
                "IPv6Address": ""
            }
        },
        "Options": {},
        "Labels": {}
    }
]


#连通之后就是将tomcat01 放到了mynet网络下

一个容器两个ip   
阿里云服务 公网ip   私网ip

Redis集群部署实践

分片+高可用+负载均衡

#创建网卡
docker  network create redis --subnet 172.38.0.0/16

#通过脚本创建六个redis配置

for port in $(seq 1 6);\
do \
mkdir -p /mydata/redis/node-${port}/conf
touch /mydata/redis/node-${port}/conf/redis.conf
cat << EOF >/mydata/redis/node-${port}/conf/redis.conf
port 6379
bind 0.0.0.0
cluster-enabled yes
cluster-config-file nodes.conf
cluster-node-timeout 5000
cluster-announce-ip 172.38.0.1${port}
cluster-announce-port 6379
cluster-announce-bus-port 16379
appendonly yes
EOF

 docker run -p 637${port}:6379 -p 1637${port}:16379 --name redis-${port} \
 -v /mydata/redis/node-${port}/data:/data \
 -v /mydata/redis/node-${port}/conf/redis.conf:/etc/redis/redis.conf \
 -d --net redis --ip 172.38.0.1${port} redis:5.0.9-alpine3.11 redis-server /etc/redis/redis.conf
 done

#开启redis服务
docker run -p 6371:6379 -p 16371:16379 --name redis-1 \
 -v /mydata/redis/node-1/data:/data \
 -v /mydata/redis/ndoe-1/conf/redis/conf:/etc/redis/redis.conf \
 -d --net redis --ip 172.38.0.11 redis:5.0.9-alpine3.11 redis-server /etc/redis/redis.conf
 
 docker run -p 6372:6379 -p 16372:16379 --name redis-2 \
 -v /mydata/redis/node-2/data:/data \
 -v /mydata/redis/ndoe-2/conf/redis/conf:/etc/redis/redis.conf \
 -d --net redis --ip 172.38.0.12 redis:5.0.9-alpine3.11 redis-server /etc/redis/redis.conf
 
 docker run -p 6373:6379 -p 16373:16379 --name redis-3 \
 -v /mydata/redis/node-3/data:/data \
 -v /mydata/redis/ndoe-3/conf/redis/conf:/etc/redis/redis.conf \
 -d --net redis --ip 172.38.0.13 redis:5.0.9-alpine3.11 redis-server /etc/redis/redis.conf
 
  docker run -p 6374:6379 -p 16374:16379 --name redis-4 \
 -v /mydata/redis/node-4/data:/data \
 -v /mydata/redis/ndoe-4/conf/redis/conf:/etc/redis/redis.conf \
 -d --net redis --ip 172.38.0.14 redis:5.0.9-alpine3.11 redis-server /etc/redis/redis.conf
 
   docker run -p 6375:6379 -p 16375:16379 --name redis-5 \
 -v /mydata/redis/node-5/data:/data \
 -v /mydata/redis/ndoe-5/conf/redis/conf:/etc/redis/redis.conf \
 -d --net redis --ip 172.38.0.15 redis:5.0.9-alpine3.11 redis-server /etc/redis/redis.conf
 
   docker run -p 6376:6379 -p 16376:16379 --name redis-6 \
 -v /mydata/redis/node-6/data:/data \
 -v /mydata/redis/ndoe-6/conf/redis/conf:/etc/redis/redis.conf \
 -d --net redis --ip 172.38.0.16 redis:5.0.9-alpine3.11 redis-server /etc/redis/redis.conf
 
 
 #创建集群
 
[root@ming 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
 
 [root@ming ~]# docker exec -it redis-1 /bin/sh
/data # redis-cli --cluster create 172.38.0.11:6379 172.38.0.12:6379 172.38.0.13:6379 172.38.0.14:6379 172.38.0.15:6379 172.38.0.16:6379 --c
luster-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: 2bb17ab40a8a5a3c764a6c69e6369d924c7352b0 172.38.0.11:6379
   slots:[0-5460] (5461 slots) master
M: c6edef832b1d1a03e76fa00db2b4599d3e023495 172.38.0.12:6379
   slots:[5461-10922] (5462 slots) master
M: 827a221dd11af32600786d5c734265625ca69623 172.38.0.13:6379
   slots:[10923-16383] (5461 slots) master
S: e21625f61d229c1421fe9e32e0e641bd374a8a36 172.38.0.14:6379
   replicates 827a221dd11af32600786d5c734265625ca69623
S: caf37cab4710b5fa6cb77250665b2c98aa16710e 172.38.0.15:6379
   replicates 2bb17ab40a8a5a3c764a6c69e6369d924c7352b0
S: f633f5eddc84a3884dab556080fe526673d86e14 172.38.0.16:6379
   replicates c6edef832b1d1a03e76fa00db2b4599d3e023495
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: 2bb17ab40a8a5a3c764a6c69e6369d924c7352b0 172.38.0.11:6379
   slots:[0-5460] (5461 slots) master
   1 additional replica(s)
S: e21625f61d229c1421fe9e32e0e641bd374a8a36 172.38.0.14:6379
   slots: (0 slots) slave
   replicates 827a221dd11af32600786d5c734265625ca69623
S: f633f5eddc84a3884dab556080fe526673d86e14 172.38.0.16:6379
   slots: (0 slots) slave
   replicates c6edef832b1d1a03e76fa00db2b4599d3e023495
M: 827a221dd11af32600786d5c734265625ca69623 172.38.0.13:6379
   slots:[10923-16383] (5461 slots) master
   1 additional replica(s)
S: caf37cab4710b5fa6cb77250665b2c98aa16710e 172.38.0.15:6379
   slots: (0 slots) slave
   replicates 2bb17ab40a8a5a3c764a6c69e6369d924c7352b0
M: c6edef832b1d1a03e76fa00db2b4599d3e023495 172.38.0.12:6379
   slots:[5461-10922] (5462 slots) master
   1 additional replica(s)
[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:144
cluster_stats_messages_pong_sent:137
cluster_stats_messages_sent:281
cluster_stats_messages_ping_received:132
cluster_stats_messages_pong_received:144
cluster_stats_messages_meet_received:5
cluster_stats_messages_received:281
127.0.0.1:6379> 

#三组三从
127.0.0.1:6379> cluster nodes
e21625f61d229c1421fe9e32e0e641bd374a8a36 172.38.0.14:6379@16379 slave 827a221dd11af32600786d5c734265625ca69623 0 1602765509551 4 connected
f633f5eddc84a3884dab556080fe526673d86e14 172.38.0.16:6379@16379 slave c6edef832b1d1a03e76fa00db2b4599d3e023495 0 1602765508949 6 connected
2bb17ab40a8a5a3c764a6c69e6369d924c7352b0 172.38.0.11:6379@16379 myself,master - 0 1602765509000 1 connected 0-5460
827a221dd11af32600786d5c734265625ca69623 172.38.0.13:6379@16379 master - 0 1602765509551 3 connected 10923-16383
caf37cab4710b5fa6cb77250665b2c98aa16710e 172.38.0.15:6379@16379 slave 2bb17ab40a8a5a3c764a6c69e6369d924c7352b0 0 1602765508548 5 connected
c6edef832b1d1a03e76fa00db2b4599d3e023495 172.38.0.12:6379@16379 master - 0 1602765508548 2 connected 5461-10922
127.0.0.1:6379> 

127.0.0.1:6379> set a b
-> Redirected to slot [15495] located at 172.38.0.13:6379
OK
172.38.0.13:6379> 

主服务器挂掉,从服务器会替代提供给服务

SpringBoot微服务打包Docker镜像

构建springboot项目

打包应用

编写dockfile

FROM java:8

COPY *.jar /app.jar

CMD ["server.port=8080"]

EXPOSE 8080

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

构建镜像

[root@ming idea]# ls
demo-0.0.1-SNAPSHOT.jar  Dockerfile
[root@ming idea]# docker build -t ming .
Sending build context to Docker daemon  16.55MB
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
 ---> fead3e7ecfe5
Step 3/5 : CMD ["server.port=8080"]
 ---> Running in 0d869aac0f9d
Removing intermediate container 0d869aac0f9d
 ---> ceda02b5b798
Step 4/5 : EXPOSE 8080
 ---> Running in 77eb6d3bbe32
Removing intermediate container 77eb6d3bbe32
 ---> 865ce2b9634b
Step 5/5 : ENTRYPOINT ["java","-jar","/app.jar"]
 ---> Running in 6585db33831c
Removing intermediate container 6585db33831c
 ---> 4fa29333c05e
Successfully built 4fa29333c05e
Successfully tagged ming:latest




[root@ming idea]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
ming                latest              4fa29333c05e        20 seconds ago      660MB
redis               latest              bd571e6529f3        39 hours ago        104MB
tomcat              latest              f796d3d2c195        4 weeks ago         647MB
redis               5.0.9-alpine3.11    3661c84ee9d0        5 months ago        29.8MB
java                8                   d23bdf5b1b1b        3 years ago         643MB

docker logs 容器id 查看容器运行情况包括错误

发布运行

posted @ 2020-10-10 22:38  yourText  阅读(930)  评论(0编辑  收藏  举报