- 一、Docker入门
- 扫描本地有无镜像信息
- 远程拉取hello-world
- 显示拉取镜像的签名信息
- Docker运行成功
- 1.2.3、离线安装
- 1.3、Docker运行原理
- 1.4、配置镜像加速器
- 1.5、Docker命令的使用
- 解释
- REPOSITORY # 镜像的仓库源
- TAG # 镜像的标签
- IMAGE ID # 镜像的id
- CREATED # 镜像的创建时间
- SIZE # 镜像的大小
- 可选项
- 下载镜像 docker pull 镜像名[:tag]
- 如果存在 就会分层下载(增量更新): docker image 的核心 联合文件系统
- 等价于
- 设置tomcat容器开机自启动,只要docker不被关闭或停止 tomcat将一直运行
- 容器挂载:将容器和本地文件佳双向绑定,进行数据同步操作
- 开启tomcat容器 命名为tomcat 将tomcat容器目录/usr/local/tomcat/webapps挂载到本地目录/usr/local/dev/docker/tomcat/webapps上 并设置开机自启动
- 创建容器
- 运行容器
- 参书说明
- 测试、启动并进入容器
- 显示日志
- docker exec -it 容器id /bin/bash
- docker attach 容器id
- 区别
- docker exec #进入当前容器后开启一个新的终端,可以在里面操作。(常用)
- docker attach # 进入容器正在执行的终端
- 二、Docker实践整合
- 出现以下内容即Nginx部署成功
- 问题1:镜像驱动链路中不存在该容器
- 解决方法:重启Docker服务
- 问题2:镜像容器名称或ID冲突
- 解决方法:删除当前镜像容器名称或id
- 不显示tomcat主页的原因:
- 解决方法
- 1、进入镜像容器
- 2、进入webapps文件夹后里面没有文件,这就是不显示主页的原因
- 3、进入webapps.dist文件
- 4、将webapps.dist下的文件拷贝到webapps下就可以访问了
- 5、查看webapps文件下内容
- 6、刷新网页
- 直接部署,不用获取镜像
- 部署ES会暴露很多端口,需要挂载安全目录和设置网络
- ES及其耗内存,会让整个Docker镜像变得十分卡顿
- 查看CPU消耗情况
- 内存的占用情况 1.06GiB / 1.694GiB ,这就是导致卡顿的原因
- -e 限制内存(64,512),修改内置
- 内村限流的效果 399.9MiB / 1.694GiB
- 2.2、镜像原理
- 2.3、容器数据卷
- 直接使用命令挂载
- 挂载前
- 挂载后
- 查看挂载情况
- 关闭容器
- 在主机目录下编辑test.java
- 启动容器
- 进入正在运行的容器
- 进入容器下的home目录
- 查看文件内容
- 同步成功
- 在容器中编辑test.java
- 若在容器中不能使用vi/vim编辑
- 更新来源
- 安装vim
- 编辑
- 在主机目录下查看文件内容
- 同步成功
- 删除容器
- 进入主机目录查看文件内容
- 删除容器后,挂载到本地的镜像还在,并且数据不变,持久化保存数据得以实现
- -v 卷名:容器内路径
- 查看本地的匿名卷的挂载
- 查看容器卷的具体路径
- 查看容器卷具体文件
- 查看本地卷名
- 查看数据卷所有文件
- 查看数据卷的配置文件
- 读写权限的使用
- 一旦设置了容器权限,挂载内容的操作就被限定了
- 以交互形式启动hg/centos
- 容器中新建文件
- 在docker-dev/volume01下创建文件
- 在docker-dev-02/volume01下查看文件
- 在docker-dev-02/volume01下创建文件
- 在docker-dev/volume01下查看文件
- 实现docker-dev与docker-dev-02数据同步并且持久化保存
- 底层镜像依赖
- 导入centos7的镜像
- 导入基础镜像依赖
- 镜像开发者 姓名+邮箱
- 变量的环境目录
- 工作目录
- 添加需要执行的功能命令
- 暴露在网络中的端口号
- 输出构建信息
- 从/bin/bash启动
- 显示本地镜像——未构建镜像时
- 启动镜像
- 显示本地镜像——构建镜像后
- 启动自定义构建的镜像
- 新加功能
- 2.4、网络连接及镜像发布
- 启动第一个tomcat容器
- 查看网络地址状态
- docker分配第一个随机地址
- 启动第二个tomcat容器
- 查看网络地址状态
- #docker分配第二个随机地址
- 每启动一个容器,就会多一个docker分配的IP
- docker分配的IP地址
- 并且每一个分配的IP都能在本地或者公网ping通,也能连接
- 两个容器之间也能相互ping/连接
- 显然是不想的,那在docker分配地址过多时,该如何通过容器名相互来连接容器呢,下面开始揭晓答案
- tomcat-02 /etc/hosts
- tomcat-03 /etc/hosts
- link在tomcat-03配置中新增了tomcat-02的网络地址172.17.0.3 tomcat-02 0512270151f0,并且时固定的,这导致了tomcat-03只能连接tomcat-02
- 启动自定义网络的容器
- 通过IP地址连接容器
- 通过域名连接容器
- 三、Docker核心技术
- 3.2、Compose的使用
- 下载地址
- 授权
- 镜像加速地址,建议使用
- 授权
- 整个配置可以分为3层
- 第一层,版本信息
- 第二层,服务
- 第三层,其他配置 网络/卷、全局规则
- 1、在home目录下创建compose文件夹
- 2、创建一个文件app.py,就是创建一个python文件
- app.py文件内容
- 3、创建导入依赖包
- 1、创建Dockerfile
- 1、在compose文件中定义service
- version太新会报错,将版本降低就可以了
- 1、构建并运行服务
- 3.3、集群搭建
Docker
一、Docker入门
1.1、Docker概述
- Docker是内核级别的虚拟化容器引擎,性能可以被压榨到机制。
- Docker 是一个开源的应用容器引擎,让开发者可以打包他们的应用以及依赖包到一个可移植的镜像中,然后发布到任何流行的 Linux或Windows 机器上,也可以实现虚拟化。容器是完全使用沙箱机制,相互之间不会有任何接口。
- 一个完整的Docker有以下几个部分组成:
- DockerClient客户端
- Docker Daemon守护进程
- Docker Image镜像
- DockerContainer容器
- Docker 是 PaaS 提供商 dotCloud 开源的一个基于 LXC 的高级容器引擎,源代码托管在 Github 上, 基于go语言并遵从Apache2.0协议开源。
Docker 使用客户端-服务器 (C/S) 架构模式,使用远程API来管理和创建Docker容器。Docker 容器通过 Docker 镜像来创建。容器与镜像的关系类似于面向对象编程中的对象与类。
| Docker | 面向对象 | | —- | —- | | 容器 | 对象 | | 镜像 | 类 |Docker采用 C/S架构 Docker daemon 作为服务端接受来自客户的请求,并处理这些请求(创建、运行、分发容器)。 客户端和服务端既可以运行在一个机器上,也可通过 socket 或者RESTful API 来进行通信。
Docker daemon 一般在宿主主机后台运行,等待接收来自客户端的消息。 Docker 客户端则为用户提供一系列可执行命令,用户用这些命令实现跟 Docker daemon 交互。
- Docker的特点
- 隔离性:容器是在运行在镜像中的,而镜像是独立在操作系统的内核上运行的,这就是Docker的运行效率大大提高
- 移动性 :实例可以很方便地复制、移动和重建。整套镜像的移植让部署变得十分轻便
- 安全性:Docker实现虚拟化,容器是完全使用沙箱机制,相互之间不会有任何接口,极大的降低了耦合性,同时也提高了安全性。
1.2、安装Docker
1.2.1、环境准备
- 环境依赖
- CentOS 7
- 系统内核3.0.0以上
- 查看环境
[root@hg14150 /]# uname -r
3.10.0-1160.15.2.el7.x86_64
- 系统环境 ```shell [root@hg14150 /]# 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”
- 下载安装镜像<br />[Docker下载地址](https://docs.docker.com/engine/install/)<br />![](https://gitee.com/hg14150/blogiamges/raw/master/img/image-20210505182326222.png#crop=0&crop=0&crop=1&crop=1&id=ZrO4v&originHeight=677&originWidth=1771&originalType=binary&ratio=1&rotation=0&showTitle=false&status=done&style=none&title=)
<a name="a1ce48a5"></a>
#### 1.2.2、联网安装
<a name="dffce0b6"></a>
##### 1、卸载系统中存在的Docker
```shell
yum remove docker \
docker-client \
docker-client-latest \
docker-common \
docker-latest \
docker-latest-logrotate \
docker-logrotate \
docker-engine
2、需要的安装yum-utils
yum install -y yum-utils
3、设置镜像仓库
#配置阿里云镜像
yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
4、更新yum软件包的索引
yum makecache fast
5、安装Docker
yum install docker-ce docker-ce-cli containerd.io
6、查询Docker版本
docker version
7、查看Docker
[root@hg14150 /]# docker version
Client: Docker Engine - Community
Version: 20.10.6
API version: 1.41
Go version: go1.13.15
Git commit: 370c289
Built: Fri Apr 9 22:45:33 2021
OS/Arch: linux/amd64
Context: default
Experimental: true
Server: Docker Engine - Community
Engine:
Version: 20.10.6
API version: 1.41 (minimum version 1.12)
Go version: go1.13.15
Git commit: 8728dd2
Built: Fri Apr 9 22:43:57 2021
OS/Arch: linux/amd64
Experimental: false
containerd:
Version: 1.4.3
GitCommit: 269548fa27e0089a8b8278fc4fc781d7f65a939b
runc:
Version: 1.0.0-rc92
GitCommit: ff819c7e9184c13b7c2607fe6c30ae19403a7aff
docker-init:
Version: 0.19.0
GitCommit: de40ad0
8、启动Docker
systemctl start docker
docker run --name nacos -d -p 8848:8848 --privileged=true --restart=always -e JVM_XMS=512m -e JVM_XMX=2048m -e MODE=standalone -e PREFER_HOST_MODE=hostname -v /home/hguo/product/nacos/conf:/home/nacos/conf nacos/nacos-server:1.4.1
9、运行Docker
#运行hello-world
docker run hello-world
- 首次运行,Docker环境中没有镜像,所以会远程拉取运行镜像
```shell
[root@hg14150 /]# systemctl start docker
[root@hg14150 /]# docker run hello-world
扫描本地有无镜像信息
Unable to find image ‘hello-world:latest’ locally远程拉取hello-world
latest: Pulling from library/hello-world显示拉取镜像的签名信息
b8dfde127a29: Pull complete Digest: sha256:f2266cbfc127c960fd30e76b7c792dc23b588c0db76233517e1891a4e357d519 Status: Downloaded newer image for hello-world:latest
Docker运行成功
Hello from Docker! This message shows that your installation appears to be working correctly.
To generate this message, Docker took the following steps:
- The Docker client contacted the Docker daemon.
- The Docker daemon pulled the “hello-world” image from the Docker Hub. (amd64)
- The Docker daemon created a new container from that image which runs the executable that produces the output you are currently reading.
- The Docker daemon streamed that output to the Docker client, which sent it to your terminal.
To try something more ambitious, you can run an Ubuntu container with: $ docker run -it ubuntu bash
Share images, automate workflows, and more with a free Docker ID: https://hub.docker.com/
For more examples and ideas, visit: https://docs.docker.com/get-started/
<a name="00e35fb4"></a>
##### 10、查看拉取信息
```shell
#hello-world镜像信息
[root@hg14150 /]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
hello-world latest d1165f221234 2 months ago 13.3kB
11、卸载Docker
- 1、卸载
yum remove docker-ce docker-ce-cli containerd.io
- 2、移除镜像
rm -rf /var/lib/docker
rm -rf /var/lib/containerd
12、详细步骤
1.2.3、离线安装
1、下载docker离线安装包
//在本地离线下载
https://download.docker.com/linux/static/stable/x86_64/docker-19.03.7.tgz
2、linux上创建安装文件
#在根目录下创建文件/tools/docker
[root@localhost ~]# mkdir -p ~/tools/docker
[root@localhost ~]# cd ~/tools/docker
3、上传并配置docker安装环境
- 将本地离线安装包上传到/root/tools/docker下
4、配置用户组
# 新建用户组
[root@localhost ~]# groupadd docker
# 将登录用户加入到docker用户组中
[root@localhost ~]# usermod -aG docker $USER
# 更新用户组
[root@localhost ~]# newgrp docker
5、安装包解压
[root@localhost ~]# cd ~/tools/docker
[root@localhost docker]# mkdir install-package
# 用于清理
[root@localhost docker]# tar -xf docker-19.03.7.tgz -C install-package --strip-components=1
# 解压安装至/usr/local/bin目录下
[root@localhost docker]# tar -xf docker-19.03.7.tgz -C /usr/local/bin --strip-components=1
6、配置服务
# 修改docker默认存储路径
[root@localhost ~]# mkdir -p ~/data/docker
- 配置docker.service
[root@localhost ~]# vim /etc/systemd/system/docker.service
[Unit]
Description=Docker Application Container Engine
Documentation=https://docs.docker.com
After=network-online.target firewalld.service
Wants=network-online.target
[Service]
Type=notify
# ExecStart的启动可选参数,可通过dockerd --help查看
ExecStart=/usr/local/bin/dockerd -H unix://var/run/docker.sock --data-root=/home/root/data/docker
ExecReload=/bin/kill -s HUP $MAINPID
TimeoutSec=0
RestartSec=2
Restart=always
StartLimitBurst=3
StartLimitInterval=60s
LimitNOFILE=infinity
LimitNPROC=infinity
LimitCORE=infinity
TasksMax=infinity
Delegate=yes
KillMode=process
[Install]
WantedBy=multi-user.target
7、启动docker服务
[root@localhost ~]# systemctl daemon-reload
# 通过systemctl启动docker服务
[root@localhost ~]# systemctl start docker
# 设置为开机启动
[root@localhost ~]# systemctl enable docker
# 验证开放2375端口,若开放了,建议把2375端口关掉
[root@localhost ~]# netstat -lntp | grep dockerd
8、测试运行docker
[root@localhost ~]# docker run hello-world
9、查看docker
[root@localhost /]# docker version
Client: Docker Engine - Community
Version: 19.03.7
API version: 1.40
Go version: go1.12.17
Git commit: 7141c199a2
Built: Wed Mar 4 01:19:42 2020
OS/Arch: linux/amd64
Experimental: false
Server: Docker Engine - Community
Engine:
Version: 19.03.7
API version: 1.40 (minimum version 1.12)
Go version: go1.12.17
Git commit: 7141c199a2
Built: Wed Mar 4 01:19:50 2020
OS/Arch: linux/amd64
Experimental: false
containerd:
Version: v1.2.13
GitCommit: 7ad184331fa3e55e52b890ea95e65ba581ae3429
runc:
Version: 1.0.0-rc10
GitCommit: dc9208a3303feef5b3839f4323d9beb36df0a9dd
docker-init:
Version: 0.18.0
GitCommit: fec3683
10、查看拉取的镜像
[root@localhost /]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
hello-world latest d1165f221234 4 months ago 13.3kB
1.3、Docker运行原理
1、Docker是怎么工作的
- Docker是一个Clent-Server结构的系统,Docker的守护进程运行在主机上,通过Socket从客户端访问
- DockerServer接收Docker-Client指令并执行
- Docker与VM的底层运行
- Docker直接运行在内核系统上,秒级镜像
- VM在内核系统基础上还有自己的镜像系统,分钟级镜像
- Docker与VM和LXC的区别
1.4、配置镜像加速器
1、进入服务器容器镜像服务
2、配置镜像加速器
- 加速地址
https://o4w0izdr.mirror.aliyuncs.com
- CentOS镜像加速配置
#创建docker加速配置文件夹
sudo mkdir -p /etc/docker
#配置镜像
sudo tee /etc/docker/daemon.json <<-'EOF'
{
"registry-mirrors": ["https://o4w0izdr.mirror.aliyuncs.com"]
}
EOF
#重启Docker服务
sudo systemctl daemon-reload
#重启Docker
sudo systemctl restart docker
- 配置过程
1.5、Docker命令的使用
1.5.1、镜像命令
- 帮助命令
docker version #显示docker的版本信息。
docker info #显示docker的系统信息,包括镜像和容器的数量
docker 命令 --help #帮助命令
- 镜像命令
docker images #查看所有本地主机上的镜像 可以使用docker image ls代替
docker search 镜像名/id #搜索镜像
docker pull 镜像名/id docker image pull 镜像名/id #下载镜像
docker rmi 镜像名/id docker image rm 镜像名/id #删除镜像
docker rmi `docker images -q` #删除所有镜像
- docker images 查看所有本地的主机上的镜像 ```shell [root@hg14150 ~]# docker images REPOSITORY TAG IMAGE ID CREATED SIZE hello-world latest d1165f221234 2 months ago 13.3kB
解释
REPOSITORY # 镜像的仓库源
TAG # 镜像的标签
IMAGE ID # 镜像的id
CREATED # 镜像的创建时间
SIZE # 镜像的大小
可选项
Options: -a, —all Show all images (default hides intermediate images) #列出所有镜像 -q, —quiet Only show numeric IDs # 只显示镜像的id
[root@hg14150 ~]# docker images -aq #显示所有镜像的id d1165f221234
- **docker search 搜索镜像**
```shell
[root@hg14150 ~] docker search mysql
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
mysql MySQL is a widely used, open-source relation… 9500 [OK]
mariadb MariaDB is a community-developed fork of MyS… 3444 [OK]
# --filter=STARS=3000 #搜索出来的镜像就是STARS大于3000的
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@hg14150 ~] docker search mysql --filter=STARS=3000
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
mysql MySQL is a widely used, open-source relation… 9500 [OK]
mariadb MariaDB is a community-developed fork of MyS… 3444 [OK]
- docker pull 下载镜像
```shell
下载镜像 docker pull 镜像名[:tag]
[root@hg14150 ~]# docker pull java:8 8: Pulling from library/java #如果不写tag,默认就是latest如果存在 就会分层下载(增量更新): docker image 的核心 联合文件系统
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 docker.io/library/java:8 #下载的真实地址
等价于
docker pull java:8 docker pull docker.io/library/java:8
- **docker rmi 删除镜像**
```shell
[root@hg14150 ~] docker rmi -f 镜像id #删除指定的镜像
[root@hg14150 ~] docker rmi -f 镜像id 镜像id 镜像id 镜像id#删除指定的镜像
[root@hg14150 ~] docker rmi -f $(docker images -aq) #删除全部的镜像
1.5.2、容器命令
- 常用容器命令
```shell
docker run 镜像id 新建容器并启动
docker ps 列出所有运行的容器 docker container list
docker rm 容器id 删除指定容器
docker start 容器id #启动容器
docker restart 容器id #重启容器
docker stop 容器id #停止当前正在运行的容器
docker kill 容器id #强制停止当前容器
—restart=always #容器开机自启动
docker run -d -p 8088:8080 —name tomcat —restart=always tomcat:5.7
设置tomcat容器开机自启动,只要docker不被关闭或停止 tomcat将一直运行
容器挂载:将容器和本地文件佳双向绑定,进行数据同步操作
docker run -d -p 8088:8080 —name tomcat -v /usr/local/dev/docker/tomcat/webapps:/usr/local/tomcat/webapps —restart=always tomcat
开启tomcat容器 命名为tomcat 将tomcat容器目录/usr/local/tomcat/webapps挂载到本地目录/usr/local/dev/docker/tomcat/webapps上 并设置开机自启动
- 有了镜像才可以创建容器,用面向对象的思想来解释就是,镜像是类,容器时对象
```shell
[root@hg14150 ~] docker container
Usage: docker container COMMAND
Manage containers
Commands:
attach Attach local standard input, output, and error streams to a running container
commit Create a new image from a container's changes
cp Copy files/folders between a container and the local filesystem
create Create a new container
diff Inspect changes to files or directories on a container's filesystem
exec Run a command in a running container
export Export a container's filesystem as a tar archive
inspect Display detailed information on one or more containers
kill Kill one or more running containers
logs Fetch the logs of a container
ls List containers
pause Pause all processes within one or more containers
port List port mappings or a specific mapping for the container
prune Remove all stopped containers
rename Rename a container
restart Restart one or more containers
rm Remove one or more containers
run Run a command in a new container
start Start one or more stopped containers
stats Display a live stream of container(s) resource usage statistics
stop Stop one or more running containers
top Display the running processes of a container
unpause Unpause all processes within one or more containers
update Update configuration of one or more containers
wait Block until one or more containers stop, then print their exit codes
Run 'docker container COMMAND --help' for more information on a command.
- 创建容器并启动
```shell
创建容器
[root@hg14150 ~]# docker pull centos:7 7: Pulling from library/centos 2d473b07cdd5: Pull complete Digest: sha256:0f4ec88e21daf75124b8a9e5ca03c37a5e937e0e108a255d890492430789b60e Status: Downloaded newer image for centos:7 docker.io/library/centos:7
运行容器
docker run [可选参数] image | docker container run [可选参数] image ——docker run —help
参书说明
—name=”Name” 容器名字 tomcat01 tomcat02 用来区分容器 -d 后台方式运行 -it 使用交互方式运行,进入容器查看内容 -p 指定容器的端口 -p 8080(宿主机):8080(容器) -p ip:主机端口:容器端口 -p 主机端口:容器端口(常用) -p 容器端口 容器端口 -P(大写) 随机指定端口
测试、启动并进入容器
[root@hg14150 /]# docker run -it centos:7 /bin/bash #交互模式启动容器 [root@911c84ad4081 /]# ll total 56 -rw-r—r— 1 root root 12114 Nov 13 01:55 anaconda-post.log lrwxrwxrwx 1 root root 7 Nov 13 01:53 bin -> usr/bin drwxr-xr-x 5 root root 360 May 6 02:42 dev drwxr-xr-x 1 root root 4096 May 6 02:42 etc drwxr-xr-x 2 root root 4096 Apr 11 2018 home lrwxrwxrwx 1 root root 7 Nov 13 01:53 lib -> usr/lib lrwxrwxrwx 1 root root 9 Nov 13 01:53 lib64 -> usr/lib64 drwxr-xr-x 2 root root 4096 Apr 11 2018 media drwxr-xr-x 2 root root 4096 Apr 11 2018 mnt drwxr-xr-x 2 root root 4096 Apr 11 2018 opt dr-xr-xr-x 115 root root 0 May 6 02:42 proc dr-xr-x—- 2 root root 4096 Nov 13 01:55 root drwxr-xr-x 11 root root 4096 Nov 13 01:55 run lrwxrwxrwx 1 root root 8 Nov 13 01:53 sbin -> usr/sbin drwxr-xr-x 2 root root 4096 Apr 11 2018 srv dr-xr-xr-x 13 root root 0 May 6 02:42 sys drwxrwxrwt 7 root root 4096 Nov 13 01:55 tmp drwxr-xr-x 13 root root 4096 Nov 13 01:53 usr drwxr-xr-x 18 root root 4096 Nov 13 01:54 var [root@95039813da8d /]# exit #从容器退回主机 exit [root@hg14150 ~] ll shell user.txt
- **显示所有运行的容器**
```shell
#docker ps 命令 #列出当前正在运行的容器
-a, --all Show all containers (default shows just running)
-n, --last int Show n last created containers (includes all states) (default -1)
-q, --quiet Only display numeric IDs
#显示正在运行的容器
[root@hg14150 /]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
#显示容器运行记录
[root@hg14150 /]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
911c84ad4081 centos:7 "/bin/bash" 3 minutes ago Exited (0) 34 seconds ago hungry_bassi
4587400755b1 hello-world "/hello" 16 hours ago Exited (0) 16 hours ago serene_morse
#显示运行容器ID
[root@hg14150 /]# docker ps -aq
911c84ad4081
4587400755b1
- 退出容器
exit #容器直接退出
ctrl +P +Q #容器不停止退出 (大写)
- 删除容器
docker rm 容器id #删除指定的容器,不能删除正在运行的容器
dockers rm -rf 容器id #强制删除运行容器
docker rm -f $(docker ps -aq) #删除指定的容器
docker ps -a -q|xargs docker rm #删除所有的容器
docker rm `docker ps -a -q` #删除所有容器
- 启动和停止容器的操作
docker start 容器id #启动容器
docker restart 容器id #重启容器
docker stop 容器id #停止当前正在运行的容器
docker kill 容器id #强制停止当前容器
docker stop `docker ps -a -q` #批量停止容器
1.5.3、其他命令
后台启动命令
#以后台方式启动镜像: docker run -d 镜像名
[root@hg14150 /]# docker run -d centos
#以交互方式启动镜像: docker run -it 镜像名
[root@hg14150 /]# docker run -it centos
a8f922c255859622ac45ce3a535b7a0e8253329be4756ed6e32265d2dd2fac6c
[root@hg14150 /]#docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
# 问题docker ps. 发现centos 停止了
# 常见的坑,docker容器使用后台运行,就必须要有要一个前台进程,docker发现没有应用,就会自动停止
# nginx,容器启动后,发现自己没有提供服务,就会立刻停止,就是没有程序了
- 查看日志
```shell
[root@hg14150 /]# docker logs —help
Usage: docker logs [OPTIONS] CONTAINER
Fetch the logs of a container
Options:
—details Show extra details provided to logs
-f, —follow Follow log output
—since string Show logs since timestamp (e.g. 2013-01-02T13:23:37Z) or relative (e.g.
-n, —tail string Number of lines to show from the end of the logs (default “all”) -t, —timestamps Show timestamps42m for 42 minutes)
[root@hg14150 /]#docker run -d centos /bin/sh -c “while true;do echo 6666;sleep 1;done” #模拟日志
显示日志
-tf #显示日志信息(一直更新) —tail number #需要显示日志条数 docker logs -t —tail n 容器id #查看n行日志 docker logs -ft 容器id #跟着日志
- **查看容器进程信息**
```shell
#docker top 容器id
[root@hg14150 /]# docker top a34419f0d1
UID PID PPID C STIME TTY TIME CMD
root 8640 8619 0 11:07 pts/0 00:00:00 /bin/bash
- 查看镜像元数据
# docker inspect 容器id
[root@hg14150 /]# docker inspect a34419f0d1f4
[
{
"Id": "a34419f0d1f4fa238dd813ce6238515fb34166186314a07c682ed02edc2c34e3",
"Created": "2021-05-06T02:51:09.437846944Z",
"Path": "/bin/bash",
"Args": [],
"State": {
"Status": "running",
"Running": true,
"Paused": false,
"Restarting": false,
"OOMKilled": false,
"Dead": false,
"Pid": 8640,
"ExitCode": 0,
"Error": "",
"StartedAt": "2021-05-06T03:07:14.033489573Z",
"FinishedAt": "2021-05-06T02:57:26.619482079Z"
},
"Image": "sha256:8652b9f0cb4c0599575e5a003f5906876e10c1ceb2ab9fe1786712dac14a50cf",
"ResolvConfPath": "/www/server/docker/containers/a34419f0d1f4fa238dd813ce6238515fb34166186314a07c682ed02edc2c34e3/resolv.conf",
"HostnamePath": "/www/server/docker/containers/a34419f0d1f4fa238dd813ce6238515fb34166186314a07c682ed02edc2c34e3/hostname",
"HostsPath": "/www/server/docker/containers/a34419f0d1f4fa238dd813ce6238515fb34166186314a07c682ed02edc2c34e3/hosts",
"LogPath": "/www/server/docker/containers/a34419f0d1f4fa238dd813ce6238515fb34166186314a07c682ed02edc2c34e3/a34419f0d1f4fa238dd813ce6238515fb34166186314a07c682ed02edc2c34e3-json.log",
"Name": "/lucid_hamilton",
"RestartCount": 0,
"Driver": "overlay2",
"Platform": "linux",
"MountLabel": "",
"ProcessLabel": "",
"AppArmorProfile": "",
"ExecIDs": null,
"HostConfig": {
"Binds": null,
"ContainerIDFile": "",
"LogConfig": {
"Type": "json-file",
"Config": {}
},
"NetworkMode": "default",
"PortBindings": {},
"RestartPolicy": {
"Name": "no",
"MaximumRetryCount": 0
},
"AutoRemove": false,
"VolumeDriver": "",
"VolumesFrom": null,
"CapAdd": null,
"CapDrop": null,
"CgroupnsMode": "host",
"Dns": [],
"DnsOptions": [],
"DnsSearch": [],
"ExtraHosts": null,
"GroupAdd": null,
"IpcMode": "private",
"Cgroup": "",
"Links": null,
"OomScoreAdj": 0,
"PidMode": "",
"Privileged": false,
"PublishAllPorts": false,
"ReadonlyRootfs": false,
"SecurityOpt": null,
"UTSMode": "",
"UsernsMode": "",
"ShmSize": 67108864,
"Runtime": "runc",
"ConsoleSize": [
0,
0
],
"Isolation": "",
"CpuShares": 0,
"Memory": 0,
"NanoCpus": 0,
"CgroupParent": "",
"BlkioWeight": 0,
"BlkioWeightDevice": [],
"BlkioDeviceReadBps": null,
"BlkioDeviceWriteBps": null,
"BlkioDeviceReadIOps": null,
"BlkioDeviceWriteIOps": null,
"CpuPeriod": 0,
"CpuQuota": 0,
"CpuRealtimePeriod": 0,
"CpuRealtimeRuntime": 0,
"CpusetCpus": "",
"CpusetMems": "",
"Devices": [],
"DeviceCgroupRules": null,
"DeviceRequests": null,
"KernelMemory": 0,
"KernelMemoryTCP": 0,
"MemoryReservation": 0,
"MemorySwap": 0,
"MemorySwappiness": null,
"OomKillDisable": false,
"PidsLimit": null,
"Ulimits": null,
"CpuCount": 0,
"CpuPercent": 0,
"IOMaximumIOps": 0,
"IOMaximumBandwidth": 0,
"MaskedPaths": [
"/proc/asound",
"/proc/acpi",
"/proc/kcore",
"/proc/keys",
"/proc/latency_stats",
"/proc/timer_list",
"/proc/timer_stats",
"/proc/sched_debug",
"/proc/scsi",
"/sys/firmware"
],
"ReadonlyPaths": [
"/proc/bus",
"/proc/fs",
"/proc/irq",
"/proc/sys",
"/proc/sysrq-trigger"
]
},
"GraphDriver": {
"Data": {
"LowerDir": "/www/server/docker/overlay2/8c827b3094cc17b877825febfd9a6692ff033c57648268281f638a4afe0c4c7c-init/diff:/www/server/docker/overlay2/3b223d6242e3202e17df0f4dc6b12c446fa76107af063e196210cb224cdc8d35/diff",
"MergedDir": "/www/server/docker/overlay2/8c827b3094cc17b877825febfd9a6692ff033c57648268281f638a4afe0c4c7c/merged",
"UpperDir": "/www/server/docker/overlay2/8c827b3094cc17b877825febfd9a6692ff033c57648268281f638a4afe0c4c7c/diff",
"WorkDir": "/www/server/docker/overlay2/8c827b3094cc17b877825febfd9a6692ff033c57648268281f638a4afe0c4c7c/work"
},
"Name": "overlay2"
},
"Mounts": [],
"Config": {
"Hostname": "a34419f0d1f4",
"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:7",
"Volumes": null,
"WorkingDir": "",
"Entrypoint": null,
"OnBuild": null,
"Labels": {
"org.label-schema.build-date": "20201113",
"org.label-schema.license": "GPLv2",
"org.label-schema.name": "CentOS Base Image",
"org.label-schema.schema-version": "1.0",
"org.label-schema.vendor": "CentOS",
"org.opencontainers.image.created": "2020-11-13 00:00:00+00:00",
"org.opencontainers.image.licenses": "GPL-2.0-only",
"org.opencontainers.image.title": "CentOS Base Image",
"org.opencontainers.image.vendor": "CentOS"
}
},
"NetworkSettings": {
"Bridge": "",
"SandboxID": "ad7906cb701afdc4d0c021cf823d61ccbbf4712a4c9a1a6116a7a7ecb89007c0",
"HairpinMode": false,
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"Ports": {},
"SandboxKey": "/var/run/docker/netns/ad7906cb701a",
"SecondaryIPAddresses": null,
"SecondaryIPv6Addresses": null,
"EndpointID": "0b6f243091561670190be25591bdc1f34bf5ce2deefb53e395640ecef643ca0d",
"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": "537fb959114fa9954aadbfaac8c5ba0cac677ead41aeb92763ca51295be05207",
"EndpointID": "0b6f243091561670190be25591bdc1f34bf5ce2deefb53e395640ecef643ca0d",
"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
}
}
}
}
]
- 进入正在运行的容器
```shell
##方式一:
docker exec -it 容器id /bin/bash
[root@hg14150 /]# docker exec -it a34419f0d1f4 /bin/bash [root@a34419f0d1f4 /]# ll total 56 -rw-r—r— 1 root root 12114 Nov 13 01:55 anaconda-post.log lrwxrwxrwx 1 root root 7 Nov 13 01:53 bin -> usr/bin drwxr-xr-x 5 root root 360 May 6 03:07 dev drwxr-xr-x 1 root root 4096 May 6 02:51 etc drwxr-xr-x 2 root root 4096 Apr 11 2018 home lrwxrwxrwx 1 root root 7 Nov 13 01:53 lib -> usr/lib lrwxrwxrwx 1 root root 9 Nov 13 01:53 lib64 -> usr/lib64 drwxr-xr-x 2 root root 4096 Apr 11 2018 media drwxr-xr-x 2 root root 4096 Apr 11 2018 mnt drwxr-xr-x 2 root root 4096 Apr 11 2018 opt dr-xr-xr-x 115 root root 0 May 6 03:07 proc dr-xr-x—- 2 root root 4096 Nov 13 01:55 root drwxr-xr-x 11 root root 4096 Nov 13 01:55 run lrwxrwxrwx 1 root root 8 Nov 13 01:53 sbin -> usr/sbin drwxr-xr-x 2 root root 4096 Apr 11 2018 srv dr-xr-xr-x 13 root root 0 May 6 02:42 sys drwxrwxrwt 7 root root 4096 Nov 13 01:55 tmp drwxr-xr-x 13 root root 4096 Nov 13 01:53 usr drwxr-xr-x 18 root root 4096 Nov 13 01:54 var
[root@a34419f0d1f4 /]# ps -ef UID PID PPID C STIME TTY TIME CMD root 1 0 0 03:07 pts/0 00:00:00 /bin/bash root 15 0 0 03:15 pts/1 00:00:00 /bin/bash root 30 15 0 03:17 pts/1 00:00:00 ps -ef
##方式二:
docker attach 容器id
[root@hg14150 /]# docker attach a34419f0d1f4 [root@hg14150 /]# docker attach a34419f0d1f4 [root@a34419f0d1f4 /]# ll total 56 -rw-r—r— 1 root root 12114 Nov 13 01:55 anaconda-post.log lrwxrwxrwx 1 root root 7 Nov 13 01:53 bin -> usr/bin drwxr-xr-x 5 root root 360 May 6 03:19 dev drwxr-xr-x 1 root root 4096 May 6 02:51 etc drwxr-xr-x 2 root root 4096 Apr 11 2018 home lrwxrwxrwx 1 root root 7 Nov 13 01:53 lib -> usr/lib lrwxrwxrwx 1 root root 9 Nov 13 01:53 lib64 -> usr/lib64 drwxr-xr-x 2 root root 4096 Apr 11 2018 media drwxr-xr-x 2 root root 4096 Apr 11 2018 mnt drwxr-xr-x 2 root root 4096 Apr 11 2018 opt dr-xr-xr-x 117 root root 0 May 6 03:19 proc dr-xr-x—- 1 root root 4096 May 6 03:18 root drwxr-xr-x 11 root root 4096 Nov 13 01:55 run lrwxrwxrwx 1 root root 8 Nov 13 01:53 sbin -> usr/sbin drwxr-xr-x 2 root root 4096 Apr 11 2018 srv dr-xr-xr-x 13 root root 0 May 6 02:42 sys drwxrwxrwt 7 root root 4096 Nov 13 01:55 tmp drwxr-xr-x 13 root root 4096 Nov 13 01:53 usr drwxr-xr-x 18 root root 4096 Nov 13 01:54 var
[root@a34419f0d1f4 /]# ps -ef UID PID PPID C STIME TTY TIME CMD root 1 0 0 03:19 pts/0 00:00:00 /bin/bash root 16 1 0 03:22 pts/0 00:00:00 ps -ef
#
区别
docker exec #进入当前容器后开启一个新的终端,可以在里面操作。(常用)
docker attach # 进入容器正在执行的终端
- **从容器内拷贝文件到主机**
```shell
#docker cp 容器id:容器内路径 主机目的路径
#进入docker容器内部
[root@hg14150 /] docker exec -it 55321bcae33d /bin/bash
[root@55321bcae33d /]# ls
bin etc lib lost+found mnt proc run srv tmp var
dev home lib64 media opt root sbin sys usr
#新建一个文件
[root@55321bcae33d /]# echo "hello" > java.java
[root@55321bcae33d /]# cat java.java
hello
[root@55321bcae33d /]# exit
exit
[root@hg14150 /]docker cp 55321bcae33d:/java.java / #拷贝
[root@hg14150 /] cd /
[root@hg14150 /] ls #可以看见java.java存在
bin home lib mnt run sys vmlinuz
boot initrd.img lib64 opt sbin tmp vmlinuz.old
dev initrd.img.old lost+found proc srv usr wget-log
etc java.java media root swapfile var
#######
#1、在主机上新建一个文件夹用于存放待拷贝的文件
#2、进入需要拷贝文件的容器,新建或找到待拷贝的文件
#3、执行拷贝 将id为55321bcae33d容器中home目录下的test.java复制到主机文件home文件夹下
[root@hg14150 /]docker cp 55321bcae33d:/home/test.java /home
1.5.4、小结
运行命令解析
attach #当前shell下 attach连接指定运行的镜像
build #通过Dockerfile定制镜像
commit #提交当前容器为新的镜像
cp #拷贝文件
create #创建一个新的容器
diff #查看docker容器的变化
events #从服务获取容器实时时间
exec #在运行中的容器上运行命令
export #导出容器文件系统作为一个tar归档文件[对应import]
history #展示一个镜像形成历史
images #列出系统当前的镜像
import #从tar包中导入内容创建一个文件系统镜像
info #显示全系统信息
inspect #查看容器详细信息
kill #kill指定docker容器
load #从一个tar包或标准输入中加载一个镜像[对应save]
login #登录Docker注册表
logout #从Docker注册表注销
logs #读取容器日志
pause #暂停一个或多个容器中的所有进程
port #列出端口映射或容器的特定映射
ps #列出容器
pull #从注册表中提取镜像或存储库
push #将镜像或存储库推送到注册表
rename #重命名容器
restart #重新启动一个或多个容器
rm #移除一个或多个容器
rmi #删除一个或多个图像
run #在新容器中运行命令
save #将一个或多个图像保存到tar存档(默认情况下流式传输到STDOUT)
search #在Docker Hub中搜索镜像
start #启动一个或多个停止的容器
stats #显示容器资源使用统计信息的实时流
stop #停止一个或多个正在运行的容器
tag #创建引用源图像的标记目标图像
top #显示容器的运行进程
unpause #取消暂停一个或多个容器中的所有进程
update #更新一个或多个容器的配置
version #显示Docker版本信息
wait #阻止直到一个或多个容器停止,然后打印其出口代码
二、Docker实践整合
2.1、部署整合
2.1.1、Docker安装mysql
- 拉取MySQL5.7镜像
[root@hg14150 ~]# docker pull mysql:5.7
Using default tag: latest
latest: Pulling from library/mysql:5.7
f7ec5a41d630: Already exists
aa1efa14b3bf: Already exists
b78b95af9b17: Already exists
c7d6bca2b8dc: Already exists
cf16cd8e71e0: Already exists
0241c68333ef: Already exists
Digest: sha256:75a55d33ecc73c2a242450a9f1cc858499d468f077ea942867e662c247b5e412
Status: Downloaded newer image for mysql:5.7
docker.io/library/mysql:5.7
- 开启MySQL容器
#以交互方式启动
#端口映射:3306
#初始化密码: MYSQL_ROOT_PASSWORD=123456
#指定镜像版本:mysql5.7
[root@localhost /]# docker run --name=mysql -itd -p 3306:3306 -e MYSQL_ROOT_PASSWORD=123456 mysql5.7
查询容器
docker ps -a
进入MySQL环境
[root@localhost /]# docker exec -it mysql /bin/bash
root@14464d16d4f0:/# mysql -uroot -p123456
本地连接
2.1.2、Docker部署Nginx
- 下载Nginx镜像
[root@hg14150 ~]# docker pull nginx
Using default tag: latest
latest: Pulling from library/nginx
f7ec5a41d630: Already exists
aa1efa14b3bf: Already exists
b78b95af9b17: Already exists
c7d6bca2b8dc: Already exists
cf16cd8e71e0: Already exists
0241c68333ef: Already exists
Digest: sha256:75a55d33ecc73c2a242450a9f1cc858499d468f077ea942867e662c247b5e412
Status: Downloaded newer image for nginx:latest
docker.io/library/nginx:latest
- 重启Docker服务
[root@hg14150 ~]# systemctl restart docker
- 查看镜像列表
[root@hg14150 ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
tomcat latest c0e850d7b9bb 13 days ago 667MB
nginx latest 62d49f9bab67 3 weeks ago 133MB
hello-world latest d1165f221234 2 months ago 13.3kB
centos 7 8652b9f0cb4c 5 months ago 204MB
java 8 d23bdf5b1b1b 4 years ago 643MB
- 启动部署的Nginx
[root@hg14150 ~]# docker run -d --name ngnix-test -p 3344:80 nginx
# -d : 以后台的启动方式启动nginx
# --name : 为部署的Nginx其别名以作区别
# -p : 指定Nginx挂载的端口号 3344:80
#nginx : 启动nginx镜像
- 查看容器
docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
519faf7d8747 nginx "/docker-entrypoint.…" 10 seconds ago Up 9 seconds 0.0.0.0:3344->80/tcp, :::3344->80/tcp ngnix-test
- 本地内网访问Nginx端口
```shell
[root@hg14150 ~]# curl localhost:3344
出现以下内容即Nginx部署成功
<!DOCTYPE html>Welcome to nginx!
If you see this page, the nginx web server is successfully installed and working. Further configuration is required.
For online documentation and support please refer to
nginx.org.
Commercial support is available at
nginx.com.
Thank you for using nginx.
- **公网访问**<br />![](https://gitee.com/hg14150/blogiamges/raw/master/img/image-20210506162725933.png#crop=0&crop=0&crop=1&crop=1&id=x4nHq&originHeight=348&originWidth=1052&originalType=binary&ratio=1&rotation=0&showTitle=false&status=done&style=none&title=)
- **关闭容器**
```shell
#docker stop 容器id
[root@hg14150 ~]# docker stop 519faf7d8747
- Nginx部署原理
- 进入容器
#进入容器
[root@hg14150 ~]# docker exec -it ngnix-test /bin/bash
#查看路径
root@519faf7d8747:/# whereis nginx
nginx: /usr/sbin/nginx /usr/lib/nginx /etc/nginx /usr/share/nginx
#查看文件
root@519faf7d8747:/# cd /etc/nginx
root@519faf7d8747:/etc/nginx# ls
conf.d koi-utf mime.types nginx.conf uwsgi_params
fastcgi_params koi-win modules scgi_params win-utf
- 可能遇到的问题
```shell
#
问题1:镜像驱动链路中不存在该容器
[root@hg14150 ~]# docker run -d —name ngnix-test -p 3344:80 nginx 22381d2e3293693927fdd11ec36922ac27002e872658185daa8702508a49d6da docker: Error response from daemon: driver failed programming external connectivity on endpoint ngnix-test (43463149407fd8c4e7e28bcd302fc632e3d6e78ffd071fdc45453fe7dd54b0f9): (iptables failed: iptables —wait -t nat -A DOCKER -p tcp -d 0/0 —dport 3344 -j DNAT —to-destination 172.17.0.3:80 ! -i docker0: iptables: No chain/target/match by that name. (exit status 1)).解决方法:重启Docker服务
[root@hg14150 ~]# systemctl restart docker
#
问题2:镜像容器名称或ID冲突
[root@hg14150 ~]# docker run -d —name ngnix-test -p 3344:80 nginx docker: Error response from daemon: Conflict. The container name “/ngnix-test” is already in use by container “22381d2e3293693927fdd11ec36922ac27002e872658185daa8702508a49d6da”. You have to remove (or rename) that container to be able to reuse that name. See ‘docker run —help’.
解决方法:删除当前镜像容器名称或id
[root@hg14150 ~]# docker rm 22381d2e3293693927fdd11ec36922ac27002e872658185daa8702508a49d6da
<a name="cfe825bf"></a>
#### 2.1.3、Docker部署Tomcat
- **官网推荐**
```shell
docker run -it rm tomcat:9.0
#用于测试,初期不建议使用
#启动后删除容器,在容器记录中查询不到
- 下载tomcat镜像
docker pull tomcat
- 启动部署tomcat
docker run -d -p 3355:8080 --name tomcat-test tomcat
# -d : 以后台的启动方式启动tomcat-test
# --name : 为部署的tomcat-test其别名以作区别
# -p : 指定tomcat-test挂载的端口号 3344:80
#tomcat : 启动tomcat镜像
解决方法
1、进入镜像容器
[root@hg14150 ~]# docker exec -it tomcat-test /bin/bash root@4868a4ea294a:/usr/local/tomcat# ls -al total 176 drwxr-xr-x 1 root root 4096 Apr 22 23:10 . drwxr-xr-x 1 root root 4096 Apr 22 00:53 .. -rw-r—r— 1 root root 18984 Mar 30 10:29 BUILDING.txt -rw-r—r— 1 root root 5587 Mar 30 10:29 CONTRIBUTING.md -rw-r—r— 1 root root 57092 Mar 30 10:29 LICENSE -rw-r—r— 1 root root 2333 Mar 30 10:29 NOTICE -rw-r—r— 1 root root 3257 Mar 30 10:29 README.md -rw-r—r— 1 root root 6898 Mar 30 10:29 RELEASE-NOTES -rw-r—r— 1 root root 16507 Mar 30 10:29 RUNNING.txt drwxr-xr-x 2 root root 4096 Apr 22 23:10 bin drwxr-xr-x 1 root root 4096 May 6 08:44 conf drwxr-xr-x 2 root root 4096 Apr 22 23:09 lib drwxrwxrwx 1 root root 4096 May 6 08:44 logs drwxr-xr-x 2 root root 4096 Apr 22 23:10 native-jni-lib drwxrwxrwx 2 root root 4096 Apr 22 23:09 temp drwxr-xr-x 2 root root 4096 Apr 22 23:09 webapps drwxr-xr-x 7 root root 4096 Mar 30 10:29 webapps.dist drwxrwxrwx 2 root root 4096 Mar 30 10:29 work
2、进入webapps文件夹后里面没有文件,这就是不显示主页的原因
root@4868a4ea294a:/usr/local/tomcat# cd webapps root@4868a4ea294a:/usr/local/tomcat/webapps# ls
3、进入webapps.dist文件
root@4868a4ea294a:/usr/local/tomcat# cd webapps.dist root@4868a4ea294a:/usr/local/tomcat/webapps.dist# ls -al total 32 drwxr-xr-x 7 root root 4096 Mar 30 10:29 . drwxr-xr-x 1 root root 4096 Apr 22 23:10 .. drwxr-xr-x 3 root root 4096 Apr 22 23:09 ROOT drwxr-xr-x 15 root root 4096 Apr 22 23:09 docs drwxr-xr-x 7 root root 4096 Apr 22 23:09 examples drwxr-xr-x 6 root root 4096 Apr 22 23:09 host-manager drwxr-xr-x 6 root root 4096 Apr 22 23:09 manager
4、将webapps.dist下的文件拷贝到webapps下就可以访问了
root@4868a4ea294a:/usr/local/tomcat# cp -r webapps.dist/* webapps cp: -r not specified; omitting directory ‘webapps.dist/ROOT’ cp: -r not specified; omitting directory ‘webapps.dist/docs’ cp: -r not specified; omitting directory ‘webapps.dist/examples’ cp: -r not specified; omitting directory ‘webapps.dist/host-manager’ cp: -r not specified; omitting directory ‘webapps.dist/manager’
5、查看webapps文件下内容
root@4868a4ea294a:/usr/local/tomcat# cd webapps root@4868a4ea294a:/usr/local/tomcat/webapps# ls -al total 32 drwxr-xr-x 1 root root 4096 May 6 09:03 . drwxr-xr-x 1 root root 4096 Apr 22 23:10 .. drwxr-xr-x 3 root root 4096 May 6 09:03 ROOT drwxr-xr-x 15 root root 4096 May 6 09:03 docs drwxr-xr-x 7 root root 4096 May 6 09:03 examples drwxr-xr-x 6 root root 4096 May 6 09:03 host-manager drwxr-xr-x 6 root root 4096 May 6 09:03 manager
6、刷新网页
<br />![](https://gitee.com/hg14150/blogiamges/raw/master/img/image-20210506170520816.png#crop=0&crop=0&crop=1&crop=1&id=PaVsq&originHeight=507&originWidth=1432&originalType=binary&ratio=1&rotation=0&showTitle=false&status=done&style=none&title=)
- **关闭容器**
```shell
#docker stop 容器id
[root@hg14150 ~]# docker stop 4868a4ea294a
2.1.4、Docker部署ES+Kibana
- 部署ES+Kibana
```shell
直接部署,不用获取镜像
docker run -d —name elasticsearch -p 9200:9200 -p 9300:9300 -e “discovery.type=single-node” elasticsearch:7.6.2
部署ES会暴露很多端口,需要挂载安全目录和设置网络
[root@hg14150 ~]# docker run -d —name elasticsearch -p 9200:9200 -p 9300:9300 -e “discovery.type=single-node” elasticsearch:7.6.2 Unable to find image ‘elasticsearch:7.6.2’ locally 7.6.2: Pulling from library/elasticsearch ab5ef0e58194: Pull complete c4d1ca5c8a25: Pull complete 941a3cc8e7b8: Pull complete 43ec483d9618: Pull complete c486fd200684: Pull complete 1b960df074b2: Pull complete 1719d48d6823: Pull complete Digest: sha256:1b09dbd93085a1e7bca34830e77d2981521a7210e11f11eda997add1c12711fa Status: Downloaded newer image for elasticsearch:7.6.2 d484bd5e65160d07841ba540bb6d8c3600b6a1fa9be1e7480b526abd0274dcda
ES及其耗内存,会让整个Docker镜像变得十分卡顿
查看CPU消耗情况
[root@hg14150 ~]#docker stats CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS d484bd5e6516 elasticsearch 0.47% 1.06GiB / 1.694GiB 62.57% 656B / 0B 6.31GB / 34.5MB 42
内存的占用情况 1.06GiB / 1.694GiB ,这就是导致卡顿的原因
- **本地测试连接**
```shell
[root@hg14150 ~]# curl localhost:9200
#连接成功
{
"name" : "d484bd5e6516",
"cluster_name" : "docker-cluster",
"cluster_uuid" : "n8R_tH99R7uOwsAZTD0iNA",
"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"
}
- 公网测试连接
- 设置内存限制(重要)
```shell
-e 限制内存(64,512),修改内置
docker run -d —name elasticsearch -p 9200:9200 -p 9300:9300 -e “discovery.type=single-node” -e ES_JAVA_OPTS=”-Xms64m -Xmx512m” elasticsearch:7.6.2
查看CPU消耗情况
[root@hg14150 ~]#docker stats CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS ead77dafa3be elasticsearch-02 2.55% 399.9MiB / 1.694GiB 23.06% 656B / 0B 113MB / 729kB 43
内村限流的效果 399.9MiB / 1.694GiB
- **Kibana与ES的连接**<br />![](https://gitee.com/hg14150/blogiamges/raw/master/img/image-20210506190304802.png#crop=0&crop=0&crop=1&crop=1&id=BxlpD&originHeight=447&originWidth=933&originalType=binary&ratio=1&rotation=0&showTitle=false&status=done&style=none&title=)
<a name="8688e0c7"></a>
#### 2.1.5、Portainer可视化
- **portainer镜像部署**
```shell
#无视权限的命令(不建议使用)
docker run -d -p 8080:9000 portainer/portainer
#设置权限的命令
docker run -d -p 8080:9000 \
--restart=always -v /var/run/docker.sock:/var/run/docker.sock --privileged=true portainer/portainer
#部署镜像
[root@hg14150 ~]# docker run -d -p 8899:9000 --restart=always -v /var/run/docker.sock:/var/run/docker.sock --privileged=true portainer/portainer
21493c63dd9ae8e53fc43b3bac9c0a4e9b755e9f01663f0b7aa1baf17bcf7652
- 公网测试
2.1.6、未完待续
2.2、镜像原理
2.2.1、什么是镜像
镜像是一种轻量级、可执行的独立软件保,用来打包软件运行环境和基于运行环境开发的软件,包含运行某个软件所需的所有内容,包括代码、运行时库、环境变量和配置文件等等
镜像加载原理 UnionFs (联合文件系统)
- UnionFs(联合文件系统):Union文件系统(UnionFs)是一种分层、轻量级并且高性能的文件系统,支持对文件系统的修改作为一次提交来一层层的叠加,同时可以将不同目录挂载到同一个虚拟文件系统下( unite several directories into a single virtual filesystem)。
- Union文件系统是 Docker镜像的基础。镜像可以通过分层来进行继承,基于基础镜像(没有父镜像),可以制作各种具体的应用镜像
- 特性:一次同时加载多个文件系统,但从外面看起来,只能看到一个文件系统,联合加载会把各层文件系统叠加起来,这样最终的文件系统会包含所有底层的文件和目录
Docker镜像加载原理
- docker的镜像实际上由一层一层的文件系统组成,这种层级的文件系统UnionFS。
- boots(boot file system)主要包含 bootloader和 Kernel, bootloader主要是引导加 kernel, Linux刚启动时会加bootfs文件系统,在 Docker镜像的最底层是 boots。这一层与我们典型的Linux/Unix系统是一样的,包含boot加載器和内核。当boot加载完成之后整个内核就都在内存中了,此时内存的使用权已由 bootfs转交给内核,此时系统也会卸载bootfs。
- rootfs(root file system),在 bootfs之上。包含的就是典型 Linux系统中的/dev,/proc,/bin,/etc等标准目录和文件。 rootfs就是各种不同的操作系统发行版,比如 Ubuntu, Centos等等。
Docker镜像加载的效果
- 对于个精简的OS,rootfs可以很小,只需要包合最基本的命令,工具和程序库就可以了,因为底层直接用Host的kernel,自己只需要提供rootfs就可以了。由此可见对于不同的Linux发行版, boots基本是一致的, rootfs会有差別,因此不同的发行版可以公用bootfs 。虚拟机是分钟级别,Docker容器是秒级!
2.2.2、Docker镜像分层
- 镜像分层 : 原理类似Git的版本分支版本,如果镜像更新了,下载镜像,旧版本的镜像文件不会被覆盖,而是以层级的形式下载新的文件
- 为什么要分层呢?
最大的好处,就是轻松实现资源共享了!比如有多个镜像都从相同的Base镜像构建而来,那么主机只需在磁盘上保留一份base镜像,同时内存中也只需要加载一份base镜像,这样就可以为所有的容器服务了,而且镜像的每一层都可以被共享。
理解
所有的 Docker镜像都起始于一个基础镜像层,当进行修改或培加新的内容时,就会在当前镜像层之上,创建新的镜像层。
- 以 Ubuntu 为例, Ubuntu Linux16.04创建一个新的镜像,这就是新镜像的第一层;
- 如果在该镜像中添加 Python包,就会在基础镜像层之上创建第二个镜像层;
- 如果继续添加一个安全补丁,就会创健第三个镜像层该像当前已经包含3个镜像层;
- 在添加额外的镜像层的同时,镜像始终保持是当前所有镜像的组合,理解这一点非常重要。
- 每个镜像层包含3个文件,而镜像包含了来自两个镜像层的6个文件
- 如果文件5有更新的版本7, 在外部看来整个镜像只有6个文件,这是因为最上层中的文件就是文件5的一个更新版
- 这种情況下,上层镜像层中的文件覆盖了底层镜像层中的文件。这样就使得文件的更新版本作为一个新镜像层添加到镜像当中
- Docker通过存储引擎的方式来实现镜像层堆栈,并保证多镜像层对外展示为统一的文件系统
- Linux上可用的存储引撃有AUFS、 Overlay2、 Device Mapper、Btrfs以及ZFS。顾名思义,每种存储引擎都基于 Linux中对应的
件系统或者块设备技术,井且每种存储引擎都有其独有的性能特点。 - Docker在 Windows上仅支持 windowsfilter 一种存储引擎,该引擎基于NTFS文件系统之上实现了分层和CoW [1]。
特点
Docker 镜像都是只读的,当容器启动时,一个新的可写层加载到镜像的顶部!这一层就是我们通常说的容器层,容器之下的都叫镜像层!镜像层是从远程下载的无法更改,容器在本地新建或运行的可更改。
2.2.3、Commit镜像
- 命令使用
# 4、将操作过的容器通过commit调教为一个镜像!以后就使用自定义修改过的镜像即可,而不需要每次都重新拷贝webapps.dist下的文件到webapps了,这就是自己的一个修改的镜像。
docker commit -m="描述信息" -a="作者" 容器id 目标镜像名:[TAG]:版本
docker commit -a="hg" -m="add webapps app" 容器id tomcat-dev:1.0
- tomcat测试
#启动tomcat容器
[root@hg14150 ~]# docker run -d -p 8090:8080 tomcat
3bfc464f089aafbb2c8f266ebb3c415f34657aa8506aa4ed887f91728fce4146
[root@hg14150 ~]# docker exec -it 3bfc464f089a /bin/bash
root@3bfc464f089a:/usr/local/tomcat# cp -r webapps.dist/* webapps
root@3bfc464f089a:/usr/local/tomcat# cd webapps
root@3bfc464f089a:/usr/local/tomcat/webapps# ls -al
total 32
drwxr-xr-x 1 root root 4096 May 7 03:03 .
drwxr-xr-x 1 root root 4096 Apr 22 23:10 ..
drwxr-xr-x 3 root root 4096 May 7 03:03 ROOT
drwxr-xr-x 15 root root 4096 May 7 03:03 docs
drwxr-xr-x 7 root root 4096 May 7 03:03 examples
drwxr-xr-x 6 root root 4096 May 7 03:03 host-manager
drwxr-xr-x 6 root root 4096 May 7 03:03 manager
root@3bfc464f089a:/# exit
exit
#提交tomcat镜像
[root@hg14150 ~]# docker commit -a="hg" -m="add webapps app" 3bfc464f089a tomcat-dev:1.0
sha256:ec6f8010be897278ed28b554989c0c3b67a89924d006235bc989cd626c731e72
[root@hg14150 ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
tomcat-dev 1.0 ec6f8010be89 11 seconds ago 672MB
tomcat latest c0e850d7b9bb 2 weeks ago 667MB
nginx latest 62d49f9bab67 3 weeks ago 133MB
portainer/portainer latest 580c0e4e98b0 7 weeks ago 79.1MB
hello-world latest d1165f221234 2 months ago 13.3kB
centos 7 8652b9f0cb4c 5 months ago 204MB
elasticsearch 7.6.2 f29a1ee41030 13 months ago 791MB
java 8 d23bdf5b1b1b 4 years ago 643MB
- 提交过后,下次使用就可以直接使用已提交的版本,不用再修改webapps下的文件了,这也相当于发布了一个镜像快照
2.3、容器数据卷
2.3.1、什么是容器数据卷
- 使用docker容器的时候,会产生一系列的数据文件,这些数据文件在我们关闭docker容器时是会消失的,但是其中产生的部分数据我们是希望能够把它给保存起来另作用途的,Docker将应用与运行环境打包成容器发布,我们希望在运行过程钟产生的部分数据是可以持久化的,而且容器之间我们希望能够实现数据共享。
- 通俗地来说,docker容器数据卷可以看成使我们生活中常用的u盘,它存在于一个或多个的容器中,由docker挂载到容器,但不属于联合文件系统,Docker不会在容器删除时删除其挂载的数据卷。
- Docker容器内容持久化的需求
- 需要将容器内容持久化到本地
- Docker动态产生的数据同步到本地
- 容器间能做到同步共享数据
- 数据卷可以让容器持久化和同步操作!也可以让容器间共享数据!
- 特点:
1:数据卷可以在容器之间共享或重用数据
2:数据卷中的更改可以直接生效
3:数据卷中的更改不会包含在镜像的更新中
4:数据卷的生命周期一直持续到没有容器使用它为止
2.3.2、容器数据卷的使用
数据卷管理
docker在容器中管理的两种方式:
- 数据卷:Volumes
- 挂载主机目录
#创建数据卷
[root@hg14150 /]# docker volume create mydata
#查看数据卷
[root@hg14150 /]# docker volume ls
#查看数据卷信息
[root@hg14150 /]# docker volume inspect mydata
注:Mountpoint为数据在本机存储的位置
- 数据卷挂载方式一
```shell
直接使用命令挂载
docker run -it -v 主机目录:容器目录 镜像 /bin/bash [root@hg14150 /]# docker run -it -v /home/test:/home centos:7 /bin/bash
挂载前
[root@hg14150 ~]# cd /home [root@hg14150 home]# ls www
挂载后
[root@hg14150 ~]# cd /home [root@hg14150 home]# ls test www
查看挂载情况
[root@hg14150 home]# docker inspect 7498735dd0af [ { “Id”: “7498735dd0afc06027e3e5f344d6a9b58bcf5fd4572acc1cbf32447870f406f5”, “Created”: “2021-05-07T03:32:29.670351409Z”, “Path”: “/bin/bash”, “Args”: [], “State”: { “Status”: “running”, “Running”: true, “Paused”: false, “Restarting”: false, “OOMKilled”: false, “Dead”: false, “Pid”: 10388, “ExitCode”: 0, “Error”: “”, “StartedAt”: “2021-05-07T03:32:30.058957908Z”, “FinishedAt”: “0001-01-01T00:00:00Z” }, “Mounts”: [ { “Type”: “bind”, “Source”: “/home/test”, “Destination”: “/home”, “Mode”: “”, “RW”: true, “Propagation”: “rprivate” } ], “Config”: { “Hostname”: “7498735dd0af”, “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:7”, “Volumes”: null, “WorkingDir”: “”, “Entrypoint”: null, “OnBuild”: null, “Labels”: { “org.label-schema.build-date”: “20201113”, “org.label-schema.license”: “GPLv2”, “org.label-schema.name”: “CentOS Base Image”, “org.label-schema.schema-version”: “1.0”, “org.label-schema.vendor”: “CentOS”, “org.opencontainers.image.created”: “2020-11-13 00:00:00+00:00”, “org.opencontainers.image.licenses”: “GPL-2.0-only”, “org.opencontainers.image.title”: “CentOS Base Image”, “org.opencontainers.image.vendor”: “CentOS” } } } ]
<br />![](https://gitee.com/hg14150/blogiamges/raw/master/img/image-20210507114150535.png#crop=0&crop=0&crop=1&crop=1&id=xuNug&originHeight=218&originWidth=491&originalType=binary&ratio=1&rotation=0&showTitle=false&status=done&style=none&title=)
- **测试挂载是否成功**
```shell
#容器内创建文件
[root@7498735dd0af home]# touch test.java
#查看主机目录下的情况
[root@hg14150 test]# ls
test.java
#主机目录下创建文件
[root@hg14150 test]# touch test-02.java
#查看容器内文件情况
[root@7498735dd0af home]# ls -al
total 8
drwxr-xr-x 2 root root 4096 May 7 03:45 .
drwxr-xr-x 1 root root 4096 May 7 03:32 ..
-rw-r--r-- 1 root root 0 May 7 03:45 test-02.java
-rw-r--r-- 1 root root 0 May 7 03:43 test.java
#######
#类似双向绑定的原理,双向联通,数据互通
在主机目录下编辑test.java
[root@hg14150 test]# vim test.java hello world :wq
启动容器
[root@hg14150 /]# docker start 7498735dd0af 7498735dd0af
进入正在运行的容器
[root@hg14150 /]# docker attach 7498735dd0af
进入容器下的home目录
[root@7498735dd0af /]# cd /home [root@7498735dd0af home]# ls test-02.java test.java
查看文件内容
[root@7498735dd0af home]# cat test.java hello world
同步成功
#
在容器中编辑test.java
若在容器中不能使用vi/vim编辑
更新来源
[root@7498735dd0af home]# apt-get update
安装vim
[root@7498735dd0af home]# apt-get install -y vim
编辑
[root@7498735dd0af home]# vi test.java hello world hello linux
在主机目录下查看文件内容
[root@hg14150 test]# cat test.java hello world hello linux
同步成功
<a name="d0885a0c"></a>
#### 2.3.3、实战挂载MySQL
- **基础命令**
```shell
#下载MySQL镜像
[root@hg14150 ~]# docker pull mysql:5.7
#下载过程
5.7: Pulling from library/mysql
f7ec5a41d630: Already exists
9444bb562699: Pull complete
6a4207b96940: Pull complete
181cefd361ce: Pull complete
8a2090759d8a: Pull complete
15f235e0d7ee: Pull complete
d870539cd9db: Pull complete
cb7af63cbefa: Pull complete
151f1721bdbf: Pull complete
fcd19c3dd488: Pull complete
415af2aa5ddc: Pull complete
Digest: sha256:a655529fdfcbaf0ef28984d68a3e21778e061c886ff458b677391924f62fb457
Status: Downloaded newer image for mysql:5.7
docker.io/library/mysql:5.7
#查看镜像
[root@hg14150 ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
tomcat-dev 1.0 ec6f8010be89 About an hour ago 672MB
tomcat latest c0e850d7b9bb 2 weeks ago 667MB
mysql 5.7 87eca374c0ed 2 weeks ago 447MB
nginx latest 62d49f9bab67 3 weeks ago 133MB
portainer/portainer latest 580c0e4e98b0 7 weeks ago 79.1MB
hello-world latest d1165f221234 2 months ago 13.3kB
centos 7 8652b9f0cb4c 5 months ago 204MB
elasticsearch 7.6.2 f29a1ee41030 13 months ago 791MB
java 8 d23bdf5b1b1b 4 years ago 643MB
#挂载MySQL服务
[root@hg14150 ~]# docker run -d -p 3307:3306 -v /home/mysql/conf:/etc/mysql/conf.d -v /home/mysql/data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=123456 --name mysql-dev mysql:5.7
#挂载成功
99517cbe7d8e1ddea2ad1b258415fd25429cc6743d29bf7a47da9081187d4d78
##########################
#分析
#-d 后台运行
#-p 暴露端口
#-v 挂载容器
#/home/mysql/conf:/etc/mydql/conf.d 主机目录:容器目录(双向绑定)
#/home/mysql/data:/var/lib/mysql 容器目录:容器目录(双向绑定)
# -e MYSQL_ROOT_PASSWORD=123456 设置mysql初始密码
#--name mysql-dev 为挂载的MySQL容器起别名
#mysql:5.7 启动指定版本的MySQL
- 公网测试连接
- 外部新建数据库
- 持久化测试
```shell
删除容器
[root@hg14150 ~]# docker rm -f mysql-dev进入主机目录查看文件内容
[root@hg14150 data]# ls auto.cnf client-key.pem ib_logfile1 private_key.pem sys ca-key.pem ib_buffer_pool ibtmp1 public_key.pem ca.pem ibdata1 mysql server-cert.pem client-cert.pem ib_logfile0 performance_schema server-key.pem
删除容器后,挂载到本地的镜像还在,并且数据不变,持久化保存数据得以实现
<a name="1c89e864"></a>
#### 2.3.4、具名/匿名挂载
- **匿名挂载**
```shell
# -v 容器内路径
[root@hg14150 ~]# docker run -d -P --name nginx-dev -v /etc/nginx nginx
76a8c2dfe397cdd1c427c3ead0ea7bbfa9485ab203976ed578fefa17afc1ca9b
#-P :大写P,随机端口
#volume的操作
[root@hg14150 ~]# docker volume --help
Usage: docker volume COMMAND
Manage volumes
Commands:
create Create a volume
inspect Display detailed information on one or more volumes
ls List volumes
prune Remove all unused local volumes
rm Remove one or more volumes
Run 'docker volume COMMAND --help' for more information on a command.
#查看本地的匿名卷的挂载
[root@hg14150 ~]# docker volume ls
DRIVER VOLUME NAME
local 7f0c6276f386557dab86b3c8c45a7b971989b1e956a3babb50f6aa3cbc2a0177
local baf6a0a2d132d14052eed478a4f74a0a08820020c9c51a4be68e147e19a206cf
local d4f77245e5246c86cb651150af44d35b082b493052fffdbf9c37f08c46c126f7
local fcfd65b62a8a3f59fa856f6ab620e09ee481cf4e11465fae36d51a100806712d
- 具名挂载
```shell
-v 卷名:容器内路径
[root@hg14150 ~]# docker run -d -P —name nginx-dev-02 -v nginx-name:/etc/nginx nginx 346784961ac10a6bb0f14f15ea8d9534913d7acd879e5a1c39736c0b5dbb4f98查看本地的匿名卷的挂载
[root@hg14150 ~]# docker volume ls DRIVER VOLUME NAME local 7f0c6276f386557dab86b3c8c45a7b971989b1e956a3babb50f6aa3cbc2a0177 local baf6a0a2d132d14052eed478a4f74a0a08820020c9c51a4be68e147e19a206cf local d4f77245e5246c86cb651150af44d35b082b493052fffdbf9c37f08c46c126f7 local fcfd65b62a8a3f59fa856f6ab620e09ee481cf4e11465fae36d51a100806712d local nginx-name
查看容器卷的具体路径
[root@hg14150 ~]# docker volume inspect nginx-name [ { “CreatedAt”: “2021-05-07T18:09:22+08:00”, “Driver”: “local”, “Labels”: null, “Mountpoint”: “/www/server/docker/volumes/nginx-name/_data”, “Name”: “nginx-name”, “Options”: null, “Scope”: “local” } ]
查看容器卷具体文件
[root@hg14150 ~]# cd /www/server/docker #文件名与Mountpoint要一致 [root@hg14150 docker]# ll total 52 drwx—x—x 4 root root 4096 Apr 28 20:54 buildkit drwx——-x 24 root root 4096 May 7 18:09 containers drwx——— 3 root root 4096 Apr 28 20:54 image drwxr-x—- 3 root root 4096 Apr 28 20:54 network drwx——-x 94 root root 12288 May 7 18:09 overlay2 drwx——— 4 root root 4096 Apr 28 20:54 plugins drwx——— 2 root root 4096 May 6 16:01 runtimes drwx——— 2 root root 4096 Apr 28 20:54 swarm drwx——— 2 root root 4096 May 7 12:10 tmp drwx——— 2 root root 4096 Apr 28 20:54 trust drwx——-x 7 root root 4096 May 7 18:09 volumes
查看本地卷名
[root@hg14150 docker]# cd volumes/ [root@hg14150 volumes]# ls 7f0c6276f386557dab86b3c8c45a7b971989b1e956a3babb50f6aa3cbc2a0177 backingFsBlockDev baf6a0a2d132d14052eed478a4f74a0a08820020c9c51a4be68e147e19a206cf d4f77245e5246c86cb651150af44d35b082b493052fffdbf9c37f08c46c126f7 fcfd65b62a8a3f59fa856f6ab620e09ee481cf4e11465fae36d51a100806712d metadata.db nginx-name
查看数据卷所有文件
[root@hg14150 volumes]# cd nginx-name/ [root@hg14150 nginx-name]# ll total 4 drwxr-xr-x 3 root root 4096 May 7 18:09 _data [root@hg14150 nginx-name]# cd _data/ [root@hg14150 _data]# ll total 40 drwxr-xr-x 2 root root 4096 May 7 18:09 conf.d -rw-r—r— 1 root root 1007 Apr 13 23:13 fastcgi_params -rw-r—r— 1 root root 2837 Apr 13 23:13 koi-utf -rw-r—r— 1 root root 2223 Apr 13 23:13 koi-win -rw-r—r— 1 root root 5231 Apr 13 23:13 mime.types lrwxrwxrwx 1 root root 22 Apr 13 23:40 modules -> /usr/lib/nginx/modules -rw-r—r— 1 root root 643 Apr 13 23:40 nginx.conf -rw-r—r— 1 root root 636 Apr 13 23:13 scgi_params -rw-r—r— 1 root root 664 Apr 13 23:13 uwsgi_params -rw-r—r— 1 root root 3610 Apr 13 23:13 win-utf
查看数据卷的配置文件
[root@hg14150 _data]# cat nginx.conf user nginx; worker_processes 1; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main ‘$remote_addr - $remote_user [$time_local] “$request” ‘ ‘$status $body_bytes_sent “$http_referer” ‘ ‘“$http_user_agent” “$http_x_forwarded_for”‘; access_log /var/log/nginx/access.log main; sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
#gzip on;
include /etc/nginx/conf.d/*.conf;
}
<br /> ![](https://gitee.com/hg14150/blogiamges/raw/master/img/image-20210507181328176.png#crop=0&crop=0&crop=1&crop=1&id=RLqoo&originHeight=229&originWidth=660&originalType=binary&ratio=1&rotation=0&showTitle=false&status=done&style=none&title=)
- **加载方法的使用情况**<br />大多数情况下使用的都是具名挂载,通过具名挂载方便的找到一个卷
```shell
#确定挂载方式
-v 容器内路径 #匿名挂载
-v 卷名:容器内路径 #具名挂载
-v /主机路径::容器内路径 #指定路径挂载(常用)
一旦设置了容器权限,挂载内容的操作就被限定了
docker run -d -P —name -v nginx-name:/etc/nginx:ro nginx #只读 docker run -d -P —name -v nginx-name:/etc/nginx:rw nginx #可读可写
<a name="0862589c"></a>
#### 2.3.5、数据卷容器(重要)
- **数据卷挂载方式二**,**Dockerfile**
Dockerfile是用来构建docker镜像的构建文件
```shell
#创建dockerfile文件,名字随机
[root@hg14150 home]# mkdir docker
#编辑dockerfile-01内容,每一步都是一层镜像,指令全大写
FROM centos
VOLUME ["volume01","volume02" ]
CMD echo "-----end------"
CMD /bin/bash
#创建镜像 每一个命令就是一层镜像
[root@hg14150 docker]# docker build -f /home/docker/dockerfile-01 -t hg/centos:1.0 .
#构建镜像
Sending build context to Docker daemon 2.048kB
#获取镜像
Step 1/4 : FROM centos
latest: Pulling from library/centos
7a0437f04f83: Pull complete
Digest: sha256:5528e8b1b1719d34604c87e11dcd1c0a20bedf46e83b5632cdeac91b8c04efc1
Status: Downloaded newer image for centos:latest
---> 300e315adb2f
#通过volume进行镜像挂载
Step 2/4 : VOLUME ["volume01","volume02" ]
---> Running in 8814c66d7e01
Removing intermediate container 8814c66d7e01
---> 387dfb28efad
#打印容器内容end
Step 3/4 : CMD echo "-----end------"
---> Running in 2bb39cee6bf0
Removing intermediate container 2bb39cee6bf0
---> e18271cca320
#进入 /bin/bash
Step 4/4 : CMD /bin/bash
---> Running in f4f5f846c551
Removing intermediate container f4f5f846c551
---> 585fbf640ca7
#镜像构建成功
Successfully built 585fbf640ca7
Successfully tagged hg/centos:1.0
#查看镜像
[root@hg14150 docker]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
hg/centos 1.0 585fbf640ca7 3 minutes ago 209MB
tomcat-dev 1.0 ec6f8010be89 9 hours ago 672MB
tomcat latest c0e850d7b9bb 2 weeks ago 667MB
mysql 5.7 87eca374c0ed 2 weeks ago 447MB
nginx latest 62d49f9bab67 3 weeks ago 133MB
portainer/portainer latest 580c0e4e98b0 7 weeks ago 79.1MB
hello-world latest d1165f221234 2 months ago 13.3kB
centos latest 300e315adb2f 5 months ago 209MB
centos 7 8652b9f0cb4c 5 months ago 204MB
elasticsearch 7.6.2 f29a1ee41030 13 months ago 791MB
java 8 d23bdf5b1b1b 4 years ago 643MB
- 启动镜像
```shell
以交互形式启动hg/centos
[root@hg14150 docker]# docker run -it 585fbf640ca7 /bin/bash [root@be98562636d7 /]# ls -l total 56 lrwxrwxrwx 1 root root 7 Nov 3 2020 bin -> usr/bin drwxr-xr-x 5 root root 360 May 7 11:50 dev drwxr-xr-x 1 root root 4096 May 7 11:50 etc drwxr-xr-x 2 root root 4096 Nov 3 2020 home lrwxrwxrwx 1 root root 7 Nov 3 2020 lib -> usr/lib lrwxrwxrwx 1 root root 9 Nov 3 2020 lib64 -> usr/lib64 drwx——— 2 root root 4096 Dec 4 17:37 lost+found drwxr-xr-x 2 root root 4096 Nov 3 2020 media drwxr-xr-x 2 root root 4096 Nov 3 2020 mnt drwxr-xr-x 2 root root 4096 Nov 3 2020 opt dr-xr-xr-x 138 root root 0 May 7 11:50 proc dr-xr-x—- 2 root root 4096 Dec 4 17:37 root drwxr-xr-x 11 root root 4096 Dec 4 17:37 run lrwxrwxrwx 1 root root 8 Nov 3 2020 sbin -> usr/sbin drwxr-xr-x 2 root root 4096 Nov 3 2020 srv dr-xr-xr-x 13 root root 0 May 6 02:42 sys drwxrwxrwt 7 root root 4096 Dec 4 17:37 tmp drwxr-xr-x 12 root root 4096 Dec 4 17:37 usr drwxr-xr-x 20 root root 4096 Dec 4 17:37 var drwxr-xr-x 2 root root 4096 May 7 11:50 volume01 drwxr-xr-x 2 root root 4096 May 7 11:50 volume02
容器中新建文件
[root@373a3878c832 volume01]# touch container.txt [root@373a3878c832 volume01]# ls container.txt
- **数据卷同步挂载**
```shell
#####实质上这是一个匿名挂载,但在主机目录下一定有一个与之同步文件
#编辑dockerfile-01内容,每一步都是一层镜像,指令全大写
FROM centos
VOLUME ["volume01","volume02" ]
CMD echo "-----end------"
CMD /bin/bash
主机挂载同步目录
#查看主机目录下数据卷挂载目录
docker inspect 373a3878c832
查看主机数据卷挂载内容
[root@hg14150 ~]# cd /www/server/docker/volumes/b0bd6025764707df5c8dce723279b95916464c50580/_data
[root@hg14150 _data]# ls
container.txt
在构建镜像时如果没有挂载,后期就要手动挂载镜像 -v卷名:容器内路径数据卷挂载实现容器间数据同步或共享
创建第一个数据卷容器不挂载
#以交互方法启动自定义镜像容器不挂载
[root@hg14150 /]# docker run -it --name docker-dev hg/centos #在hg/centos容器下启动
[root@39f1e87eb519 /]# ls -al
total 64
drwxr-xr-x 1 root root 4096 May 7 12:19 .
drwxr-xr-x 1 root root 4096 May 7 12:19 ..
-rwxr-xr-x 1 root root 0 May 7 12:19 .dockerenv
lrwxrwxrwx 1 root root 7 Nov 3 2020 bin -> usr/bin
drwxr-xr-x 5 root root 360 May 7 12:19 dev
drwxr-xr-x 1 root root 4096 May 7 12:19 etc
drwxr-xr-x 2 root root 4096 Nov 3 2020 home
lrwxrwxrwx 1 root root 7 Nov 3 2020 lib -> usr/lib
lrwxrwxrwx 1 root root 9 Nov 3 2020 lib64 -> usr/lib64
drwx------ 2 root root 4096 Dec 4 17:37 lost+found
drwxr-xr-x 2 root root 4096 Nov 3 2020 media
drwxr-xr-x 2 root root 4096 Nov 3 2020 mnt
drwxr-xr-x 2 root root 4096 Nov 3 2020 opt
dr-xr-xr-x 129 root root 0 May 7 12:19 proc
dr-xr-x--- 2 root root 4096 Dec 4 17:37 root
drwxr-xr-x 11 root root 4096 Dec 4 17:37 run
lrwxrwxrwx 1 root root 8 Nov 3 2020 sbin -> usr/sbin
drwxr-xr-x 2 root root 4096 Nov 3 2020 srv
dr-xr-xr-x 13 root root 0 May 6 02:42 sys
drwxrwxrwt 7 root root 4096 Dec 4 17:37 tmp
drwxr-xr-x 12 root root 4096 Dec 4 17:37 usr
drwxr-xr-x 20 root root 4096 Dec 4 17:37 var
drwxr-xr-x 2 root root 4096 May 7 12:19 volume01
drwxr-xr-x 2 root root 4096 May 7 12:19 volume02
创建第二个数据卷容器挂载继承第一个容器
#以交互方式启动自定义镜像容器挂载第一个容器
[root@hg14150 ~]# docker run -it --name docker-dev-02 --volumes-from docker-dev hg/centos
#在hg/centos容器下启动
[root@c3db7747e7b8 /]# ls -al
total 64
drwxr-xr-x 1 root root 4096 May 7 12:23 .
drwxr-xr-x 1 root root 4096 May 7 12:23 ..
-rwxr-xr-x 1 root root 0 May 7 12:23 .dockerenv
lrwxrwxrwx 1 root root 7 Nov 3 2020 bin -> usr/bin
drwxr-xr-x 5 root root 360 May 7 12:23 dev
drwxr-xr-x 1 root root 4096 May 7 12:23 etc
drwxr-xr-x 2 root root 4096 Nov 3 2020 home
lrwxrwxrwx 1 root root 7 Nov 3 2020 lib -> usr/lib
lrwxrwxrwx 1 root root 9 Nov 3 2020 lib64 -> usr/lib64
drwx------ 2 root root 4096 Dec 4 17:37 lost+found
drwxr-xr-x 2 root root 4096 Nov 3 2020 media
drwxr-xr-x 2 root root 4096 Nov 3 2020 mnt
drwxr-xr-x 2 root root 4096 Nov 3 2020 opt
dr-xr-xr-x 132 root root 0 May 7 12:23 proc
dr-xr-x--- 2 root root 4096 Dec 4 17:37 root
drwxr-xr-x 11 root root 4096 Dec 4 17:37 run
lrwxrwxrwx 1 root root 8 Nov 3 2020 sbin -> usr/sbin
drwxr-xr-x 2 root root 4096 Nov 3 2020 srv
dr-xr-xr-x 13 root root 0 May 6 02:42 sys
drwxrwxrwt 7 root root 4096 Dec 4 17:37 tmp
drwxr-xr-x 12 root root 4096 Dec 4 17:37 usr
drwxr-xr-x 20 root root 4096 Dec 4 17:37 var
drwxr-xr-x 2 root root 4096 May 7 12:19 volume01
drwxr-xr-x 2 root root 4096 May 7 12:19 volume02
实现数据同步 ```shell
在docker-dev/volume01下创建文件
[root@39f1e87eb519 volume01]# touch docker-dev.java [root@39f1e87eb519 volume01]# ls docker-dev.java
在docker-dev-02/volume01下查看文件
root@c3db7747e7b8 volume01]# ls docker-dev.java
在docker-dev-02/volume01下创建文件
[root@c3db7747e7b8 volume01]# touch docker-dev.txt
在docker-dev/volume01下查看文件
[root@39f1e87eb519 volume01]# ls docker-dev.java docker-dev.txt
实现docker-dev与docker-dev-02数据同步并且持久化保存
![](https://gitee.com/hg14150/blogiamges/raw/master/img/image-20210507205124219.png#crop=0&crop=0&crop=1&crop=1&id=YuAAb&originHeight=411&originWidth=1261&originalType=binary&ratio=1&rotation=0&showTitle=false&status=done&style=none&title=)
- **实现多个MySQL实现数据共享**
```shell
#启用两个MySQL公用一个数据库
#启动mysql-dev-01容器
[root@hg14150 /]# docker run -d -p 3307:3306 -v /etc/mysql/conf.d -v /var/lib/mysql -e MYSQL_ROOT_PASSWORD=123456 --name mysql-dev-01 mysql:5.7
#启动mysql-dev-02容器
[root@hg14150 /]# docker run -d -p 3308:3306 -v /etc/mysql/conf.d -v /var/lib/mysql -e MYSQL_ROOT_PASSWORD=123456 --name mysql-dev-01 mysql:5.7
2.3.6、Dockerfile
1、Dockerfile介绍
- dockerfile是用来构建docker镜像的文件,命令参数脚本
- 构建步骤:
- 编写一个dockerfile文件
- docker build构建成为一个镜像
- docker run 运行镜像
- docker push 发布镜像(DockerHub 阿里云仓库等)
- 官方详解
发布镜像,在GitHub上
- GitHub上的镜像内容
- 镜像脚本
```shell
底层镜像依赖
FROM scratch导入centos7的镜像
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=”20201113” \ 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-11-13 00:00:00+00:00”
CMD [“/bin/bash”]
- 官方镜像只有基础包,只能满足基础需求,自定义镜像时需要往里面添加东西的
<a name="bb290ccf"></a>
##### 2、Dockerfile构建过程
- **Dockerfile基础命令**
- 每个保留关键字(指令)都必须是大写字母
- 执行遵循从上到下的顺序,不能反
- ‘#’ 表示注释
- 每一个指令都表示一层镜像
- Dockerfile时面向开发的,
![](https://gitee.com/hg14150/blogiamges/raw/master/img/image-20210508115137052.png#crop=0&crop=0&crop=1&crop=1&id=uKeds&originHeight=584&originWidth=1170&originalType=binary&ratio=1&rotation=0&showTitle=false&status=done&style=none&title=)
- **Dockerfile构建步骤**
- DockerFile:构建文件,定义底层需求即源码
- DockerImages:通过DockerFile构建生成的镜像,最终发布或运行的产品
- Docker容器:即镜像运行起来的服务
<a name="a0f5ec5a"></a>
##### 3、**DockerFile指令说明**
- **dockerfile指令是构建的基础** <br />![](https://gitee.com/hg14150/blogiamges/raw/master/img/image-20210508120502478.png#crop=0&crop=0&crop=1&crop=1&id=mKAeM&originHeight=643&originWidth=1186&originalType=binary&ratio=1&rotation=0&showTitle=false&status=done&style=none&title=)
| 指令 | 指令说明 |
| --- | --- |
| FROM | 基础镜像,一切从这里出发 90%使用的都是**(scrath)** |
| MAINAINER | 镜像签署,姓名+邮箱 |
| RUN | 镜像构建时需要运行的命令 |
| ADD | 添加内容,如tomcat镜像,添加压缩包 |
| WORKDIR | 镜像工作目录 |
| VOLUME | 镜像挂载目录 |
| EXPOSE | 保留端口配置 |
| CMD | 指定容器启动时的运行命令,只有最后一个会生效 |
| ENTRYPOINT | 指定容器启动时的命令,可追加 |
| ONBUILD | 构建一个被继承DockerFile,运行ONBUILD触发指令 |
| COPY | 类似ADD,将文件拷贝到镜像中 |
| ENV | 构建容器时配置环境 |
- **CMD与ENTRYOINT的区别**
```shell
CMD #指定容器启动时运行需要的命令,只有最后一个会生效,可被替换
ENTRYOINT #指定容器启动时的命令,可追加
测试CMD与ENTRYOINT
CMD
ENTRYOINT
4、实战测试(重要)
镜像开发者 姓名+邮箱
MAINTAINER hguohlgc14150@163.com
变量的环境目录
ENV MYPATH /usr/local
工作目录
WORKDIR $MYPATH
添加需要执行的功能命令
RUN yum -y install vim RUN yum -y install net-tools
暴露在网络中的端口号
EXPOSE 1314
输出构建信息
CMD echo $MYPATH CMD echo “———end————-“
从/bin/bash启动
CMD /bin/bash
- **构建镜像**
```shell
#-f指定文件 -t指定镜像名:版本(target)
[root@hg14150 dockerfile]# docker build -f dockerfile-centos -t centos-dev:1.0 .
Sending build context to Docker daemon 2.048kB
Step 1/10 : FROM centos
---> 300e315adb2f
Step 2/10 : MAINTAINER hguo<hlgc14150@163.com>
---> Running in cbd3477727d6
Removing intermediate container cbd3477727d6
---> 3f19d12e227f
Step 3/10 : ENV MYPATH /usr/local
---> Running in 2752bb89a19c
Removing intermediate container 2752bb89a19c
---> c3928311c8dc
Step 4/10 : WORKDIR $MYPATH
---> Running in 8701858b521a
Removing intermediate container 8701858b521a
---> fe0815bc00c2
Step 5/10 : RUN yum -y install vim
---> Running in 9edfab7adda2
CentOS Linux 8 - AppStream 2.3 MB/s | 6.3 MB 00:02
CentOS Linux 8 - BaseOS 1.1 MB/s | 2.3 MB 00:02
CentOS Linux 8 - Extras 20 kB/s | 9.6 kB 00:00
Dependencies resolved.
================================================================================
Package Arch Version Repository Size
================================================================================
Installing:
vim-enhanced x86_64 2:8.0.1763-15.el8 appstream 1.4 M
Installing dependencies:
gpm-libs x86_64 1.20.7-15.el8 appstream 39 k
vim-common x86_64 2:8.0.1763-15.el8 appstream 6.3 M
vim-filesystem noarch 2:8.0.1763-15.el8 appstream 48 k
which x86_64 2.21-12.el8 baseos 49 k
Transaction Summary
================================================================================
Install 5 Packages
Total download size: 7.8 M
Installed size: 30 M
Downloading Packages:
(1/5): gpm-libs-1.20.7-15.el8.x86_64.rpm 222 kB/s | 39 kB 00:00
(2/5): vim-filesystem-8.0.1763-15.el8.noarch.rp 945 kB/s | 48 kB 00:00
(3/5): vim-enhanced-8.0.1763-15.el8.x86_64.rpm 4.4 MB/s | 1.4 MB 00:00
(4/5): which-2.21-12.el8.x86_64.rpm 335 kB/s | 49 kB 00:00
(5/5): vim-common-8.0.1763-15.el8.x86_64.rpm 6.0 MB/s | 6.3 MB 00:01
--------------------------------------------------------------------------------
Total 4.1 MB/s | 7.8 MB 00:01
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 Linux 8 - AppStream 1.6 MB/s | 1.6 kB 00:00
Importing GPG key 0x8483C65D:
#构建警告,可忽略
Userid : "CentOS (CentOS Official Signing Key) <security@centos.org>"
Fingerprint: 99DB 70FA E1D7 CE22 7FB6 4882 05B5 55B3 8483 C65D
From : /etc/pki/rpm-gpg/RPM-GPG-KEY-centosofficial
Key imported successfully
Running transaction check
Transaction check succeeded.
Running transaction test
Transaction test succeeded.
Running transaction
Preparing : 1/1
Installing : which-2.21-12.el8.x86_64 1/5
Installing : vim-filesystem-2:8.0.1763-15.el8.noarch 2/5
Installing : vim-common-2:8.0.1763-15.el8.x86_64 3/5
Installing : gpm-libs-1.20.7-15.el8.x86_64 4/5
Running scriptlet: gpm-libs-1.20.7-15.el8.x86_64 4/5
Installing : vim-enhanced-2:8.0.1763-15.el8.x86_64 5/5
Running scriptlet: vim-enhanced-2:8.0.1763-15.el8.x86_64 5/5
Running scriptlet: vim-common-2:8.0.1763-15.el8.x86_64 5/5
Verifying : gpm-libs-1.20.7-15.el8.x86_64 1/5
Verifying : vim-common-2:8.0.1763-15.el8.x86_64 2/5
Verifying : vim-enhanced-2:8.0.1763-15.el8.x86_64 3/5
Verifying : vim-filesystem-2:8.0.1763-15.el8.noarch 4/5
Verifying : which-2.21-12.el8.x86_64 5/5
Installed:
gpm-libs-1.20.7-15.el8.x86_64 vim-common-2:8.0.1763-15.el8.x86_64
vim-enhanced-2:8.0.1763-15.el8.x86_64 vim-filesystem-2:8.0.1763-15.el8.noarch
which-2.21-12.el8.x86_64
Complete!
Removing intermediate container 9edfab7adda2
---> 8fdaf408a2ac
Step 6/10 : RUN yum -y install net-tools
---> Running in 0638bf81c3f0
Last metadata expiration check: 0:00:09 ago on Sat May 8 04:31:25 2021.
Dependencies resolved.
================================================================================
Package Architecture Version Repository Size
================================================================================
Installing:
net-tools x86_64 2.0-0.52.20160912git.el8 baseos 322 k
Transaction Summary
================================================================================
Install 1 Package
Total download size: 322 k
Installed size: 942 k
Downloading Packages:
net-tools-2.0-0.52.20160912git.el8.x86_64.rpm 834 kB/s | 322 kB 00:00
--------------------------------------------------------------------------------
Total 405 kB/s | 322 kB 00:00
Running transaction check
Transaction check succeeded.
Running transaction test
Transaction test succeeded.
Running transaction
Preparing : 1/1
Installing : net-tools-2.0-0.52.20160912git.el8.x86_64 1/1
Running scriptlet: net-tools-2.0-0.52.20160912git.el8.x86_64 1/1
Verifying : net-tools-2.0-0.52.20160912git.el8.x86_64 1/1
Installed:
net-tools-2.0-0.52.20160912git.el8.x86_64
Complete!
Removing intermediate container 0638bf81c3f0
---> b37cb7b5de29
Step 7/10 : EXPOSE 1314
---> Running in fabd6f3cb69e
Removing intermediate container fabd6f3cb69e
---> bc8105dde0e8
Step 8/10 : CMD echo $MYPATH
---> Running in 782d4d6d2216
Removing intermediate container 782d4d6d2216
---> 2cb505be74fc
Step 9/10 : CMD echo "------end---------"
---> Running in ca14de401385
Removing intermediate container ca14de401385
---> b2b2f736004c
Step 10/10 : CMD /bin/bash
---> Running in d89c3297ba2c
Removing intermediate container d89c3297ba2c
---> 7d13c0755aeb
Successfully built 7d13c0755aeb
Successfully tagged centos-dev:1.0
#构建成功
- 分析镜像构建
Step 1/10 : FROM centos
#复用官方centos的镜像
---> 300e315adb2f
#配置开发者信息
Step 2/10 : MAINTAINER hguo<hlgc14150@163.com>
---> Running in cbd3477727d6
#移除冲突镜像容器
Removing intermediate container cbd3477727d6
---> 3f19d12e227f
#配置工作目录
Step 3/10 : ENV MYPATH /usr/local
---> Running in 2752bb89a19c
Removing intermediate container 2752bb89a19c
---> c3928311c8dc
Step 4/10 : WORKDIR $MYPATH
---> Running in 8701858b521a
Removing intermediate container 8701858b521a
---> fe0815bc00c2
#下载vim的信息文件
Step 5/10 : RUN yum -y install vim
Removing intermediate container 9edfab7adda2
---> 8fdaf408a2ac
#下载net-tools需要的信息文件
Step 6/10 : RUN yum -y install net-tools
Removing intermediate container 0638bf81c3f0
---> b37cb7b5de29
#释放端口,放行1314端口
Step 7/10 : EXPOSE 1314
---> Running in fabd6f3cb69e
Removing intermediate container fabd6f3cb69e
---> bc8105dde0e8
#输出构建信息
Step 8/10 : CMD echo $MYPATH
---> Running in 782d4d6d2216
Removing intermediate container 782d4d6d2216
---> 2cb505be74fc
#镜像构建结束
Step 9/10 : CMD echo "------end---------"
---> Running in ca14de401385
Removing intermediate container ca14de401385
---> b2b2f736004c
#启动镜像服务
Step 10/10 : CMD /bin/bash
---> Running in d89c3297ba2c
Removing intermediate container d89c3297ba2c
---> 7d13c0755aeb
- 镜像对比
```shell
显示本地镜像——未构建镜像时
[root@hg14150 /]# docker images REPOSITORY TAG IMAGE ID CREATED SIZE hg/centos 1.0 585fbf640ca7 17 hours ago 209MB tomcat-dev 1.0 ec6f8010be89 25 hours ago 672MB hello-world latest d1165f221234 2 months ago 13.3kB centos latest 300e315adb2f 5 months ago 209MB
启动镜像
[root@hg14150 /]# docker run -it centos [root@5f6327cf0913 /]# pwd / [root@5f6327cf0913 /]# ls -l total 40 drwxr-xr-x 2 root root 4096 Nov 3 2020 bin drwxr-xr-x 2 root root 4096 Nov 3 2020 etc drwxr-xr-x 2 root root 4096 Nov 3 2020 games drwxr-xr-x 2 root root 4096 Nov 3 2020 include drwxr-xr-x 2 root root 4096 Nov 3 2020 lib drwxr-xr-x 3 root root 4096 Dec 4 17:37 lib64 drwxr-xr-x 2 root root 4096 Nov 3 2020 libexec drwxr-xr-x 2 root root 4096 Nov 3 2020 sbin drwxr-xr-x 5 root root 4096 Dec 4 17:37 share drwxr-xr-x 2 root root 4096 Nov 3 2020 src [root@5f6327cf0913 /]# ifconfig bash: docker: command not found [root@5f6327cf0913 /]# exit exit
显示本地镜像——构建镜像后
[root@hg14150 /]# docker images REPOSITORY TAG IMAGE ID CREATED SIZE centos-dev 1.0 7d13c0755aeb 9 minutes ago 291MB hg/centos 1.0 585fbf640ca7 17 hours ago 209MB tomcat-dev 1.0 ec6f8010be89 26 hours ago 672MB centos latest 300e315adb2f 5 months ago 209MB
启动自定义构建的镜像
[root@hg14150 /]# docker run -it centos-dev:1.0 [root@c3a2f3a6d4fb local]# pwd /usr/local [root@c3a2f3a6d4fb local]# ls -l total 40 drwxr-xr-x 2 root root 4096 Nov 3 2020 bin drwxr-xr-x 2 root root 4096 Nov 3 2020 etc drwxr-xr-x 2 root root 4096 Nov 3 2020 games drwxr-xr-x 2 root root 4096 Nov 3 2020 include drwxr-xr-x 2 root root 4096 Nov 3 2020 lib drwxr-xr-x 3 root root 4096 Dec 4 17:37 lib64 drwxr-xr-x 2 root root 4096 Nov 3 2020 libexec drwxr-xr-x 2 root root 4096 Nov 3 2020 sbin drwxr-xr-x 5 root root 4096 Dec 4 17:37 share drwxr-xr-x 2 root root 4096 Nov 3 2020 src
新加功能
[root@c3a2f3a6d4fb local]# ifconfig
eth0: flags=4163
lo: flags=73
- **查看镜像构建过程**
```shell
#history 镜像id 查看镜像构建过程
[root@hg14150 dockerfile]# docker history 7d13c0755aeb
IMAGE CREATED CREATED BY SIZE COMMENT
7d13c0755aeb 17 minutes ago /bin/sh -c #(nop) CMD ["/bin/sh" "-c" "/bin… 0B
b2b2f736004c 17 minutes ago /bin/sh -c #(nop) CMD ["/bin/sh" "-c" "echo… 0B
2cb505be74fc 17 minutes ago /bin/sh -c #(nop) CMD ["/bin/sh" "-c" "echo… 0B
bc8105dde0e8 17 minutes ago /bin/sh -c #(nop) EXPOSE 1314 0B
b37cb7b5de29 17 minutes ago /bin/sh -c yum -y install net-tools 23.3MB
8fdaf408a2ac 17 minutes ago /bin/sh -c yum -y install vim 58MB
fe0815bc00c2 18 minutes ago /bin/sh -c #(nop) WORKDIR /usr/local 0B
c3928311c8dc 18 minutes ago /bin/sh -c #(nop) ENV MYPATH=/usr/local 0B
3f19d12e227f 18 minutes ago /bin/sh -c #(nop) MAINTAINER hguo<hlgc14150… 0B
300e315adb2f 5 months ago /bin/sh -c #(nop) CMD ["/bin/bash"] 0B
<missing> 5 months ago /bin/sh -c #(nop) LABEL org.label-schema.sc… 0B
<missing> 5 months ago /bin/sh -c #(nop) ADD file:bd7a2aed6ede423b7… 209MB
2.3.7、实战构建tomcat(重要)
1、准备镜像文件,tomcat、jdk压缩包
#在主机home目录下新建tomcat文件夹,将tomcat、jdk压缩包上传至此
[root@hg14150 ~]# cd /home/tomcat
[root@hg14150 tomcat]# ll
-rw-r--r-- 1 root root 11486964 May 8 19:59 apache-tomcat-9.0.45.tar.gz
-rw-r--r-- 1 root root 36044800 May 8 20:04 jdk-8u291-linux-x64.tar.gz
2、编写Dockerfile文件
[root@hg14150 tomcat]# touch readme.txt
[root@hg14150 tomcat]# vim Dockerfile
FROM centos
MAINTAINER hguo<hlgc14150@163.com>
COPY readme.txt /usr/local/readme.txt
ADD jdk-8u291-linux-x64.tar.gz /usr/local/
ADD apache-tomcat-9.0.45.tar.gz /usr/local/
RUN yum -y install vim
ENV MYPATH /usr/local
WORK $MYPATH
ENV JAVA_HOME /usr/local/jdk1.8.0
ENV CLASSPATH $JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
ENV CATALINA_HOME /usr/local/apache-tomcat-9.0.45
ENV CATALINA_BASH /usr/local/apache-tomcat-9.0.45
ENV PATH $PATH:$JAVA_HOME/bin:$CATALINA_HOME/lib:$CATALINA_HOME/bin
EXPOSE 8080
CMD /usr/local/apache-tomcat-9.0.45/bin/startup.sh && tail -F /usr/local/apache-tomcat-9.0.45/bin/logs/catalina.out
3、构建镜像
#构建镜像 -t 镜像名
[root@hg14150 tomcat]# docker build -t tomcat-plus .
Sending build context to Docker daemon 156.4MB
Step 1/15 : FROM centos
---> 300e315adb2f
Step 2/15 : MAINTAINER hguo<hlgc14150@163.com>
---> Using cache
---> 3f19d12e227f
Step 3/15 : COPY readme.txt /usr/local/readme.txt
---> eab29281c731
Step 4/15 : ADD jdk-8u291-linux-x64.tar.gz /usr/local/
---> ae722ed8bf57
Step 5/15 : ADD apache-tomcat-9.0.45.tar.gz /usr/local/
---> 33a9b564bb44
Step 6/15 : RUN yum -y install vim
---> Running in 0bb712c9bbfc
CentOS Linux 8 - AppStream 1.9 MB/s | 6.3 MB 00:03
CentOS Linux 8 - BaseOS 2.1 MB/s | 2.3 MB 00:01
CentOS Linux 8 - Extras 2.0 kB/s | 9.6 kB 00:04
Dependencies resolved.
================================================================================
Package Arch Version Repository Size
================================================================================
Installing:
vim-enhanced x86_64 2:8.0.1763-15.el8 appstream 1.4 M
Installing dependencies:
gpm-libs x86_64 1.20.7-15.el8 appstream 39 k
vim-common x86_64 2:8.0.1763-15.el8 appstream 6.3 M
vim-filesystem noarch 2:8.0.1763-15.el8 appstream 48 k
which x86_64 2.21-12.el8 baseos 49 k
Transaction Summary
================================================================================
Install 5 Packages
Total download size: 7.8 M
Installed size: 30 M
Downloading Packages:
(1/5): gpm-libs-1.20.7-15.el8.x86_64.rpm 307 kB/s | 39 kB 00:00
(2/5): vim-filesystem-8.0.1763-15.el8.noarch.rp 1.3 MB/s | 48 kB 00:00
(3/5): which-2.21-12.el8.x86_64.rpm 679 kB/s | 49 kB 00:00
(4/5): vim-enhanced-8.0.1763-15.el8.x86_64.rpm 4.2 MB/s | 1.4 MB 00:00
(5/5): vim-common-8.0.1763-15.el8.x86_64.rpm 9.1 MB/s | 6.3 MB 00:00
--------------------------------------------------------------------------------
Total 1.7 MB/s | 7.8 MB 00:04
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 Linux 8 - AppStream 1.5 MB/s | 1.6 kB 00:00
Importing GPG key 0x8483C65D:
Userid : "CentOS (CentOS Official Signing Key) <security@centos.org>"
Fingerprint: 99DB 70FA E1D7 CE22 7FB6 4882 05B5 55B3 8483 C65D
From : /etc/pki/rpm-gpg/RPM-GPG-KEY-centosofficial
Key imported successfully
Running transaction check
Transaction check succeeded.
Running transaction test
Transaction test succeeded.
Running transaction
Preparing : 1/1
Installing : which-2.21-12.el8.x86_64 1/5
Installing : vim-filesystem-2:8.0.1763-15.el8.noarch 2/5
Installing : vim-common-2:8.0.1763-15.el8.x86_64 3/5
Installing : gpm-libs-1.20.7-15.el8.x86_64 4/5
Running scriptlet: gpm-libs-1.20.7-15.el8.x86_64 4/5
Installing : vim-enhanced-2:8.0.1763-15.el8.x86_64 5/5
Running scriptlet: vim-enhanced-2:8.0.1763-15.el8.x86_64 5/5
Running scriptlet: vim-common-2:8.0.1763-15.el8.x86_64 5/5
Verifying : gpm-libs-1.20.7-15.el8.x86_64 1/5
Verifying : vim-common-2:8.0.1763-15.el8.x86_64 2/5
Verifying : vim-enhanced-2:8.0.1763-15.el8.x86_64 3/5
Verifying : vim-filesystem-2:8.0.1763-15.el8.noarch 4/5
Verifying : which-2.21-12.el8.x86_64 5/5
Installed:
gpm-libs-1.20.7-15.el8.x86_64 vim-common-2:8.0.1763-15.el8.x86_64
vim-enhanced-2:8.0.1763-15.el8.x86_64 vim-filesystem-2:8.0.1763-15.el8.noarch
which-2.21-12.el8.x86_64
Complete!
Removing intermediate container 0bb712c9bbfc
---> f69e2ff5d3ad
Step 7/15 : ENV MYPATH /usr/local
---> Running in 38278921fe01
Removing intermediate container 38278921fe01
---> deec2bf56ec4
Step 8/15 : WORKDIR $MYPATH
---> Running in 16f050b6e14b
Removing intermediate container 16f050b6e14b
---> 53fe26eab228
Step 9/15 : ENV JAVA_HOME /usr/local/jdk1.8.0
---> Running in 44013f99d11d
Removing intermediate container 44013f99d11d
---> 89a2ba9201d8
Step 10/15 : ENV CLASSPATH $JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
---> Running in 69b853a74b1d
Removing intermediate container 69b853a74b1d
---> 7065ef1b3ef5
Step 11/15 : ENV CATALINA_HOME /usr/local/apache-tomcat-9.0.45
---> Running in 26f79d733a48
Removing intermediate container 26f79d733a48
---> 12a4b1deb52f
Step 12/15 : ENV CATALINA_BASH /usr/local/apache-tomcat-9.0.45
---> Running in b9de256bbe3b
Removing intermediate container b9de256bbe3b
---> a95ced2d9dd4
Step 13/15 : ENV PATH $PATH:$JAVA_HOME/bin:$CATALINA_HOME/lib:$CATALINA_HOME/bin
---> Running in a06c397fad98
Removing intermediate container a06c397fad98
---> a20996c8d4fc
Step 14/15 : EXPOSE 8080
---> Running in af7e6eb815b3
Removing intermediate container af7e6eb815b3
---> cd78d02f1f12
Step 15/15 : CMD /usr/local/apache-tomcat-9.0.45/bin/startup.sh && tail -F /usr/local/apache-tomcat-9.0.45/bin/logs/catalina.out
---> Running in 33de53fa78fb
Removing intermediate container 33de53fa78fb
---> 40d2d688f884
Successfully built 40d2d688f884
Successfully tagged tomcat-plus:latest
4、本地挂载
#挂载到主机usr/local目录下
[root@hg14150 tomcat]# docker run -d -p 8000:8080 --name hguo-tomcat -v /home/hguo/build/tomcat/test:/usr/local/apache-tomcat-9.0.45/webapps/test -v /home/hguo/build/tomcat/logs/:/usr/cal/apache-tomcat-9.0.45/logs tomcat-plus
3fa6b8d348f52b83f7d25b9b151043b5557d96ee96cfa1010b64c3762722a23d
#查看生成目录hguo
[root@hg14150 home]# ll
total 28
drwxr-xr-x 2 root root 4096 May 7 18:48 docker
drwxr-xr-x 2 root root 4096 May 8 12:24 dockerfile
drwxr-xr-x 3 root root 4096 May 8 20:40 hguo
drwxr-xr-x 4 root root 4096 May 7 12:19 mysql
drwxr-xr-x 2 root root 4096 May 7 11:56 test
drwxr-xr-x 2 root root 4096 May 8 20:30 tomcat
drwx------ 3 www www 4096 Apr 28 20:51 www
[root@hg14150 home]# cd hguo/build/tomcat 路径与挂载路径一致
[root@hg14150 tomcat]# ll
total 8
drwxr-xr-x 2 root root 4096 May 8 20:40 logs
drwxr-xr-x 2 root root 4096 May 8 20:40 test
#启动容器
[root@hg14150 tomcat]# docker exec -it 3fa6b8d348f52b8 /bin/bash
[root@3fa6b8d348f5 local]# ls -l
total 52
drwxr-xr-x 1 root root 4096 May 8 12:32 apache-tomcat-9.0.45
drwxr-xr-x 2 root root 4096 Nov 3 2020 bin
drwxr-xr-x 2 root root 4096 Nov 3 2020 etc
drwxr-xr-x 2 root root 4096 Nov 3 2020 games
drwxr-xr-x 2 root root 4096 Nov 3 2020 include
drwxr-xr-x 8 10143 10143 4096 Apr 7 19:26 jdk1.8.0_291
drwxr-xr-x 2 root root 4096 Nov 3 2020 lib
drwxr-xr-x 3 root root 4096 Dec 4 17:37 lib64
drwxr-xr-x 2 root root 4096 Nov 3 2020 libexec
-rw-r--r-- 1 root root 0 May 8 12:08 readme.txt
drwxr-xr-x 2 root root 4096 Nov 3 2020 sbin
drwxr-xr-x 5 root root 4096 Dec 4 17:37 share
drwxr-xr-x 2 root root 4096 Nov 3 2020 src
#查看当前路径
[root@3fa6b8d348f5 local]# pwd
/usr/local
#查看tomcat文件内容
[root@3fa6b8d348f5 local]# cd apache-tomcat-9.0.45/
[root@3fa6b8d348f5 apache-tomcat-9.0.45]# ls -l
total 148
-rw-r----- 1 root root 18984 Mar 30 10:29 BUILDING.txt
-rw-r----- 1 root root 5587 Mar 30 10:29 CONTRIBUTING.md
-rw-r----- 1 root root 57092 Mar 30 10:29 LICENSE
-rw-r----- 1 root root 2333 Mar 30 10:29 NOTICE
-rw-r----- 1 root root 3257 Mar 30 10:29 README.md
-rw-r----- 1 root root 6898 Mar 30 10:29 RELEASE-NOTES
-rw-r----- 1 root root 16507 Mar 30 10:29 RUNNING.txt
drwxr-x--- 2 root root 4096 Mar 30 10:29 bin
drwx------ 2 root root 4096 Mar 30 10:29 conf
drwxr-x--- 2 root root 4096 Mar 30 10:29 lib
drwxr-xr-x 2 root root 4096 May 8 12:40 logs
drwxr-x--- 2 root root 4096 Mar 30 10:29 temp
drwxr-x--- 1 root root 4096 May 8 12:40 webapps
drwxr-x--- 2 root root 4096 Mar 30 10:29 work
5、启动服务
6、读取日志
2.3.8、发布镜像到DockerHub(重要)
1、前期准备
- 注册DockerHub账号
- 制作待发布镜像
2、命令行进行DockerHub(重要)
[root@hg14150 /]# 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
#登陆DockerHub
[root@hg14150 /]# docker login -u hg14150
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
#定义上传格式,作者名称一定要与DockerHub的ID一致
[root@hg14150 /]# docker tag centos-dev:1.0 hg14150/centos-dev:1.0
#发布镜像
[root@hg14150 /]# docker push hg14150/centos-dev:1.0
The push refers to repository [docker.io/hg14150/centos-dev]
fe64eec8c9df: Pushed
a1fb6e96249f: Pushed
2653d992f4ef: Pushed
1.0: digest: sha256:68e25fe1b8562c3823cfce7bf95542671deb29b7485811fe7de66a6fbe7d8231 size: 953
2.4、网络连接及镜像发布
1、网络地址分析
#本地回环地址
1: lo: inet 127.0.0.1/8 scope host lo
inet6 ::1/128 scope host
#服务器内网地址
2: eth0: inet 172.20.2.40/20 brd 172.20.15.255 scope global dynamic eth0
inet 172.20.2.40/20 brd 172.20.15.255 scope global dynamic eth0
#docker0初始地址
3: docker0: inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
inet6 fe80::42:2eff:feef:ba27/64 scope link
2、evth-pair技术
- linux系统提供的一套虚拟对外接口,成对出现,互相连接。提供了容器间的通信
- 启动容器查看规律
```shell
启动第一个tomcat容器
[root@hg14150 ~]# docker run -d -P —name tomcat-01 tomcat-dev:1.0 c41c4d69fa7ec2452d12faf0531530139197649efe109635ac2c8910619ba1c7
查看网络地址状态
[root@hg14150 ~]# docker exec -it tomcat-01 ip addr
1: lo:
docker分配第一个随机地址
124: eth0@if125:
启动第二个tomcat容器
[root@hg14150 ~]# docker run -d -P —name tomcat-02 tomcat-dev:1.0 0512270151f009774458ed19f721f4f84b5c43368ebdfbd370b01b011c4d690d
查看网络地址状态
[root@hg14150 ~]# docker exec -it tomcat-02 ip addr
1: lo:
#docker分配第二个随机地址
126: eth0@if127:
每启动一个容器,就会多一个docker分配的IP
[root@hg14150 ~]# ip addr
1: lo:
docker分配的IP地址
125: veth6628a9b@if124:
并且每一个分配的IP都能在本地或者公网ping通,也能连接
[root@hg14150 ~]# ping 172.17.0.2/3 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.059 ms 64 bytes from 172.17.0.2: icmp_seq=2 ttl=64 time=0.051 ms 64 bytes from 172.17.0.2: icmp_seq=3 ttl=64 time=0.050 ms 64 bytes from 172.17.0.2: icmp_seq=4 ttl=64 time=0.046 ms 64 bytes from 172.17.0.2: icmp_seq=5 ttl=64 time=0.064 ms 64 bytes from 172.17.0.2: icmp_seq=6 ttl=64 time=0.050 ms 64 bytes from 172.17.0.2: icmp_seq=7 ttl=64 time=0.043 ms 64 bytes from 172.17.0.2: icmp_seq=8 ttl=64 time=0.060 ms
两个容器之间也能相互ping/连接
[root@hg14150 ~]# docker exec -it tomcat-01 ping 172.17.0.3 PING 172.17.0.3 (172.17.0.3) 56(84) bytes of data. 64 bytes from 172.17.0.3: icmp_seq=1 ttl=64 time=0.110 ms 64 bytes from 172.17.0.3: icmp_seq=2 ttl=64 time=0.084 ms 64 bytes from 172.17.0.3: icmp_seq=3 ttl=64 time=0.061 ms 64 bytes from 172.17.0.3: icmp_seq=4 ttl=64 time=0.086 ms 64 bytes from 172.17.0.3: icmp_seq=5 ttl=64 time=0.076 ms 64 bytes from 172.17.0.3: icmp_seq=6 ttl=64 time=0.078 ms
- **docker分配的网络IP模型**<br />![](https://gitee.com/hg14150/blogiamges/raw/master/img/image-20210509103416401.png#crop=0&crop=0&crop=1&crop=1&id=jtrAi&originHeight=718&originWidth=1107&originalType=binary&ratio=1&rotation=0&showTitle=false&status=done&style=none&title=)
- docker0在网络连接中扮演的角色相当于桥梁中介,连接docker分配的IP,所有容器不指定网络的情况下,路由默认都是docker0:127.17.0.1
- **Docker在linux系统中使用的是默认docker0网桥**<br />![](https://gitee.com/hg14150/blogiamges/raw/master/img/image-20210509104014944.png#crop=0&crop=0&crop=1&crop=1&id=ELWgn&originHeight=653&originWidth=926&originalType=binary&ratio=1&rotation=0&showTitle=false&status=done&style=none&title=)
- **docker中的所有网络端口或IP都是虚拟的,提高了转发的效率,当然,删除容器,对应的网桥对就会消失**
```shell
#查看网络
[root@hg14150 ~]# docker network ls
NETWORK ID NAME DRIVER SCOPE
4d75f8b9202d bridge bridge local
d9dd7449663b host host local
d02c44a3f177 none null local
#查看网桥信息
[root@hg14150 ~]# docker network inspect bridge
{
"Name": "bridge",
"Id": "4d75f8b9202dc28c36f9658167c7244811cfce9706181b705762850b00600478",
"Created": "2021-05-07T21:31:24.86228954+08:00",
"Scope": "local",
"Driver": "bridge",
"EnableIPv6": false,
"IPAM": {
"Driver": "default",
"Options": null,
"Config": [
{
"Subnet": "172.17.0.0/16",
#docker0地址
"Gateway": "172.17.0.1"
}
]
}
}
3、link网络连接(已淘汰)
- 容器之间能不能通过容器名连接网络 ```shell [root@hg14150 ~]# docker exec -it tomcat-01 ping tomcat-02 ping: tomcat-02: Name or service not known
显然是不想的,那在docker分配地址过多时,该如何通过容器名相互来连接容器呢,下面开始揭晓答案
- **link连接,解决了网络层的问题**
```shell
#--link 单向连接tomcat-03——>tomcat-02
[root@hg14150 ~]# docker run -d -P --name tomcat-03 --link tomcat-02 tomcat-dev:1.0
5c4ef3159089acb9fad7441a63c2e9f330957ddf04af2e075cf1415fe0b141d9
[root@hg14150 ~]# docker exec -it tomcat-03 ping tomcat-02
PING tomcat-02 (172.17.0.3) 56(84) bytes of data.
64 bytes from tomcat-02 (172.17.0.3): icmp_seq=1 ttl=64 time=0.124 ms
64 bytes from tomcat-02 (172.17.0.3): icmp_seq=2 ttl=64 time=0.075 ms
64 bytes from tomcat-02 (172.17.0.3): icmp_seq=3 ttl=64 time=0.072 ms
64 bytes from tomcat-02 (172.17.0.3): icmp_seq=4 ttl=64 time=0.076 ms
64 bytes from tomcat-02 (172.17.0.3): icmp_seq=5 ttl=64 time=0.086 ms
#但是并不能反向连接
[root@hg14150 ~]# docker exec -it tomcat-02 ping tomcat-03
ping: tomcat-03: Name or service not known
docker network inspect bridge
- 查看tomcat-02/03hosts配置
```shell
tomcat-02 /etc/hosts
[root@hg14150 ~]# docker exec -it tomcat-02 cat /etc/hosts 127.0.0.1 localhost ::1 localhost ip6-localhost ip6-loopback fe00::0 ip6-localnet ff00::0 ip6-mcastprefix ff02::1 ip6-allnodes ff02::2 ip6-allrouters 172.17.0.3 0512270151f0
tomcat-03 /etc/hosts
[root@hg14150 ~]# docker exec -it tomcat-03 cat /etc/hosts 127.0.0.1 localhost ::1 localhost ip6-localhost ip6-loopback fe00::0 ip6-localnet ff00::0 ip6-mcastprefix ff02::1 ip6-allnodes ff02::2 ip6-allrouters
link在tomcat-03配置中新增了tomcat-02的网络地址172.17.0.3 tomcat-02 0512270151f0,并且时固定的,这导致了tomcat-03只能连接tomcat-02
172.17.0.3 tomcat-02 0512270151f0 172.17.0.4 5c4ef3159089
<a name="43067de0"></a>
#### 4、自定义网络
- **网络模式**
- bridge:桥接(docker默认)
- none : 不配置网络
- hosts : 共用主机网络
- container :容器内网络连接,有局限使用少
- **定义网络**
```shell
#使用默认docker0的网定义
docker run -d -P --name tomcat-01 tomcat-dev
#实际上是默认定义了docker0为网络路由的
docker run -d -P --name tomcat-01 --net bridge tomcat-dev
#######
#docker0的特点:
##1、docker默认使用
##2、域名不能直接访问,需要借助link连接
#######
#自定义网络
# --driver bridge 默认网络服务
# --subnet 192.168.0.0/16 配置子网
#--gateway 192.16.0.1 默认网关
[root@hg14150 ~]# docker network create --driver bridge --subnet 192.168.0.0/16 --gateway 192.168.0.1 net-dev
10ee4913b161c8de25dc39079f7a7a990392faf80ffa34a4ab90d7a3270c919a
[root@hg14150 ~]# docker network ls
NETWORK ID NAME DRIVER SCOPE
4d75f8b9202d bridge bridge local
d9dd7449663b host host local
10ee4913b161 net-dev bridge local
d02c44a3f177 none null local
#查看网络配置
[root@hg14150 ~]# docker network inspect net-dev
[
{
"Name": "net-dev",
"Id": "10ee4913b161c8de25dc39079f7a7a990392faf80ffa34a4ab90d7a3270c919a",
"Created": "2021-05-09T11:21:59.353942175+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": {}
}
]
- 自定义网络
- 自定义网络配置
- 设置网络连接
```shell
启动自定义网络的容器
[root@hg14150 ~]# docker run -d -P —name tomcat-net-01 —net net-dev tomcat-dev:1.0 8072b81ec837276c196c4aa665a3c20b7daeb41644e5aaf57f1f680a12cdb9ba [root@hg14150 ~]# docker run -d -P —name tomcat-net-02 —net net-dev tomcat-dev:1.0 8200ee9c6efa30b99a19a673f3f16decd9e91bbed10a86caa9beef9676e7b702
通过IP地址连接容器
[root@hg14150 ~]# docker exec -it tomcat-net-01 ping 192.168.0.3 PING 192.168.0.3 (192.168.0.3) 56(84) bytes of data. 64 bytes from 192.168.0.3: icmp_seq=1 ttl=64 time=0.086 ms 64 bytes from 192.168.0.3: icmp_seq=2 ttl=64 time=0.082 ms 64 bytes from 192.168.0.3: icmp_seq=3 ttl=64 time=0.074 ms
通过域名连接容器
[root@hg14150 ~]# docker exec -it tomcat-net-01 ping tomcat-net-02 PING tomcat-net-02 (192.168.0.3) 56(84) bytes of data. 64 bytes from tomcat-net-02.net-dev (192.168.0.3): icmp_seq=1 ttl=64 time=0.105 ms 64 bytes from tomcat-net-02.net-dev (192.168.0.3): icmp_seq=2 ttl=64 time=0.075 ms 64 bytes from tomcat-net-02.net-dev (192.168.0.3): icmp_seq=3 ttl=64 time=0.086 ms 64 bytes from tomcat-net-02.net-dev (192.168.0.3): icmp_seq=4 ttl=64 time=0.068 ms
- **打通默认网络与自定义网络的连接**
```shell
#实际上,默认网络docker0的网络和自定义的网络是不能直接连接的
#tomcat-01:默认网络
#tomcat-net-01:自定义网络
#因此需要connect来打通连接
[root@hg14150 ~]# docker network connect net-dev tomcat-01
#连接tomcat-01和tomcat-net-01
[root@hg14150 ~]# docker exec -it tomcat-01 ping tomcat-net-01
PING tomcat-net-01 (192.168.0.2) 56(84) bytes of data.
64 bytes from tomcat-net-01.net-dev (192.168.0.2): icmp_seq=1 ttl=64 time=0.072 ms
64 bytes from tomcat-net-01.net-dev (192.168.0.2): icmp_seq=2 ttl=64 time=0.060 ms
64 bytes from tomcat-net-01.net-dev (192.168.0.2): icmp_seq=3 ttl=64 time=0.073 ms
64 bytes from tomcat-net-01.net-dev (192.168.0.2): icmp_seq=4 ttl=64 time=0.070 ms
64 bytes from tomcat-net-01.net-dev (192.168.0.2): icmp_seq=5 ttl=64 time=0.062 ms
64 bytes from tomcat-net-01.net-dev (192.168.0.2): icmp_seq=6 ttl=64 time=0.060 ms
- connect连接原理
- 总结
- 自定义网络可以通过IP及域名连接容器
- 便于后期维护
- redis——不同的集群使用不同的网络,保证集群的安全与健康
- MySQL——不同的集群使用不同的网络,保证集群的安全与健康
2.5、redis集群(重点)
1、需求分析
- 分片+高可用+均衡负载,三主三从的集群,当三台主机中的某台或某多台主机宕机后,从机能够快速补上,防止数据崩塌
2、创建redis网络服务
#创建redis网络服务
[root@hg14150 ~]# docker network create redis --subnet 172.38.0.0/16
fc5df114eadcd3c8e4d5966ffd74bb1d4e3b94444f820f901f5b1d10e0577b74
[root@hg14150 ~]# docker network ls
NETWORK ID NAME DRIVER SCOPE
4d75f8b9202d bridge bridge local
d9dd7449663b host host local
10ee4913b161 net-dev bridge local
d02c44a3f177 none null local
fc5df114eadc redis bridge local
[root@hg14150 ~]# docker network inspect redis
[
{
"Name": "redis",
"Id": "fc5df114eadcd3c8e4d5966ffd74bb1d4e3b94444f820f901f5b1d10e0577b74",
"Created": "2021-05-09T13:07:16.997348876+08:00",
"Scope": "local",
"Driver": "bridge",
"EnableIPv6": false,
"IPAM": {
"Driver": "default",
"Options": {},
"Config": [
{
"Subnet": "172.38.0.0/16"
}
]
},
"Internal": false,
"Attachable": false,
"Ingress": false,
"ConfigFrom": {
"Network": ""
},
"ConfigOnly": false,
"Containers": {},
"Options": {},
"Labels": {}
}
]
3、创建redis集群
#创建redis集群
# 通过脚本创建六个redis配置
#创建6个redis服务
[root@hg14150 ~]for port in $(seq 1 6);\
do \
#创建redis配置文件 /mydata/redis/node-${port}/conf
mkdir -p /mydata/redis/node-${port}/conf
#创建redis服务具体配置 /mydata/redis/node-${port}/conf/redis.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
#重点,开启redis集群
cluster-enabled yes
cluster-config-file nodes.conf
cluster-node-timeout 5000
cluster-announce-ip 172.38.0.1${port}
cluster-announce-port 6379
cluster-announce-bus-port 16379
appendonly yes
EOF
done
4、开启redis集群服务
# 通过脚本运行六个redis
# 在命令/mydata/redis/node-${port}/conf下运行
[root@hg14150 conf]for port in $(seq 1 6);\
docker run -p 637${port}:6379 -p 1667${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
#redis默认没有bash
[root@hg14150 conf]docker exec -it redis-1 /bin/sh
#启动的时候要一个一个启动/mydata/redis/node-1/conf
[root@hg14150 conf]docker run -p 6371:6379 -p 16671:16379 --name redis-1 \
-v /mydata/redis/node-1/data:/data \
-v /mydata/redis/node-1/conf/redis.conf:/etc/redis/redis.conf \
-d --net redis --ip 172.38.0.11 redis:5.0.9-alpine3.11 redis-server /etc/redis/redis.conf
#剩下的也是如此
5、设置集群服务
#配置集群 docker exec -it redis-1 /bin/sh,进入/bin/sh目录下进行
/data # redis-cli --cluster create 172.38.0.11:6379 172.38.0.12:6379 172.38.0.13:6379 172.38.0.14:6379 172.38.0.15:6379 172.38.0.16:6379 --cluster-replicas 1
>>> Performing hash slots allocation on 6 nodes...
#主机
Master[0] -> Slots 0 - 5460
Master[1] -> Slots 5461 - 10922
Master[2] -> Slots 10923 - 16383
#从机
Adding replica 172.38.0.15:6379 to 172.38.0.11:6379
Adding replica 172.38.0.16:6379 to 172.38.0.12:6379
Adding replica 172.38.0.14:6379 to 172.38.0.13:6379
M: d944e80c43e91234a49905800c5c8d3b5b7c867f 172.38.0.11:6379
slots:[0-5460] (5461 slots) master
M: 0be66d379573ce4d19fb2a623246b354c902e759 172.38.0.12:6379
slots:[5461-10922] (5462 slots) master
M: 7079d3acd263ce0a3fdabd9a82292122a9a720b0 172.38.0.13:6379
slots:[10923-16383] (5461 slots) master
S: f88fcd67ac04dfce13f4d12dcb065517fa976848 172.38.0.14:6379
replicates 7079d3acd263ce0a3fdabd9a82292122a9a720b0
S: ad9382b9b6b89d46b9788913b027debcea46bc4f 172.38.0.15:6379
replicates d944e80c43e91234a49905800c5c8d3b5b7c867f
S: 5fb807ce393c72a02d37b6755c1a005dfbaf9d1b 172.38.0.16:6379
replicates 0be66d379573ce4d19fb2a623246b354c902e759
#yes
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: d944e80c43e91234a49905800c5c8d3b5b7c867f 172.38.0.11:6379
slots:[0-5460] (5461 slots) master
1 additional replica(s)
S: 5fb807ce393c72a02d37b6755c1a005dfbaf9d1b 172.38.0.16:6379
slots: (0 slots) slave
replicates 0be66d379573ce4d19fb2a623246b354c902e759
M: 0be66d379573ce4d19fb2a623246b354c902e759 172.38.0.12:6379
slots:[5461-10922] (5462 slots) master
1 additional replica(s)
S: ad9382b9b6b89d46b9788913b027debcea46bc4f 172.38.0.15:6379
slots: (0 slots) slave
replicates d944e80c43e91234a49905800c5c8d3b5b7c867f
S: f88fcd67ac04dfce13f4d12dcb065517fa976848 172.38.0.14:6379
slots: (0 slots) slave
replicates 7079d3acd263ce0a3fdabd9a82292122a9a720b0
M: 7079d3acd263ce0a3fdabd9a82292122a9a720b0 172.38.0.13:6379
slots:[10923-16383] (5461 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.
6、查看集群
#查看集群信息
/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:227
cluster_stats_messages_pong_sent:251
cluster_stats_messages_sent:478
cluster_stats_messages_ping_received:246
cluster_stats_messages_pong_received:227
cluster_stats_messages_meet_received:5
cluster_stats_messages_received:478
#查看集群服务
127.0.0.1:6379> cluster nodes
d944e80c43e91234a49905800c5c8d3b5b7c867f 172.38.0.11:6379@16379 myself,master - 0 1620540069000 1 connected 0-5460
5fb807ce393c72a02d37b6755c1a005dfbaf9d1b 172.38.0.16:6379@16379 slave 0be66d379573ce4d19fb2a623246b354c902e759 0 1620540068540 6 connected
0be66d379573ce4d19fb2a623246b354c902e759 172.38.0.12:6379@16379 master - 0 1620540068038 2 connected 5461-10922
ad9382b9b6b89d46b9788913b027debcea46bc4f 172.38.0.15:6379@16379 slave d944e80c43e91234a49905800c5c8d3b5b7c867f 0 1620540069042 5 connected
f88fcd67ac04dfce13f4d12dcb065517fa976848 172.38.0.14:6379@16379 slave 7079d3acd263ce0a3fdabd9a82292122a9a720b0 0 1620540068000 4 connected
7079d3acd263ce0a3fdabd9a82292122a9a720b0 172.38.0.13:6379@16379 master - 0 1620540069544 3 connected 10923-16383
7、测试集群
#传入数据
127.0.0.1:6379> set a b
#分配主机3号接管数据
-> Redirected to slot [15495] located at 172.38.0.13:6379
OK
#停止3号主机,从机补上
[root@hg14150 ~]# docker stop redis-3
redis-3
#查询传入的值
/data # redis-cli -c
127.0.0.1:6379> get a
#172.38.0.14:6379 从机调结果,并且4号成为主机,在启动3号时,3号成为从机
-> Redirected to slot [15495] located at 172.38.0.14:6379
"b"
#redis集群故障转移成功实现
三、Docker核心技术
3.1、SpringBoot集成Docker
1、准备好好要发布的springboot项目,打成jar包
2、创建Dockerfile文件并编辑镜像容器内容
#1、将jar包上传至linux指定文件目录下
#2、在项目主目录下创建Dockerfile文件,一定要是Dockerfile
#3、编辑镜像发布内容
#4、以笔记代码为准
#基础镜像为java8
FROM java:8
#添加开发者信息
MAINTAINER bingo<hlgc14150@163.com>
#添加jar包 重命名jar包
ADD spring-boot-project-01-0.0.1-SNAPSHOT.jar hguoweb.jar
#暴露端口
EXPOSE 8080
#执行运行命令
ENTRYPOINT ["java","-jar","hguoweb.jar"]
###Dockerfile编写规则:
FROM # 基于哪个基础镜像构建
MAINTAINER # 镜像作者的信息
RUN # 容器镜像构建的时候需要运行的命令
ADD # 在这个镜像中放置的软件压缩包,会自动解压
WORKDIR # 镜像的工作目录
VOLUME # 给镜像指定挂在卷
EXPOSE # 对外暴露的端口
CMD # 容器启动后执行的命令,可以被替代,只有最后一个会生效, (通常用于启动我们的应用)
ENTRYPOINT # 容器启动后执行的命令,可以追加
ONBUILD
COPY # 和add类似,将压缩包拷贝进镜像中
ENV # 构建时,设置环境变量,如设置mysql的用户名密码
----以上关键字必须大写
3、在linux下创建对应目录,将jar包跟Dockerfile上传
4、构建发布镜像
#查看上传情况
[root@hg14150 java]# ll
total 18620
-rw-r--r-- 1 root root 275 May 9 14:49 Dockerfile
-rw-r--r-- 1 root root 19059833 May 9 14:49 spring-boot-project-01-0.0.1-SNAPSHOT.jar
#构建名称为 hg14150/hguoweb,版本默认的镜像 最后面的点不能忽略
[root@hg14150 java]# docker build -t hg14150/hguoweb .
Sending build context to Docker daemon 19.06MB
Step 1/5 : FROM java:8
---> d23bdf5b1b1b
Step 2/5 : MAINTAINER bingo<hlgc14150@163.com>
---> Running in 61d54a12b482
Removing intermediate container 61d54a12b482
---> ab853025e614
Step 3/5 : ADD spring-boot-project-01-0.0.1-SNAPSHOT.jar hguoweb.jar
---> b1b3e5576ce5
Step 4/5 : EXPOSE 8080
---> Running in d848b4f73bb9
Removing intermediate container d848b4f73bb9
---> 8082d657e059
Step 5/5 : ENTRYPOINT ["java","-jar","hguoweb.jar"]
---> Running in 435dba81451a
Removing intermediate container 435dba81451a
---> b3458451c4d9
Successfully built b3458451c4d9
Successfully tagged hg14150/hguoweb:latest
#查看镜像构建情况
[root@hg14150 java]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
hg14150/hguoweb latest b3458451c4d9 6 seconds ago 662MB
hg/centos 1.0 585fbf640ca7 44 hours ago 209MB
tomcat-dev 1.0 ec6f8010be89 2 days ago 672MB
5、运行镜像
#运行容器
[root@hg14150 java]# docker run -d -p 8889:8080 --name hguo-javaweb hg14150/hguoweb
a118d8563e277a97c4fecefc654e5922c5af11fe139c50d8fd1f9ad1f8236e9b
#查看容器
[root@hg14150 java]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS POR NAMES
a118d8563e27 hg14150/hguoweb "java -jar hguoweb.j…" 9 seconds ago Up 8 seconds 0.0.0.0:8889->8080/tcp, :::8889->8080/tcp hguo-javaweb
6、运行测试
- 本地运行
- 公网运行
- 参考文档
https://www.cnblogs.com/ZhuChangwu/p/13686744.html
3.2、Compose的使用
3.2.1、Docker Compose入门
1、理解Compose
- 如果需要集群大量服务时,为节省时间、维护等成本,提高效率。集群需要批量操作,这就引入了容器编排的理念
- Compose是官方开源项目,类似插件,需要另行安装
- 使用 Docker Compose 可以轻松、高效的管理容器,它是一个用于定义和运行多容器 Docker 的应用程序工具,一次定义、运行多个容器或
- Docker Compose 将所管理的容器分为三层
- 工程(project)
- 服务(service)
- 容器(container)
- Docker Compose 运行目录下的所有文件(docker-compose.yml)组成一个工程,一个工程包含多个服务,每个服务中定义了容器运行的镜像、参数、依赖,一个服务可包括多个容器实例
2、安装Compose
- 下载压缩包
```shell
下载地址
sudo curl -L “https://github.com/docker/compose/releases/download/1.29.1/docker-compose-$(uname -s)-$(uname -m)” -o /usr/local/bin/docker-compose授权
chmod +x /usr/local/bin/docker-compose
镜像加速地址,建议使用
curl -L https://get.daocloud.io/docker/compose/releases/download/1.26.2/docker-compose-`uname -s-
uname -m` > /usr/local/bin/docker-compose
授权
chmod +x /usr/local/bin/docker-compose 123456
- **安装**
```shell
[root@hg14150 ~]# curl -L https://get.daocloud.io/docker/compose/releases/download/1.26.2/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose
#下载路径/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 251 0 0:00:01 0:00:01 --:--:-- 251
100 11.6M 100 11.6M 0 0 4868k 0 0:00:02 0:00:02 --:--:-- 22.1M
#授权
chmod +x /usr/local/bin/docker-compose
#查看版本,授权后docker-compose文件会变高亮
[root@hg14150 bin]# docker-compose version
docker-compose version 1.26.2, build eefe0d31
docker-py version: 4.2.2
CPython version: 3.7.7
OpenSSL version: OpenSSL 1.1.0l 10 Sep 2019
- 授权前后变化
- 授权前
- 授权后
- 授权前
3、Compose配置
第一层,版本信息
version: ‘’ #版本
第二层,服务
service:
服务1: web
#服务配置
images
build
network
.....
服务2: reids
.....
服务3: ....
.....
第三层,其他配置 网络/卷、全局规则
volumes: networks: configs:
- **docker-compose.yaml案例**
```shell
version: "2.4"
services:
web:
build: .
ports:
- "5000:5000"
volumes:
- .:/code
networks:
- front-tier
- back-tier
redis:
image: redis
volumes:
- redis-data:/var/lib/redis
networks:
- back-tier
volumes:
redis-data:
driver: local
networks:
front-tier:
driver: bridge
back-tier:
driver: bridge
- 版本号以官网的为例
3.2.2服务部署
1、Compose部署服务上线
- 需求分析
2、创建一个文件app.py,就是创建一个python文件
[root@hg14150 compose]# vim app.py
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)
[root@hg14150 compose]# cat app.py
3、创建导入依赖包
[root@hg14150 compose]# vim requirements.txt [root@hg14150 compose]# cat requirements.txt flask redis
第二步:环境配置
1、创建Dockerfile
[root@hg14150 compose]# vim Dockerfile
FROM python:3.7-alpine WORKDIR /code ENV FLASK_APP=app.py ENV FLASK_RUN_HOST=0.0.0.0 RUN apk add —no-cache gcc musl-dev linux-headers COPY requirements.txt requirements.txt RUN pip install -r requirements.txt EXPOSE 5000 COPY . . CMD [“flask”, “run”]
[root@hg14150 compose]# cat Dockerfile
#第三步:定义服务
1、在compose文件中定义service
[root@hg14150 compose]# vim docker-compose.yml [root@hg14150 compose]# cat docker-compose.yml version: “3” services: web: build: . ports:
- "5000:5000"
redis: image: “redis:alpine”
version太新会报错,将版本降低就可以了
#第四步:启动并运行
1、构建并运行服务
[root@hg14150 compose]# docker-compose up
- **compose服务启动过程**
```shell
[root@hg14150 composetest]# docker-compose up
Building web
Sending build context to Docker daemon 5.632kB
Step 1/10 : FROM python:3.7-alpine
---> ec8ed031b5be
Step 2/10 : WORKDIR /code
---> Using cache
---> 876f16a2de1c
Step 3/10 : ENV FLASK_APP=app.py
---> Using cache
---> cb215cbe364d
Step 4/10 : ENV FLASK_RUN_HOST=0.0.0.0
---> Using cache
---> 48e040a71924
Step 5/10 : RUN apk add --no-cache gcc musl-dev linux-headers
---> Running in 211a4ed11f7d
fetch https://dl-cdn.alpinelinux.org/alpine/v3.13/main/x86_64/APKINDEX.tar.gz
fetch https://dl-cdn.alpinelinux.org/alpine/v3.13/community/x86_64/APKINDEX.tar.gz
(1/13) Installing libgcc (10.2.1_pre1-r3)
(2/13) Installing libstdc++ (10.2.1_pre1-r3)
(3/13) Installing binutils (2.35.2-r1)
(4/13) Installing libgomp (10.2.1_pre1-r3)
(5/13) Installing libatomic (10.2.1_pre1-r3)
(6/13) Installing libgphobos (10.2.1_pre1-r3)
(7/13) Installing gmp (6.2.1-r0)
(8/13) Installing isl22 (0.22-r0)
(9/13) Installing mpfr4 (4.1.0-r0)
(10/13) Installing mpc1 (1.2.0-r0)
(11/13) Installing gcc (10.2.1_pre1-r3)
(12/13) Installing linux-headers (5.7.8-r0)
(13/13) Installing musl-dev (1.2.2-r0)
Executing busybox-1.32.1-r6.trigger
OK: 139 MiB in 48 packages
Removing intermediate container 211a4ed11f7d
---> ea68b9e675ce
Step 6/10 : COPY requirements.txt requirements.txt
---> e8b29c7853b4
Step 7/10 : RUN pip install -r requirements.txt
---> Running in ad6a2e18aea9
Collecting flask
Downloading Flask-1.1.2-py2.py3-none-any.whl (94 kB)
Collecting redis
Downloading redis-3.5.3-py2.py3-none-any.whl (72 kB)
Collecting itsdangerous>=0.24
Downloading itsdangerous-1.1.0-py2.py3-none-any.whl (16 kB)
Collecting click>=5.1
Downloading click-7.1.2-py2.py3-none-any.whl (82 kB)
Collecting Jinja2>=2.10.1
Downloading Jinja2-2.11.3-py2.py3-none-any.whl (125 kB)
Collecting Werkzeug>=0.15
Downloading Werkzeug-1.0.1-py2.py3-none-any.whl (298 kB)
Collecting MarkupSafe>=0.23
Downloading MarkupSafe-1.1.1.tar.gz (19 kB)
Building wheels for collected packages: MarkupSafe
Building wheel for MarkupSafe (setup.py): started
Building wheel for MarkupSafe (setup.py): finished with status 'done'
Created wheel for MarkupSafe: filename=MarkupSafe-1.1.1-cp37-cp37m-linux_x86_64.whl size=17026 sha256=6a999f0d436707c7f913cadbee2a3dbe17e60485c56956a6722288cdbc6484e3
Stored in directory: /root/.cache/pip/wheels/b9/d9/ae/63bf9056b0a22b13ade9f6b9e08187c1bb71c47ef21a8c9924
Successfully built MarkupSafe
Installing collected packages: MarkupSafe, Werkzeug, Jinja2, itsdangerous, click, redis, flask
Successfully installed Jinja2-2.11.3 MarkupSafe-1.1.1 Werkzeug-1.0.1 click-7.1.2 flask-1.1.2 itsdangerous-1.1.0 redis-3.5.3
WARNING: Running pip as root will break packages and permissions. You should install packages reliably by using venv: https://pip.pypa.io/warnings/venv
Removing intermediate container ad6a2e18aea9
---> 2c7b7e2be931
Step 8/10 : EXPOSE 5000
---> Running in a643013a99ce
Removing intermediate container a643013a99ce
---> f2b422ee80a0
Step 9/10 : COPY . .
---> f2842de43b27
Step 10/10 : CMD ["flask", "run"]
---> Running in 6f34c5f85045
Removing intermediate container 6f34c5f85045
---> db913e4ee592
Successfully built db913e4ee592
Successfully tagged composetest_web:latest
WARNING: Image for service web was built because it did not already exist. To rebuild this image you must use `docker-compose build` or `docker-compose up --build`.
Creating composetest_web_1 ... done
Creating composetest_redis_1 ... done
Attaching to composetest_redis_1, composetest_web_1
redis_1 | 1:C 10 May 2021 08:01:40.322 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
redis_1 | 1:C 10 May 2021 08:01:40.322 # Redis version=6.2.3, bits=64, commit=00000000, modified=0, pid=1, just started
redis_1 | 1:C 10 May 2021 08:01:40.322 # 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 10 May 2021 08:01:40.322 * monotonic clock: POSIX clock_gettime
redis_1 | 1:M 10 May 2021 08:01:40.323 * Running mode=standalone, port=6379.
redis_1 | 1:M 10 May 2021 08:01:40.323 # 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 10 May 2021 08:01:40.323 # Server initialized
redis_1 | 1:M 10 May 2021 08:01:40.323 # 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 10 May 2021 08:01:40.324 * Ready to accept connections
web_1 | * Serving Flask app "app.py"
web_1 | * Environment: production
web_1 | WARNING: This is a development server. Do not use it in a production deployment.
web_1 | Use a production WSGI server instead.
web_1 | * Debug mode: off
web_1 | * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
- 停止服务
[root@hg14150 wordpress-dev]# docker-compose down
Removing wordpress-dev_wordpress_1 ... done
Removing wordpress-dev_db_1 ... done
Removing network wordpress-dev_default
- 镜像情况
- 容器情况
- 访问分析,访问一次打印就增加一次
- 流程分析
- 创建容器文件 mkdir compose-file
- cd compose-file
- vim 项目
- vim 导入类
- vim Docker-compose.yaml
- 执行Docker-compose.yaml
- 启动服务docker-compose up (根据定义的services自动生成)
- crate compose_web
- creat compose_redis
- 创建容器文件 mkdir compose-file
2、一键部署WP博客
1、新建容器文件 mkdir composefile
[root@hg14150 home]# mkdir wordpress-dev
[root@hg14150 home]# cd wordpress-dev/
2、配置docker-compose.yaml文件
[root@hg14150 wordpress-dev]# vim docker-compose.yml
version: "3.9"
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: {}
[root@hg14150 wordpress-dev]# cat docker-compose.yml
3、docker-compose up 一键启动
[root@hg14150 wordpress-dev]# docker-compose up
Creating network "wordpress-dev_default" with the default driver
Creating volume "wordpress-dev_db_data" with default driver
Pulling wordpress (wordpress:latest)...
latest: Pulling from library/wordpress
f7ec5a41d630: Already exists
941223b59841: Pull complete
a5f2415e5a0c: Pull complete
b9844b87f0e3: Pull complete
5a07de50525b: Pull complete
caeca1337a66: Pull complete
5dbe0d7f8481: Pull complete
b5287b60e185: Pull complete
a3bdca77fbaf: Pull complete
e3edcade6aa2: Pull complete
703ba034e6f0: Pull complete
36ef47972442: Pull complete
4acb239a9263: Pull complete
e74d610ba693: Pull complete
97f505d02f6f: Pull complete
d6dd6701aaec: Pull complete
43ef3ceb4f4b: Pull complete
a59b940a007f: Pull complete
714359ef8f41: Pull complete
24b7e9a8c62d: Pull complete
b400ea29ad59: Pull complete
Digest: sha256:208def35d7fcbbfd76df18997ce6cd5a5221c0256221b7fdaba41c575882d4f0
Status: Downloaded newer image for wordpress:latest
Creating wordpress-dev_db_1 ... done
Creating wordpress-dev_wordpress_1 ... done
Attaching to wordpress-dev_db_1, wordpress-dev_wordpress_1
4、停止服务
[root@hg14150 wordpress-dev]# docker-compose down
Removing wordpress-dev_wordpress_1 ... done
Removing wordpress-dev_db_1 ... done
Removing network wordpress-dev_default
- 容器启动情况
5、启动结果
6、总结
集群部署的基本步骤
- 开发项目并打包(配置文件及Dockerfile打包在内)
- dockerfile构建镜像
- docker-compose.yaml项目编排
- docker-compose up -d 一键启动
3.3、集群搭建
- swam集群搭建具体文档如下
cnblogs.com/zhujingzhi/p/9792432.html