likes
comments
collection
share

Docker 详解与微服务部署实战

作者站长头像
站长
· 阅读数 19

Docker简介

Docker 详解与微服务部署实战

Docker 于 2013年发布,是一个开源的容器引擎,它有助于更快地交付应用。 Docker可将应用程序和基础设施层隔离,并且能将基础设施当作程序一样进行管理。使用 Docker可更快地打包、测试以及部署应用程序,并可以缩短从编写到部署运行代码的周期。

Docker的优点如下:

1、简化程序

Docker 让开发者可以打包他们的应用以及依赖包到一个可移植的容器中,然后发布到任何流行的 Linux 机器上,便可以实现虚拟化。Docker改变了虚拟化的方式,使开发者可以直接将自己的成果放入Docker中进行管理。方便快捷已经是 Docker的最大优势,过去需要用数天乃至数周的 任务,在Docker容器的处理下,只需要数秒就能完成。

2、避免选择恐惧症

如果你有选择恐惧症,还是资深患者。Docker 帮你 打包你的纠结!比如 Docker 镜像;Docker 镜像中包含了运行环境和配置,所以 Docker 可以简化部署多种应用实例工作。比如 Web 应用、后台应用、数据库应用、大数据应用比如 Hadoop 集群、消息队列等等都可以打包成一个镜像部署。

3、节省开支

一方面,云计算时代到来,使开发者不必为了追求效果而配置高额的硬件,Docker 改变了高性能必然高价格的思维定势。

Docker 与云的结合,让云空间得到更充分的利用。不仅解决了硬件管理的问题,也改变了虚拟化的方式。

Docker的架构

Docker 详解与微服务部署实战

  • Docker daemon( Docker守护进程)

Docker daemon是一个运行在宿主机( DOCKER-HOST)的后台进程。可通过 Docker客户端与之通信。

  • Client( Docker客户端)

Docker客户端是 Docker的用户界面,它可以接受用户命令和配置标识,并与 Docker daemon 通信。图中, docker build 等都是 Docker 的相关命令。

  • Images( Docker镜像)

Docker 镜像是一个只读模板,它包含创建 Docker 容器的说明。它和系统安装光盘有点像,使用系统安装光盘可以安装系统,同理,使用Docker 镜像可以运行 Docker 镜像中的程序。

  • Container(容器)

容器是镜像的可运行实例。镜像和容器的关系有点类似于面向对象中,类和对象的关系。可通过 Docker API 或者 CLI 命令来启停、移动、删除容器。

  • Registry

Docker Registry 是一个集中存储与分发镜像的服务。构建完 Docker 镜像后,就可在当前宿主机上运行。但如果想要在其他机器上运行这个镜像,就需要手动复制。此时可借助 Docker Registry 来避免镜像的手动复制。

一个 Docker Registry 可包含多个 Docker 仓库,每个仓库可包含多个镜像标签,每个标签对应一个 Docker 镜像。这跟Maven的仓库有点类似,如果把 Docker Registry 比作 Maven 仓库的话,那么 Docker 仓库就可理解为某jar包的路径,而镜像标签则可理解为jar包的版本号。

Docker Registry 可分为公有 Docker Registry 和私有 Docker Registry。 最常⽤的 Docker Registry 莫过于官⽅的 Docker Hub, 这也是默认的 Docker Registry。 Docker Hub 上存放着⼤量优秀的镜像, 我们可使⽤ Docker 命令下载并使⽤。

Docker 的安装

Docker 是一个开源的商业产品,有两个版本:社区版(Community Edition,缩写为 CE)和企业版(Enterprise Edition,缩写为 EE)。企业版包含了一些收费服务,个人开发者一般用不到。下面的介绍都针对社区版。

Docker CE 的安装请参考官方文档,我们这里以CentOS为例:

1、Docker 要求 CentOS 系统的内核版本高于 3.10

通过 uname -r 命令查看你当前的内核版本

[root@localhost ~]# uname -r
3.10.0-1160.90.1.el7.x86_64
[root@localhost ~]# 

2、使用 root 权限登录 Centos。确保 yum 包更新到最新。

[root@localhost ~]# yum ‐y update

3、卸载旧版本(如果安装过旧版本的话)

##卸载所有包文件
[root@localhost ~]# sudo yum remove ‐y docker*
##也可以查出来,逐一卸载
[root@localhost ~]# rpm -qa|grep docker
docker-ce-rootless-extras-24.0.2-1.el7.x86_64
docker-ce-cli-24.0.2-1.el7.x86_64
docker-buildx-plugin-0.10.5-1.el7.x86_64
docker-compose-plugin-2.18.1-1.el7.x86_64
docker-ce-24.0.2-1.el7.x86_64
[root@localhost ~]# yum remove docker-ce-rootless-extras-24.0.2-1.el7.x86_64 docker-ce-cli-24.0.2-1.el7.x86_64 docker-buildx-plugin-0.10.5-1.el7.x86_64 docker-compose-plugin-2.18.1-1.el7.x86_64 docker-ce-24.0.2-1.el7.x86_64
已加载插件:fastestmirror, product-id, search-disabled-repos, subscription-manager

This system is not registered with an entitlement server. You can use subscription-manager to register.

正在解决依赖关系
--> 正在检查事务
---> 软件包 docker-buildx-plugin.x86_64.0.0.10.5-1.el7 将被 删除
---> 软件包 docker-ce.x86_64.3.24.0.2-1.el7 将被 删除
---> 软件包 docker-ce-cli.x86_64.1.24.0.2-1.el7 将被 删除
---> 软件包 docker-ce-rootless-extras.x86_64.0.24.0.2-1.el7 将被 删除
---> 软件包 docker-compose-plugin.x86_64.0.2.18.1-1.el7 将被 删除
--> 解决依赖关系完成

依赖关系解决

=================================================================================================================================================================================================================
 Package                                                     架构                                     版本                                             源                                                   大小
=================================================================================================================================================================================================================
正在删除:
 docker-buildx-plugin                                        x86_64                                   0.10.5-1.el7                                     @docker-ce-stable                                    54 M
 docker-ce                                                   x86_64                                   3:24.0.2-1.el7                                   @docker-ce-stable                                    98 M
 docker-ce-cli                                               x86_64                                   1:24.0.2-1.el7                                   @docker-ce-stable                                    35 M
 docker-ce-rootless-extras                                   x86_64                                   24.0.2-1.el7                                     @docker-ce-stable                                    19 M
 docker-compose-plugin                                       x86_64                                   2.18.1-1.el7                                     @docker-ce-stable                                    52 M

事务概要
=================================================================================================================================================================================================================
移除  5 软件包

安装大小:258 M
是否继续?[y/N]:y
Downloading packages:
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  正在删除    : docker-ce-rootless-extras-24.0.2-1.el7.x86_64                                                                                                                                                1/5 
  正在删除    : 3:docker-ce-24.0.2-1.el7.x86_64                                                                                                                                                              2/5 
  正在删除    : 1:docker-ce-cli-24.0.2-1.el7.x86_64                                                                                                                                                          3/5 
  正在删除    : docker-buildx-plugin-0.10.5-1.el7.x86_64                                                                                                                                                     4/5 
  正在删除    : docker-compose-plugin-2.18.1-1.el7.x86_64                                                                                                                                                    5/5 
  验证中      : docker-compose-plugin-2.18.1-1.el7.x86_64                                                                                                                                                    1/5 
  验证中      : 3:docker-ce-24.0.2-1.el7.x86_64                                                                                                                                                              2/5 
  验证中      : 1:docker-ce-cli-24.0.2-1.el7.x86_64                                                                                                                                                          3/5 
  验证中      : docker-ce-rootless-extras-24.0.2-1.el7.x86_64                                                                                                                                                4/5 
  验证中      : docker-buildx-plugin-0.10.5-1.el7.x86_64                                                                                                                                                     5/5 

删除:
  docker-buildx-plugin.x86_64 0:0.10.5-1.el7  docker-ce.x86_64 3:24.0.2-1.el7  docker-ce-cli.x86_64 1:24.0.2-1.el7  docker-ce-rootless-extras.x86_64 0:24.0.2-1.el7  docker-compose-plugin.x86_64 0:2.18.1-1.el7 

完毕!

4、安装需要的软件包, yum-util 提供yum-config-manager功能,另外两个是devicemapper驱动依赖的

[root@localhost ~]# yum install -y yum-utils
已加载插件:fastestmirror, product-id, search-disabled-repos, subscription-manager

This system is not registered with an entitlement server. You can use subscription-manager to register.

Loading mirror speeds from cached hostfile
 * base: mirrors.bfsu.edu.cn
 * epel: ftp.iij.ad.jp
 * extras: mirrors.bfsu.edu.cn
 * updates: mirrors.qlu.edu.cn
软件包 yum-utils-1.1.31-54.el7_8.noarch 已安装并且是最新版本
无须任何处理 //因为我这里已经安装过了

5、设置yum源,并更新 yum 的包索引

[root@localhost ~]# yum-config-manager \
> --add-repo \
> https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
已加载插件:fastestmirror, product-id, subscription-manager

This system is not registered with an entitlement server. You can use subscription-manager to register.

adding repo from: https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
grabbing file https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo to /etc/yum.repos.d/docker-ce.repo
repo saved to /etc/yum.repos.d/docker-ce.repo

6、可以查看所有仓库中所有docker版本,并选择特定版本安装

[root@localhost ~]# yum list docker-ce --showduplicates | sort -r
已加载插件:fastestmirror, product-id, search-disabled-repos, subscription-manager
可安装的软件包
 * updates: mirrors.qlu.edu.cn
This system is not registered with an entitlement server. You can use subscription-manager to register.
Loading mirror speeds from cached hostfile
 * extras: mirrors.bfsu.edu.cn
 * epel: ftp.iij.ad.jp
docker-ce.x86_64            3:24.0.2-1.el7                      docker-ce-stable
docker-ce.x86_64            3:24.0.1-1.el7                      docker-ce-stable
docker-ce.x86_64            3:24.0.0-1.el7                      docker-ce-stable
docker-ce.x86_64            3:23.0.6-1.el7                      docker-ce-stable
docker-ce.x86_64            3:23.0.5-1.el7                      docker-ce-stable
docker-ce.x86_64            3:23.0.4-1.el7                      docker-ce-stable
docker-ce.x86_64            3:23.0.3-1.el7                      docker-ce-stable
docker-ce.x86_64            3:23.0.2-1.el7                      docker-ce-stable
docker-ce.x86_64            3:23.0.1-1.el7                      docker-ce-stable
docker-ce.x86_64            3:23.0.0-1.el7                      docker-ce-stable
docker-ce.x86_64            3:20.10.9-3.el7                     docker-ce-stable
docker-ce.x86_64            3:20.10.8-3.el7                     docker-ce-stable
docker-ce.x86_64            3:20.10.7-3.el7                     docker-ce-stable
docker-ce.x86_64            3:20.10.6-3.el7                     docker-ce-stable
docker-ce.x86_64            3:20.10.5-3.el7                     docker-ce-stable
docker-ce.x86_64            3:20.10.4-3.el7                     docker-ce-stable
docker-ce.x86_64            3:20.10.3-3.el7                     docker-ce-stable
docker-ce.x86_64            3:20.10.24-3.el7                    docker-ce-stable
docker-ce.x86_64            3:20.10.2-3.el7                     docker-ce-stable
docker-ce.x86_64            3:20.10.23-3.el7                    docker-ce-stable
docker-ce.x86_64            3:20.10.22-3.el7                    docker-ce-stable
docker-ce.x86_64            3:20.10.21-3.el7                    docker-ce-stable
docker-ce.x86_64            3:20.10.20-3.el7                    docker-ce-stable
docker-ce.x86_64            3:20.10.19-3.el7                    docker-ce-stable
docker-ce.x86_64            3:20.10.18-3.el7                    docker-ce-stable
docker-ce.x86_64            3:20.10.17-3.el7                    docker-ce-stable
docker-ce.x86_64            3:20.10.16-3.el7                    docker-ce-stable
docker-ce.x86_64            3:20.10.15-3.el7                    docker-ce-stable
docker-ce.x86_64            3:20.10.14-3.el7                    docker-ce-stable
docker-ce.x86_64            3:20.10.1-3.el7                     docker-ce-stable
docker-ce.x86_64            3:20.10.13-3.el7                    docker-ce-stable
docker-ce.x86_64            3:20.10.12-3.el7                    docker-ce-stable
docker-ce.x86_64            3:20.10.11-3.el7                    docker-ce-stable
docker-ce.x86_64            3:20.10.10-3.el7                    docker-ce-stable
docker-ce.x86_64            3:20.10.0-3.el7                     docker-ce-stable
docker-ce.x86_64            3:19.03.9-3.el7                     docker-ce-stable
docker-ce.x86_64            3:19.03.8-3.el7                     docker-ce-stable
docker-ce.x86_64            3:19.03.7-3.el7                     docker-ce-stable
docker-ce.x86_64            3:19.03.6-3.el7                     docker-ce-stable
docker-ce.x86_64            3:19.03.5-3.el7                     docker-ce-stable
docker-ce.x86_64            3:19.03.4-3.el7                     docker-ce-stable
docker-ce.x86_64            3:19.03.3-3.el7                     docker-ce-stable
docker-ce.x86_64            3:19.03.2-3.el7                     docker-ce-stable
docker-ce.x86_64            3:19.03.15-3.el7                    docker-ce-stable
docker-ce.x86_64            3:19.03.14-3.el7                    docker-ce-stable
docker-ce.x86_64            3:19.03.1-3.el7                     docker-ce-stable
docker-ce.x86_64            3:19.03.13-3.el7                    docker-ce-stable
docker-ce.x86_64            3:19.03.12-3.el7                    docker-ce-stable
docker-ce.x86_64            3:19.03.11-3.el7                    docker-ce-stable
docker-ce.x86_64            3:19.03.10-3.el7                    docker-ce-stable
docker-ce.x86_64            3:19.03.0-3.el7                     docker-ce-stable
docker-ce.x86_64            3:18.09.9-3.el7                     docker-ce-stable
docker-ce.x86_64            3:18.09.8-3.el7                     docker-ce-stable
docker-ce.x86_64            3:18.09.7-3.el7                     docker-ce-stable
docker-ce.x86_64            3:18.09.6-3.el7                     docker-ce-stable
docker-ce.x86_64            3:18.09.5-3.el7                     docker-ce-stable
docker-ce.x86_64            3:18.09.4-3.el7                     docker-ce-stable
docker-ce.x86_64            3:18.09.3-3.el7                     docker-ce-stable
docker-ce.x86_64            3:18.09.2-3.el7                     docker-ce-stable
docker-ce.x86_64            3:18.09.1-3.el7                     docker-ce-stable
docker-ce.x86_64            3:18.09.0-3.el7                     docker-ce-stable
docker-ce.x86_64            18.06.3.ce-3.el7                    docker-ce-stable
docker-ce.x86_64            18.06.2.ce-3.el7                    docker-ce-stable
docker-ce.x86_64            18.06.1.ce-3.el7                    docker-ce-stable
docker-ce.x86_64            18.06.0.ce-3.el7                    docker-ce-stable
docker-ce.x86_64            18.03.1.ce-1.el7.centos             docker-ce-stable
docker-ce.x86_64            18.03.0.ce-1.el7.centos             docker-ce-stable
docker-ce.x86_64            17.12.1.ce-1.el7.centos             docker-ce-stable
docker-ce.x86_64            17.12.0.ce-1.el7.centos             docker-ce-stable
docker-ce.x86_64            17.09.1.ce-1.el7.centos             docker-ce-stable
docker-ce.x86_64            17.09.0.ce-1.el7.centos             docker-ce-stable
docker-ce.x86_64            17.06.2.ce-1.el7.centos             docker-ce-stable
docker-ce.x86_64            17.06.1.ce-1.el7.centos             docker-ce-stable
docker-ce.x86_64            17.06.0.ce-1.el7.centos             docker-ce-stable
docker-ce.x86_64            17.03.3.ce-1.el7                    docker-ce-stable
docker-ce.x86_64            17.03.2.ce-1.el7.centos             docker-ce-stable
docker-ce.x86_64            17.03.1.ce-1.el7.centos             docker-ce-stable
docker-ce.x86_64            17.03.0.ce-1.el7.centos             docker-ce-stable
 * base: mirrors.bfsu.edu.cn


//选择其中一个版本安装,最好不要选择最新的,尽量选中间的一个(因为本人就试过选最上面的安装失败了)

选中间的,比如

docker-ce.x86_64 3:20.10.9-3.el7 docker-ce-stable

这个版本,去掉 “3:” 和 “-3.el7” 只保留 “20.10.9”,“20.10.9” 才是你需要安装的版本号

[root@localhost ~]# yum install docker-ce-20.10.9 docker-ce-cli-20.10.9 containerd.io docker-compose-plugin
已加载插件:fastestmirror, product-id, search-disabled-repos, subscription-manager

This system is not registered with an entitlement server. You can use subscription-manager to register.

Loading mirror speeds from cached hostfile
 * base: mirrors.bfsu.edu.cn
 * epel: ftp.riken.jp
 * extras: mirrors.bfsu.edu.cn
 * updates: mirrors.qlu.edu.cn
软件包 containerd.io-1.6.21-3.1.el7.x86_64 已安装并且是最新版本
正在解决依赖关系
--> 正在检查事务
---> 软件包 docker-ce.x86_64.3.20.10.9-3.el7 将被 安装
--> 正在处理依赖关系 docker-ce-rootless-extras,它被软件包 3:docker-ce-20.10.9-3.el7.x86_64 需要
---> 软件包 docker-ce-cli.x86_64.1.20.10.9-3.el7 将被 安装
--> 正在处理依赖关系 docker-scan-plugin(x86-64),它被软件包 1:docker-ce-cli-20.10.9-3.el7.x86_64 需要
---> 软件包 docker-compose-plugin.x86_64.0.2.18.1-1.el7 将被 安装
--> 正在检查事务
---> 软件包 docker-ce-rootless-extras.x86_64.0.24.0.2-1.el7 将被 安装
---> 软件包 docker-scan-plugin.x86_64.0.0.23.0-3.el7 将被 安装
--> 解决依赖关系完成

依赖关系解决

=================================================================================================================================================================================================================
 Package                                                     架构                                     版本                                              源                                                  大小
=================================================================================================================================================================================================================
正在安装:
 docker-ce                                                   x86_64                                   3:20.10.9-3.el7                                   docker-ce-stable                                    23 M
 docker-ce-cli                                               x86_64                                   1:20.10.9-3.el7                                   docker-ce-stable                                    29 M
 docker-compose-plugin                                       x86_64                                   2.18.1-1.el7                                      docker-ce-stable                                    12 M
为依赖而安装:
 docker-ce-rootless-extras                                   x86_64                                   24.0.2-1.el7                                      docker-ce-stable                                   9.1 M
 docker-scan-plugin                                          x86_64                                   0.23.0-3.el7                                      docker-ce-stable                                   3.8 M

事务概要
=================================================================================================================================================================================================================
安装  3 软件包 (+2 依赖软件包)

总下载量:77 M
安装大小:319 M
Is this ok [y/d/N]: y
Downloading packages:
(1/5): docker-ce-20.10.9-3.el7.x86_64.rpm                                                                                                                                                 |  23 MB  00:00:41     
(2/5): docker-ce-rootless-extras-24.0.2-1.el7.x86_64.rpm                                                                                                                                  | 9.1 MB  00:00:16     
(3/5): docker-ce-cli-20.10.9-3.el7.x86_64.rpm                                                                                                                                             |  29 MB  00:01:03     
(4/5): docker-scan-plugin-0.23.0-3.el7.x86_64.rpm                                                                                                                                         | 3.8 MB  00:00:07     
(5/5): docker-compose-plugin-2.18.1-1.el7.x86_64.rpm                                                                                                                                      |  12 MB  00:00:20     
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
总计                                                                                                                                                                             1.0 MB/s |  77 MB  00:01:18     
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  正在安装    : docker-scan-plugin-0.23.0-3.el7.x86_64                                                                                                                                                       1/5 
  正在安装    : 1:docker-ce-cli-20.10.9-3.el7.x86_64                                                                                                                                                         2/5 
  正在安装    : docker-ce-rootless-extras-24.0.2-1.el7.x86_64                                                                                                                                                3/5 
  正在安装    : 3:docker-ce-20.10.9-3.el7.x86_64                                                                                                                                                             4/5 
  正在安装    : docker-compose-plugin-2.18.1-1.el7.x86_64                                                                                                                                                    5/5 
  验证中      : docker-scan-plugin-0.23.0-3.el7.x86_64                                                                                                                                                       1/5 
  验证中      : docker-compose-plugin-2.18.1-1.el7.x86_64                                                                                                                                                    2/5 
  验证中      : 1:docker-ce-cli-20.10.9-3.el7.x86_64                                                                                                                                                         3/5 
  验证中      : docker-ce-rootless-extras-24.0.2-1.el7.x86_64                                                                                                                                                4/5 
  验证中      : 3:docker-ce-20.10.9-3.el7.x86_64                                                                                                                                                             5/5 

已安装:
  docker-ce.x86_64 3:20.10.9-3.el7                                docker-ce-cli.x86_64 1:20.10.9-3.el7                                docker-compose-plugin.x86_64 0:2.18.1-1.el7                               

作为依赖被安装:
  docker-ce-rootless-extras.x86_64 0:24.0.2-1.el7                                                            docker-scan-plugin.x86_64 0:0.23.0-3.el7                                                           

完毕!

到这里就已经安装完了,

7、我们也可以使用 docker version 验证一下安装是否成功,(有 client 和 Server 两部分表示docker安装启动都成功了,安装失败可能 Server 端信息无法显示出来)

[root@localhost ~]# docker version
Client: Docker Engine - Community
 Version:           20.10.9
 API version:       1.41
 Go version:        go1.16.8
 Git commit:        c2ea9bc
 Built:             Mon Oct  4 16:08:14 2021
 OS/Arch:           linux/amd64
 Context:           default
 Experimental:      true

Server: Docker Engine - Community
 Engine:
  Version:          20.10.9
  API version:      1.41 (minimum version 1.12)
  Go version:       go1.16.8
  Git commit:       79ea9d3
  Built:            Mon Oct  4 16:06:37 2021
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          1.6.21
  GitCommit:        3dce8eb055cbb6872793272b4f20ed16117344f8
 runc:
  Version:          1.1.7
  GitCommit:        v1.1.7-0-g860f061
 docker-init:
  Version:          0.19.0
  GitCommit:        de40ad0


8、启动并加入开机启动

[root@localhost ~]# systemctl start docker
##加入开机启动
[root@localhost ~]# systemctl enable docker
Created symlink from /etc/systemd/system/multi-user.target.wants/docker.service to /usr/lib/systemd/system/docker.service.

##查看docker运行状态
[root@localhost ~]# systemctl status docker
● docker.service - Docker Application Container Engine
   Loaded: loaded (/usr/lib/systemd/system/docker.service; disabled; vendor preset: disabled)
   Active: active (running) since 六 2023-05-27 15:39:50 CST; 21s ago
     Docs: https://docs.docker.com
 Main PID: 2035 (dockerd)
    Tasks: 10
   Memory: 48.2M
   CGroup: /system.slice/docker.service
           └─2035 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock

527 15:39:49 localhost.localdomain dockerd[2035]: time="2023-05-27T15:39:49.389110857+08:00" level=warning msg="overlay2: the backing xfs filesystem is formatted without d_type support, which leads to i...
5月 27 15:39:49 localhost.localdomain dockerd[2035]: time="2023-05-27T15:39:49.389573093+08:00" level=info msg="[graphdriver] using prior storage driver: overlay2"
5月 27 15:39:49 localhost.localdomain dockerd[2035]: time="2023-05-27T15:39:49.399855207+08:00" level=info msg="Loading containers: start."
5月 27 15:39:50 localhost.localdomain dockerd[2035]: time="2023-05-27T15:39:50.009947706+08:00" level=info msg="Default bridge (docker0) is assigned with an IP address 172.17.0.0/16. Daemon op...d IP address"
5月 27 15:39:50 localhost.localdomain dockerd[2035]: time="2023-05-27T15:39:50.138727426+08:00" level=info msg="Firewalld: interface docker0 already part of docker zone, returning"
5月 27 15:39:50 localhost.localdomain dockerd[2035]: time="2023-05-27T15:39:50.248952788+08:00" level=info msg="Loading containers: done."
5月 27 15:39:50 localhost.localdomain dockerd[2035]: time="2023-05-27T15:39:50.278044741+08:00" level=info msg="Docker daemon" commit=79ea9d3 graphdriver(s)=overlay2 version=20.10.9
5月 27 15:39:50 localhost.localdomain dockerd[2035]: time="2023-05-27T15:39:50.278207185+08:00" level=info msg="Daemon has completed initialization"
5月 27 15:39:50 localhost.localdomain systemd[1]: Started Docker Application Container Engine.
5月 27 15:39:50 localhost.localdomain dockerd[2035]: time="2023-05-27T15:39:50.300377563+08:00" level=info msg="API listen on /var/run/docker.sock"
Hint: Some lines were ellipsized, use -l to show in full.


注意:一般需要配置docker镜像加速器

我们可以借助阿里云的镜像加速器,登录阿里云(cr.console.aliyun.com/#/accelerat…)

可以看到镜像加速地址如下图(每个用户的镜像地址应该是不一样的):

Docker 详解与微服务部署实战

[root@localhost ~]#  cd /etc/docker
[root@localhost docker]# ls
daemon.json  key.json
[root@localhost docker]# 

查看有没有 daemon.json。这是docker默认的配置文件。

如果没有新建,如果有,则修改。

sudo tee /etc/docker/daemon.json <<-'EOF'
{
  "registry-mirrors": ["https://14saylz9.mirror.aliyuncs.com"]
}
EOF

重启docker服务

sudo systemctl daemon-reload
sudo systemctl restart docker

成功!

Docker常用命令

镜像相关命令

1、搜索镜像

可使用 docker search 命令搜索存放在 Docker Hub 中的镜像。执行该命令后, Docker 就会在 Docker Hub 中搜索含有 java 这个关键词的镜像仓库。

[root@localhost ~]# docker search java
NAME                               DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
node                               Node.js is a JavaScript-based platform for s…   12642     [OK]       
tomcat                             Apache Tomcat is an open source implementati…   3544      [OK]       
java                               DEPRECATED; use "openjdk" (or other JDK impl…   1987      [OK]       
ghost                              Ghost is a free and open source blogging pla…   1631      [OK]       
couchdb                            CouchDB is a database that uses JSON for doc…   520       [OK]       
jetty                              Jetty provides a Web server and javax.servle…   399       [OK]       
amazoncorretto                     Corretto is a no-cost, production-ready dist…   304       [OK]       
groovy                             Apache Groovy is a multi-faceted language fo…   140       [OK]       
ibmjava                            Official IBM® SDK, Java™ Technology Edition …   115       [OK]       
tomee                              Apache TomEE is an all-Apache Java EE certif…   108       [OK]       
bitnami/java                       Bitnami Java Docker Image                       17                   [OK]
javanile/vtiger                    Vtiger CRM is open source software that help…   14                   [OK]
appdynamics/java-agent             Java Agent for Kubernetes                       10                   
javanile/novnc                     Ready to use NoVNC client for SeleniumHQ on …   2                    [OK]
circleci/java                      This image is for internal use                  2                    
kasmweb/java-dev                   Ubuntu Java development desktop for Kasm Wor…   1                    
javanile/adminer                   Build adminer                                   1                    [OK]
circleci/java-nginx                Java+nginx image. This image is for internal…   1                    
airbyte/java-datadog-tracer-base   Docker image that provides the DataDog Java …   0                    
javanile/vtiger-dev                Ready for development vtiger docker image       0                    
javanile/bash-ci                                                                   0                    
javanile/xdebug                                                                    0                    
javanile/make.bat                                                                  0                    
javanile/pwd                                                                       0                    
javanile/mysql                     MySQL for development                           0                    
[root@localhost ~]# 

以上列表包含五列,含义如下:

  • NAME:镜像仓库名称。

  • DESCRIPTION:镜像仓库描述。

  • STARS:镜像仓库收藏数,表示该镜像仓库的受欢迎程度,类似于 GitHub的 stars0

  • OFFICAL:表示是否为官方仓库,该列标记为[0K]的镜像均由各软件的官方项目组创建和维护。

  • AUTOMATED:表示是否是自动构建的镜像仓库。

2、下载镜像

使用命令docker pull命令即可从 Docker Registry上下载镜像,执行该命令后,Docker会从 Docker Hub中的 java 仓库下载最

新版本的 Java镜像。如果要下载指定版本则在java后面加冒号指定版本,例如:docker pull java:8

[root@localhost ~]# docker pull java:8
8: Pulling from library/java
5040bd298390: Pull complete 
fce5728aad85: Pull complete 
76610ec20bf5: Pull complete 
60170fec2151: Pull complete 
e98f73de8f0d: Pull complete 
11f7af24ed9c: Pull complete 
49e2d6393f32: Pull complete 
bb9cdec9c7f3: Pull complete 
Digest: sha256:c1ff613e8ba25833d2e1940da0940c3824f03f802c449f3d1815a66b7f8c0e9d
Status: Downloaded newer image for java:8
docker.io/library/java:8
[root@localhost ~]# docker images
REPOSITORY   TAG       IMAGE ID       CREATED       SIZE
java         8         d23bdf5b1b1b   6 years ago   643MB
[root@localhost ~]# docker pull nginx
Using default tag: latest
latest: Pulling from library/nginx
a2abf6c4d29d: Downloading [================>                                  ]  10.35MB/31.36MB
a9edb18cadd1: Download complete 
a2abf6c4d29d: Pull complete 
a9edb18cadd1: Pull complete 
589b7251471a: Pull complete 
186b1aaa4aa6: Pull complete 
b4df32aa5a72: Pull complete 
a0bcbecc962e: Pull complete 
Digest: sha256:0d17b565c37bcbd895e9d92315a05c1c3c9a29f762b011a10c54a66cd53c9b31
Status: Downloaded newer image for nginx:latest
docker.io/library/nginx:latest
[root@localhost ~]# 

注意:下载镜像需要登录阿里云

3、列出镜像

使用 docker images命令即可列出已下载的镜像

[root@localhost ~]# docker images
REPOSITORY   TAG       IMAGE ID       CREATED         SIZE
nginx        latest    605c77e624dd   17 months ago   141MB
java         8         d23bdf5b1b1b   6 years ago     643MB

以上列表含义如下

  • REPOSITORY:镜像所属仓库名称。

  • TAG:镜像标签。默认是 latest,表示最新。

  • IMAGE ID:镜像 ID,表示镜像唯一标识。

  • CREATED:镜像创建时间。

  • SIZE: 镜像大小。

4、删除本地镜像

使用 docker rmi命令即可删除指定镜像,强制删除加 -f

docker rmi java

删除所有镜像

docker rmi $(docker images ‐q)

容器相关命令

1、新建并启动容器

使用以下docker run命令即可新建并启动一个容器,该命令是最常用的命令,它有很多选项,下面将列举一些常用的选项。

-d选项:表示后台运行

-P选项:随机端口映射

-p选项:指定端口映射,有以下四种格式。

-- ip:hostPort:containerPort

-- ip::containerPort

-- hostPort:containerPort

-- containerPort

--net选项:指定网络模式,该选项有以下可选参数:

--net=bridge:默认选项,表示连接到默认的网桥。

--net=host:容器使用宿主机的网络。

--net=container:NAME-or-ID:告诉 Docker让新建的容器使用已有容器的网络配置。

--net=none:不配置该容器的网络,用户可自定义网络配置。

[root@localhost ~]# docker run -d -p 91:80 nginx
b5f920b5067e0842e894f43a9a42e8627cf71e84aa8182a36d89d28ea63681c1

这样就成功启动了一个 Nginx 容器。在本例中,为 docker run 添加了两个参数,含义如下:

-d 后台运行

-p 宿主机端口:容器端口 #开放容器端口到宿主机端口

访问 Docker 宿主机 IP:91/,将会看到 nginx 的主界面如下:

Docker 详解与微服务部署实战

需要注意的是,使用 docker run 命令创建容器时,会先检查本地是否存在指定镜像。如果本地不存在该名称的镜像, Docker 就

会自动从 Docker Hub下载镜像并启动一个 Docker 容器。

也可以在虚拟机主机中访问80端口:

[root@localhost ~]# curl 172.17.0.2:80
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

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

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

2、列出容器

用 docker ps 命令即可列出运行中的容器

[root@localhost ~]# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS          PORTS                               NAMES
b5f920b5067e   nginx     "/docker-entrypoint.…"   15 seconds ago   Up 14 seconds   0.0.0.0:91->80/tcp, :::91->80/tcp   competent_lumiere

如需列出所有容器(包括已停止的容器),可使用-a参数。该列表包含了7列,含义如下

  • CONTAINER_ID:表示容器 ID。

  • IMAGE:表示镜像名称。

  • COMMAND:表示启动容器时运行的命令。

  • CREATED:表示容器的创建时间。

  • STATUS:表示容器运行的状态。UP表示运行中, Exited表示已停止。

  • PORTS:表示容器对外的端口号。

  • NAMES:表示容器名称。该名称默认由 Docker自动生成,也可使用 docker run命令的--name选项自行指定。

3、停止容器

使用 docker stop 命令,即可停止容器

[root@localhost ~]# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED       STATUS       PORTS                               NAMES
b5f920b5067e   nginx     "/docker-entrypoint.…"   3 hours ago   Up 3 hours   0.0.0.0:91->80/tcp, :::91->80/tcp   competent_lumiere
[root@localhost ~]# docker stop b5f920b5067e
b5f920b5067e
[root@localhost ~]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@localhost ~]# 

用 docker ps 命令查看,此时已经没有正在运行的 docker 容器了。

4、强制停止容器

可使用 docker kill命令发送 SIGKILL 信号来强制停止容器,命令:

docker kill 容器id

5、启动已停止的容器

使用docker run命令,即可新建并启动一个容器。对于已停止的容器,可使用 docker start 命令来启动

docker start 容器id

[root@localhost ~]# docker start b5f920b5067e
b5f920b5067e
[root@localhost ~]# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED       STATUS         PORTS                               NAMES
b5f920b5067e   nginx     "/docker-entrypoint.…"   3 hours ago   Up 4 seconds   0.0.0.0:91->80/tcp, :::91->80/tcp   competent_lumiere
[root@localhost ~]# 

6、查看容器所有信息
[root@localhost ~]# docker inspect b5f920b5067e
[
    {
        "Id": "b5f920b5067e0842e894f43a9a42e8627cf71e84aa8182a36d89d28ea63681c1",//容器完整id
        "Created": "2023-05-27T11:16:42.1740757Z",
        "Path": "/docker-entrypoint.sh",
        "Args": [
            "nginx",
            "-g",
            "daemon off;"
        ],
        "State": {
            "Status": "running",//运行状态
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 2182,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2023-05-27T11:16:42.738685746Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:605c77e624ddb75e6110f997c58876baa13f8754486b461117934b24a9dc3a85",
        "ResolvConfPath": "/var/lib/docker/containers/b5f920b5067e0842e894f43a9a42e8627cf71e84aa8182a36d89d28ea63681c1/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/b5f920b5067e0842e894f43a9a42e8627cf71e84aa8182a36d89d28ea63681c1/hostname",
        "HostsPath": "/var/lib/docker/containers/b5f920b5067e0842e894f43a9a42e8627cf71e84aa8182a36d89d28ea63681c1/hosts",
        "LogPath": "/var/lib/docker/containers/b5f920b5067e0842e894f43a9a42e8627cf71e84aa8182a36d89d28ea63681c1/b5f920b5067e0842e894f43a9a42e8627cf71e84aa8182a36d89d28ea63681c1-json.log",
        "Name": "/competent_lumiere",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "",
        "ExecIDs": null,
        "HostConfig": {
            "Binds": null,
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "default",
            "PortBindings": {
                "80/tcp": [
                    {
                        "HostIp": "",
                        "HostPort": "91"
                    }
                ]
            },
            "RestartPolicy": {
                "Name": "no",
                "MaximumRetryCount": 0
            },
            "AutoRemove": false,
            "VolumeDriver": "",
            "VolumesFrom": null,
            "CapAdd": null,
            "CapDrop": null,
            "CgroupnsMode": "host",
            "Dns": [],
            "DnsOptions": [],
            "DnsSearch": [],
            "ExtraHosts": null,
            "GroupAdd": null,
            "IpcMode": "private",
            "Cgroup": "",
            "Links": null,
            "OomScoreAdj": 0,
            "PidMode": "",
            "Privileged": false,
            "PublishAllPorts": false,
            "ReadonlyRootfs": false,
            "SecurityOpt": null,
            "UTSMode": "",
            "UsernsMode": "",
            "ShmSize": 67108864,
            "Runtime": "runc",
            "ConsoleSize": [
                0,
                0
            ],
            "Isolation": "",
            "CpuShares": 0,
            "Memory": 0,
            "NanoCpus": 0,
            "CgroupParent": "",
            "BlkioWeight": 0,
            "BlkioWeightDevice": [],
            "BlkioDeviceReadBps": null,
            "BlkioDeviceWriteBps": null,
            "BlkioDeviceReadIOps": null,
            "BlkioDeviceWriteIOps": null,
            "CpuPeriod": 0,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": [],
            "DeviceCgroupRules": null,
            "DeviceRequests": null,
            "KernelMemory": 0,
            "KernelMemoryTCP": 0,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": null,
            "OomKillDisable": false,
            "PidsLimit": null,
            "Ulimits": null,
            "CpuCount": 0,
            "CpuPercent": 0,
            "IOMaximumIOps": 0,
            "IOMaximumBandwidth": 0,
            "MaskedPaths": [
                "/proc/asound",
                "/proc/acpi",
                "/proc/kcore",
                "/proc/keys",
                "/proc/latency_stats",
                "/proc/timer_list",
                "/proc/timer_stats",
                "/proc/sched_debug",
                "/proc/scsi",
                "/sys/firmware"
            ],
            "ReadonlyPaths": [
                "/proc/bus",
                "/proc/fs",
                "/proc/irq",
                "/proc/sys",
                "/proc/sysrq-trigger"
            ]
        },
        "GraphDriver": {
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/0e0fb66e4135af183181cfb99be57eda8b52e7e814a70c31b0a98541fbb6deef-init/diff:/var/lib/docker/overlay2/71a73da43f7a3c616e21c8bcf1db18cb6ad169aa0e436eeed9a2a8617088266b/diff:/var/lib/docker/overlay2/d72fe02bb0af515c7e7d2d5ee149b0412afa9edd45399d0c61ebb6cf180e87aa/diff:/var/lib/docker/overlay2/84e0bfcdf61f43a8e7fe2ee1b0ced52ccd1b41cafd479664b092a8cd4efdda6e/diff:/var/lib/docker/overlay2/b7a4d8567c0634bc5f1a87c53dcfd0cac99be7c3bcf2f8bb457e729cbac11946/diff:/var/lib/docker/overlay2/2ce6537694e0d3fd59162836ca3e4d134ea46c05b5054485edd7bb08c6cfe2c8/diff:/var/lib/docker/overlay2/063bf59268a317a09f2629a97ac53b5cee59687c26016e0775c394f5cebe57a1/diff",
                "MergedDir": "/var/lib/docker/overlay2/0e0fb66e4135af183181cfb99be57eda8b52e7e814a70c31b0a98541fbb6deef/merged",
                "UpperDir": "/var/lib/docker/overlay2/0e0fb66e4135af183181cfb99be57eda8b52e7e814a70c31b0a98541fbb6deef/diff",
                "WorkDir": "/var/lib/docker/overlay2/0e0fb66e4135af183181cfb99be57eda8b52e7e814a70c31b0a98541fbb6deef/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "b5f920b5067e",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "ExposedPorts": {
                "80/tcp": {}
            },
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "NGINX_VERSION=1.21.5",
                "NJS_VERSION=0.7.1",
                "PKG_RELEASE=1~bullseye"
            ],
            "Cmd": [
                "nginx",
                "-g",
                "daemon off;"
            ],
            "Image": "nginx",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": [
                "/docker-entrypoint.sh"
            ],
            "OnBuild": null,
            "Labels": {
                "maintainer": "NGINX Docker Maintainers <docker-maint@nginx.com>"
            },
            "StopSignal": "SIGQUIT"
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "5f7b486975ff55c508f9dd2062d8eaf37931640442c45181c2e9dc6c6ab64f49",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {
                "80/tcp": [
                    {
                        "HostIp": "0.0.0.0",
                        "HostPort": "91"
                    },
                    {
                        "HostIp": "::",
                        "HostPort": "91"
                    }
                ]
            },
            "SandboxKey": "/var/run/docker/netns/5f7b486975ff",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "fbffd281fd17eb6565de7e80c18ffccf5e9ca4be84397d198ad0059dafb4a049",
            "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": "113de181de4ecde14acd3aca334f2a0f74d5a72c039387c6814b7c4ed56ffdcf",
                    "EndpointID": "fbffd281fd17eb6565de7e80c18ffccf5e9ca4be84397d198ad0059dafb4a049",
                    "Gateway": "172.17.0.1",//主机ip
                    "IPAddress": "172.17.0.2",//分配容器的ip
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:11:00:02",
                    "DriverOpts": null
                }
            }
        }
    }
]


7、查看容器日志
[root@localhost ~]# docker container logs b5f920b5067e
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf
10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
/docker-entrypoint.sh: Configuration complete; ready for start up
2023/05/27 11:16:42 [notice] 1#1: using the "epoll" event method
2023/05/27 11:16:42 [notice] 1#1: nginx/1.21.5
2023/05/27 11:16:42 [notice] 1#1: built by gcc 10.2.1 20210110 (Debian 10.2.1-6) 
2023/05/27 11:16:42 [notice] 1#1: OS: Linux 3.10.0-1160.90.1.el7.x86_64
2023/05/27 11:16:42 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
2023/05/27 11:16:42 [notice] 1#1: start worker processes
2023/05/27 11:16:42 [notice] 1#1: start worker process 31
2023/05/27 11:16:42 [notice] 1#1: start worker process 32
2023/05/27 11:16:42 [notice] 1#1: start worker process 33
2023/05/27 11:16:42 [notice] 1#1: start worker process 34
8、查看容器里的进程
[root@localhost ~]# docker top b5f920b5067e
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                2182                2161                0                   19:16               ?                   00:00:00            nginx: master process nginx -g daemon off;
101                 2234                2182                0                   19:16               ?                   00:00:00            nginx: worker process
101                 2235                2182                0                   19:16               ?                   00:00:00            nginx: worker process
101                 2236                2182                0                   19:16               ?                   00:00:00            nginx: worker process
101                 2237                2182                0                   19:16               ?                   00:00:00            nginx: worker process

9、容器与宿主机相互复制文件
  • 从容器里面拷文件到宿主机:

docker cp 容器id:要拷贝的文件在容器里面的路径 宿主机的相应路径

如:docker cp 7aa5dc458f9d:/etc/nginx/nginx.conf /mydata/nginx

  • 从宿主机拷文件到容器里面:

docker cp 要拷贝的宿主机文件路径 容器id:要拷贝到容器里面对应的路径

10、进入容器

使用docker exec命令用于进入一个正在运行的docker容器。如果docker run命令运行容器的时候,没有使用-it参数,就要用这

个命令进入容器。一旦进入了容器,就可以在容器的 Shell 执行命令了

docker exec ‐it 容器id /bin/bash (有的容器需要把 /bin/bash 换成 sh)

[root@localhost ~]# docker exec -it b5f920b5067e /bin/bash
root@b5f920b5067e:/# ls
bin  boot  dev  docker-entrypoint.d  docker-entrypoint.sh  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
//进入到容器中,此时所在的坐标从localhost变成了b5f920b5067e(容器id)
root@b5f920b5067e:/# exit
exit
//exit退出容器,回到宿主机
[root@localhost ~]# 
[root@localhost ~]# CLASSPATH=.:$JAVA_HOME/jre/lib/ext:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
11、容器内安装vim、ping、ifconfig等指令

1 apt‐get update

2 apt‐get install vim #安装vim

3 apt‐get install iputils‐ping #安装ping

4 apt‐get install net‐tools #安装ifconfig

12、删除容器

使用 docker rm命令即可删除指定容器

docker rm f0b1c8ab3633

该命令只能删除已停止的容器,如需删除正在运行的容器,可使用-f参数

强制删除所有容器

docker rm ‐f $(docker ps ‐a ‐q)

将微服务运行在docker上

使用Dockerfile构建Docker镜像

Dockerfile是一个文本文件,其中包含了若干条指令,指令描述了构建镜像的细节

先来编写一个最简单的Dockerfile,以前文下载的Nginx镜像为例,来编写一个Dockerfile修改该Nginx镜像的首页

1、新建 Dockerfile

新建一个空文件夹docker-demo,在里面再新建文件夹app,在app目录下新建一个名为Dockerfile的文件,在里面增加如下内容:

FROM nginx
RUN echo '<h1>Hello, Docker Nginx!!!</h1>' > /usr/share/nginx/html/index.html

[root@localhost ~]# cd /usr/local
[root@localhost local]# ls
bin  etc  games  include  lib  lib64  libexec  redis-5.0.3  redis-5.0.3.tar.gz  sbin  share  src
[root@localhost local]# mkdir docker-app
[root@localhost local]# cd docker-app/
[root@localhost docker-app]# ls
[root@localhost docker-app]# mkdir docker-demo
[root@localhost docker-app]# ls
docker-demo
[root@localhost docker-app]# cd docker-demo
[root@localhost docker-demo]# ls
[root@localhost docker-demo]# touch Dockerfile
[root@localhost docker-demo]# ls
Dockerfile
[root@localhost docker-demo]# vi Dockerfile


From nginx
RUN echo '<h1>Hello, Docker Nginx!!!</h1>' > /usr/share/nginx/html/index.html
~                                                                                                                                                                                                                
~                                                                                                                                                                                                                
~                                                                                                                                                                                                                
~                                                                                                                                                                                                                
~                                                                                                                                                                                                                
~                                                                                                                                                                                                                
~                                                                                                                                                                                                                
~                                                                                                                                                                                                                
~                                                                                                                                                                                                                
~                                                                                                                                                                                                                
~                                                                                                                                                                                                                
~                                                                                                                                                                                                                
~                                                                                                                                                                                                                
~                                                                                                                                                                                                                
~                                                                                                                                                                                                                
~                                                                                                                                                                                                                
~                                                                                                                                                                                                                
~                                                                                                                                                                                                                
~                                                                                                                                                                                                                
~                                                                                                                                                                                                                
~                                                                                                                                                                                                                
~                                                                                                                                                                                                                
~                                                                                                                                                                                                                
~                                                                                                                                                                                                                
~                                                                                                                                                                                                                
~                                                                                                                                                                                                                
~                                                                                                                                                                                                                
~                                                                                                                                                                                                                
~                                                                                                                                                                                                                
~                                                                                                                                                                                                                
~                                                                                                                                                                                                                
~                                                                                                                                                                                                                
~                                                                                                                                                                                                                
~                                                                                                                                                                                                                
~                                                                                                                                                                                                                
~                                                                                                                                                                                                                
:wq

该 Dockerfile 非常简单,其中的 FROM、 RUN 都是 Dockerfile 的指令。 FROM 指令用于指定基础镜像, RUN 指令用于执行命令。

[root@localhost ~]# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED       STATUS          PORTS                               NAMES
b5f920b5067e   nginx     "/docker-entrypoint.…"   4 hours ago   Up 41 minutes   0.0.0.0:91->80/tcp, :::91->80/tcp   competent_lumiere
[root@localhost ~]# docker exec -it b5f920b5067e /bin/bash
root@b5f920b5067e:/# cd /usr/share/nginx/html/
root@b5f920b5067e:/usr/share/nginx/html# ls
50x.html  index.html
root@b5f920b5067e:/usr/share/nginx/html# 
root@b5f920b5067e:/usr/share/nginx/html# cat index.html
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

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

<p><em>Thank you for using nginx.</em></p>
</body>
</html>
root@b5f920b5067e:/usr/share/nginx/html# 

2、在 Dockerfile 所在路径执行以下命令构建镜像:

docker build ‐t nginx:docker2023 .

其中,-t指定镜像名字,命令最后的点(.)表示 Dockerfile 文件所在路径

[root@localhost docker-demo]# docker build -t nginx:docker2023 .
Sending build context to Docker daemon  2.048kB
Step 1/2 : From nginx
 ---> 605c77e624dd
Step 2/2 : RUN echo '<h1>Hello, Docker Nginx!!!</h1>' > /usr/share/nginx/html/index.html
 ---> Running in 4e7558d53899
Removing intermediate container 4e7558d53899
 ---> 1ea2c9461931
Successfully built 1ea2c9461931
Successfully tagged nginx:docker2023
//构建成功,查看docker所有镜像
[root@localhost docker-demo]# docker images
REPOSITORY   TAG          IMAGE ID       CREATED          SIZE
nginx        docker2023   1ea2c9461931   30 seconds ago   141MB
nginx        latest       605c77e624dd   17 months ago    141MB
java         8            d23bdf5b1b1b   6 years ago      643MB

3、执行以下命令,即可使用该镜像启动一个 Docker 容器

docker run ‐d ‐p 93:80 nginx:docker2023

[root@localhost docker-demo]# docker run -d -p 93:80 nginx:docker2023
6678d93f4f1ac9e5535444c04c3f76eec4b215f8e3c4db3616d4585bfe642f7c
[root@localhost docker-demo]# docker ps
CONTAINER ID   IMAGE              COMMAND                  CREATED          STATUS          PORTS                               NAMES
6678d93f4f1a   nginx:docker2023   "/docker-entrypoint.…"   About a minute ago   Up About a minute   0.0.0.0:93->80/tcp, :::93->80/tcp   competent_noether
b5f920b5067e   nginx              "/docker-entrypoint.…"   4 hours ago      Up 52 minutes   0.0.0.0:91->80/tcp, :::91->80/tcp   competent_lumiere
[root@localhost docker-demo]# 

4、访问 Docker 宿主机IP:93/,可看到下图所示界面

Docker 详解与微服务部署实战

Dockerfile常用指令

Docker 详解与微服务部署实战

注意:RUN命令在 image 文件的构建阶段执行,执行结果都会打包进入 image 文件;CMD命令则是在容器启动后执行。另外,一个 Dockerfile 可以包含多个RUN命令,但是只能有一个CMD命令。

注意,指定了CMD命令以后,docker container run命令就不能附加命令了(比如前面的/bin/bash),否则它会覆盖CMD命令。

使用Dockerfile构建微服务镜像

以项目ms-eureka-server为例,将该微服务的可运行jar包构建成docker镜像

1、上传jar包到linux服务器

将jar包上传linux服务器/usr/local/docker-app/docker-demo/app/eureka目录(可使用WinSCP软件),在jar包所在目录创建名为Dockerfile的文件

[root@localhost /]# cd /usr/local/docker-app/docker-demo/app/eureka/
[root@localhost eureka]# ls
microservice-eureka-server-0.0.1-SNAPSHOT.jar

jar文件是可以直接运行的,

Docker 详解与微服务部署实战

服务已经启动完毕,端口是8761(这里我已经把上面的服务停了,否则需要换一个端口启动,比如8762),使用Chrome浏览器访问,需关闭防火墙

##查看防火墙状态
[root@localhost eureka]# firewall-cmd --state
not running
##关闭防火墙
[root@localhost ~]# systemctl stop firewalld
##禁止firewall开机启动
[root@localhost ~]# systemctl disable firewalld
Removed symlink /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
Removed symlink /etc/systemd/system/basic.target.wants/firewalld.service.

Docker 详解与微服务部署实战

2、在Dockerfile中添加以下内容
1 # 基于哪个镜像

2 From java:8

3 # 复制文件到容器

4 ADD microservice‐eureka‐server‐0.0.1‐SNAPSHOT.jar /app.jar

5 # 声明需要暴露的端口

6 EXPOSE 8761

7 # 配置容器启动后执行的命令

ENTRYPOINT java ${JAVA_OPTS} ‐jar /app.jar
3、使用docker build命令构建镜像
docker build ‐t microservice‐eureka‐server:0.0.1 .

格式: docker build -t 镜像名称:标签 Dockerfile的相对位置

在这里,使用-t选项指定了镜像的标签。执行该命令后,终端将会输出如下的内容

[root@localhost eureka]# docker build -t microservice-eureka-server-0.0.1 .
Sending build context to Docker daemon  39.93MB
Step 1/4 : From java:8
 ---> d23bdf5b1b1b
Step 2/4 : ADD microservice-eureka-server-0.0.1-SNAPSHOT.jar /app.jar
 ---> c7a1522cb2d9
Step 3/4 : EXPOSE 8761
 ---> Running in ec2e3f08312b
Removing intermediate container ec2e3f08312b
 ---> c0377bf06bed
Step 4/4 : ENTRYPOINT java ${JAVA_OPTS} ‐jar /app.jar
 ---> Running in af286d106df6
Removing intermediate container af286d106df6
 ---> b12cabc7fff3
Successfully built b12cabc7fff3
Successfully tagged microservice-eureka-server-0.0.1:latest

镜像列表可以查看到刚刚构建的 microservice-eureka-server-0.0.1

[root@localhost eureka]# docker images
REPOSITORY                         TAG          IMAGE ID       CREATED              SIZE
microservice-eureka-server-0.0.1   latest       b12cabc7fff3   About a minute ago   683MB
nginx                              docker2023   f24895fe2f58   2 hours ago          141MB
nginx                              latest       605c77e624dd   17 months ago        141MB
java                               8            d23bdf5b1b1b   6 years ago          643MB
[root@localhost eureka]# 

4、启动镜像,加-d可在后台启动

docker run -d -p 8761:8761 microservice-eureka-server-0.0.1

使用 -v 可以挂载一个主机上的目录到容器的目录

docker run ‐d ‐p 8761:8761 ‐v /log:/container‐log microservice‐eureka‐server:0.0.1

[root@localhost eureka]# docker run -d -p 8761:8761 microservice-eureka-server-0.0.1
050924a0fb8a2ddb6397e8030588580f32aebad98db7881cf9b14d2ccef258a6
[root@localhost eureka]# 
[root@localhost eureka]# docker ps
CONTAINER ID   IMAGE              COMMAND                  CREATED       STATUS       PORTS                               NAMES
4058071b4518   nginx:docker2023   "/docker-entrypoint.…"   2 hours ago   Up 2 hours   0.0.0.0:93->80/tcp, :::93->80/tcp   strange_shirley
ff1687bd1901   nginx              "/docker-entrypoint.…"   3 hours ago   Up 3 hours   0.0.0.0:91->80/tcp, :::91->80/tcp   youthful_babbage
[root@localhost eureka]# docker ps -a
CONTAINER ID   IMAGE                              COMMAND                  CREATED          STATUS                      PORTS                               NAMES
050924a0fb8a   microservice-eureka-server-0.0.1   "/bin/sh -c 'java ${…"   33 seconds ago   Exited (1) 30 seconds ago                                       magical_meninsky
4058071b4518   nginx:docker2023                   "/docker-entrypoint.…"   2 hours ago      Up 2 hours                  0.0.0.0:93->80/tcp, :::93->80/tcp   strange_shirley
ff1687bd1901   nginx                              "/docker-entrypoint.…"   3 hours ago      Up 3 hours                  0.0.0.0:91->80/tcp, :::91->80/tcp   youthful_babbage

看来是出问题了,去掉 -d 直接在前台运行,看看运行日志:

[root@localhost eureka]# docker run -p 8762:8761 microservice-eureka-server-0.0.1
Error: Could not find or load main class ‐jar
[root@localhost eureka]# 

dockerfile 把启动命令改成 ENTRYPOINT ["java", "-jar", "app.jar"] 或 CMD ["java", "-jar", "app.jar"]

#ENTRYPOINT java ${JAVA_OPTS} ‐jar app.jar
CMD ["java", "-jar", "app.jar"]

重新构建:

[root@localhost eureka]# docker build -t microservice-eureka-server-0.0.1 .
Sending build context to Docker daemon  39.93MB
Step 1/5 : From java:8
 ---> d23bdf5b1b1b
Step 2/5 : ADD microservice-eureka-server-0.0.1-SNAPSHOT.jar /app.jar
 ---> 4172cd818475
Step 3/5 : RUN bash -c 'touch /app.jar'
 ---> Running in 624f155e0d2a
Removing intermediate container 624f155e0d2a
 ---> bb2ba940d4c3
Step 4/5 : EXPOSE 8761
 ---> Running in e1385b42bf4d
Removing intermediate container e1385b42bf4d
 ---> 880e1b33ac6a
Step 5/5 : CMD ["java", "-jar", "app.jar"]
 ---> Running in 68eb97f8d168
Removing intermediate container 68eb97f8d168
 ---> 34c7d6a0958a
Successfully built 34c7d6a0958a
Successfully tagged microservice-eureka-server-0.0.1:latest
[root@localhost eureka]# docker run -p 8762:8761 microservice-eureka-server-0.0.1

再次运行,成功

Docker 详解与微服务部署实战

加上JVM参数:

# ‐‐cap‐add=SYS_PTRACE 这个参数是让docker能支持在容器里能执行jdk自带类似jinfo,jmap这些命令,如果不需要在容器里执行这些命令可以不加

docker run ‐e JAVA_OPTS='‐Xms1028M ‐Xmx1028M ‐Xmn512M ‐Xss512K ‐XX:MetaspaceSize=256M ‐XX:MaxMetaspaceSize=

256M' ‐‐cap‐add=SYS_PTRACE ‐d ‐p 8761:8761 microservice‐eureka‐server:0.0.1
5、访问Docker宿主机IP:8762/,可正常显示Eureka Server首页

Docker 详解与微服务部署实战

转载自:https://juejin.cn/post/7238493216206962746
评论
请登录