Docker从入门到实践

Docker 从入门到实践
Author: yanpengGong         Email:yanpenggong@163.com

文章目录

前言

Docker 是个伟大的项目,它彻底释放了虚拟化的威力,极大降低了云计算资源供应的成本,同时让应用的分发、测试、部署和分发都变得前所未有的高效和轻松!

本书既适用于具备基础 Linux 知识的 Docker 初学者,也希望可供理解原理和实现的高级用户参考。同时,书中给出的实践案例,可供在进行实际部署时借鉴。前六章为基础内容,供用户理解 Docker 的基本概念和操作;7 ~ 9 章介绍一些高级操作;第 10 章给出典型的应用场景和实践案例;11 ~ 13 章介绍关于 Docker 实现的相关技术。14 ~ 17章介绍相关的一些开源项目。

一、 Docker 简介

1. Docker是什么

Docker 是一个开源项目,诞生于 2013 年初,最初是 dotCloud 公司内部的一个业余项目。它基于 Google 公司推出的 Go 语言实现。 项目后来加入了 Linux 基金会,遵从了 Apache 2.0 协议,项目代码在 GitHub 上进行维护。

Docker 自开源后受到广泛的关注和讨论,以至于 dotCloud 公司后来都改名为 Docker Inc。Redhat 已经在其 RHEL6.5 中集中支持 Docker;Google 也在其 PaaS 产品中广泛应用。

Docker 项目的目标是实现轻量级的操作系统虚拟化解决方案。 Docker 的基础是 Linux 容器(LXC)等技术。

在 LXC 的基础上 Docker 进行了进一步的封装,让用户不需要去关心容器的管理,使得操作更为简便。用户操作 Docker 的容器就像操作一个快速轻量级的虚拟机一样简单。

容器是在操作系统层面上实现虚拟化,直接复用本地主机的操作系统,而传统方式则是在硬件层面实现。

2. 使用Docker的理由

作为一种虚拟化方式,Docker 跟传统的虚拟化方式相比具有众多的优势。

首先,Docker 容器的启动可以在秒级实现,这相比传统的虚拟机方式要快得多。 其次,Docker 对系统资源的利用率很高,一台主机上可以同时运行数千个 Docker 容器。

容器除了运行其中应用外,基本不消耗额外的系统资源,使得应用的性能很高,同时系统的开销尽量小。传统虚拟机方式运行 10 个不同的应用就要起 10 个虚拟机,而Docker 只需要启动 10 个隔离的应用即可。

具体说来,Docker 在如下几个方面具有较大的优势。

  1. 更快速的交付和部署

    对开发和运维(devop)人员来说,最希望的就是一次创建或配置,可以在任意地方正常运行。

    开发者可以使用一个标准的镜像来构建一套开发容器,开发完成之后,运维人员可以直接使用这个容器来部署代码。 Docker 可以快速创建容器,快速迭代应用程序,并让整个过程全程可见,使团队中的其他成员更容易理解应用程序是如何创建和工作的。 Docker 容器很轻很快!容器的启动时间是秒级的,大量地节约开发、测试、部署的时间。

  2. 更高效的虚拟化

Docker 容器的运行不需要额外的 hypervisor 支持,它是内核级的虚拟化,因此可以实现更高的性能和效率。

  1. 更轻松的迁移和扩展

    Docker 容器几乎可以在任意的平台上运行,包括物理机、虚拟机、公有云、私有云、个人电脑、服务器等。 这种兼容性可以让用户把一个应用程序从一个平台直接迁移到另外一个。

  2. 更简单的管理

    使用 Docker,只需要小小的修改,就可以替代以往大量的更新工作。所有的修改都以增量的方式被分发和更新,从而实现自动化并且高效的管理。

  3. 对比传统虚拟机总结

    特性 容器 虚拟机
    启动 秒级 分钟级
    硬盘使用 一般为 MB 一般为 GB
    性能 接近原生 弱于
    系统支持量 单机支持上千个容器 一般几十个

二、Docker 基本概念

1. Docker 镜像

Docker 镜像就是一个只读的模板。

例如:一个镜像可以包含一个完整的 ubuntu 操作系统环境,里面仅安装了 Apache 或用户需要的其它应用程序。

镜像可以用来创建 Docker 容器。

Docker 提供了一个很简单的机制来创建镜像或者更新现有的镜像,用户甚至可以直接从其他人那里下载一个已经做好的镜像来直接使用。

2. Docker容器的运用

2018-08-04 17:51 更新

Docker 利用容器来运行应用。

容器是从镜像创建的运行实例。它可以被启动、开始、停止、删除。每个容器都是相互隔离的、保证安全的平台。

可以把容器看做是一个简易版的 Linux 环境(包括root用户权限、进程空间、用户空间和网络空间等)和运行在其中的应用程序。

注:镜像是只读的,容器在启动的时候创建一层可写层作为最上层。

3. Docker仓库

仓库是集中存放镜像文件的场所。有时候会把仓库和仓库注册服务器(Registry)混为一谈,并不严格区分。实际上,仓库注册服务器上往往存放着多个仓库,每个仓库中又包含了多个镜像,每个镜像有不同的标签(tag)。

仓库分为公开仓库(Public)和私有仓库(Private)两种形式。

最大的公开仓库是 Docker Hub,存放了数量庞大的镜像供用户下载。 国内的公开仓库包括 Docker Pool 等,可以提供大陆用户更稳定快速的访问。

当然,用户也可以在本地网络内创建一个私有仓库。

当用户创建了自己的镜像之后就可以使用 push 命令将它上传到公有或者私有仓库,这样下次在另外一台机器上使用这个镜像时候,只需要从仓库上 pull 下来就可以了。

注:Docker 仓库的概念跟 Git 类似,注册服务器可以理解为 GitHub 这样的托管服务。

三、Docker安装指南

官方网站上有各种环境下的 安装指南,这里主要介绍下CentOS系列的安装。

1. 使用官方安装脚本自动安装

[root@localhost software]# curl -fsSL https://get.docker.com | bash -s docker --mirror Aliyun
# Executing docker install script, commit: b2e29ef7a9a89840d2333637f7d1900a83e7153f
+ sh -c 'yum install -y -q yum-utils'
Package yum-utils-1.1.31-54.el7_8.noarch already installed and latest version
+ sh -c 'yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo'
Loaded plugins: fastestmirror, langpacks, 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
+ '[' stable '!=' stable ']'
+ sh -c 'yum makecache'
Loaded plugins: fastestmirror, langpacks, 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: ftp.sjtu.edu.cn
 * extras: mirrors.bfsu.edu.cn
 * updates: ftp.sjtu.edu.cn
base                                                                                                                                                                           | 3.6 kB  00:00:00     
docker-ce-stable                                                                                                                                                               | 3.5 kB  00:00:00     
extras                                                                                                                                                                         | 2.9 kB  00:00:00     
updates                                                                                                                                                                        | 2.9 kB  00:00:00     
Metadata Cache Created
+ sh -c 'yum install -y -q docker-ce docker-ce-cli containerd.io docker-scan-plugin docker-compose-plugin docker-ce-rootless-extras'
warning: /var/cache/yum/x86_64/7/docker-ce-stable/packages/docker-ce-20.10.17-3.el7.x86_64.rpm: Header V4 RSA/SHA512 Signature, key ID 621e9f35: NOKEY
Public key for docker-ce-20.10.17-3.el7.x86_64.rpm is not installed

Importing GPG key 0x621E9F35:
 Userid     : "Docker Release (CE rpm) <docker@docker.com>"
 Fingerprint: 060a 61c5 1b55 8a7f 742b 77aa c52f eb6b 621e 9f35
 From       : https://mirrors.aliyun.com/docker-ce/linux/centos/gpg

================================================================================

To run Docker as a non-privileged user, consider setting up the
Docker daemon in rootless mode for your user:

    dockerd-rootless-setuptool.sh install

Visit https://docs.docker.com/go/rootless/ to learn about rootless mode.


To run the Docker daemon as a fully privileged service, but granting non-root
users access, refer to https://docs.docker.com/go/daemon-access/

WARNING: Access to the remote API on a privileged Docker daemon is equivalent
         to root access on the host. Refer to the 'Docker daemon attack surface'
         documentation for details: https://docs.docker.com/go/attack-surface/

================================================================================

[root@localhost software]# 

也可以使用国内 daocloud 一键安装命令:

[root@localhost software]# curl -sSL https://get.daocloud.io/docker | sh

2. 手动安装

2.1 卸载旧版本

较旧的 Docker 版本称为 docker 或 docker-engine 。如果已安装这些程序,请卸载它们以及相关的依赖项。

[root@localhost software]# yum remove docker \
>                   docker-client \
>                   docker-client-latest \
>                   docker-common \
>                   docker-latest \
>                   docker-latest-logrotate \
>                   docker-logrotate \
>                   docker-engine
Loaded plugins: fastestmirror, langpacks, product-id, search-disabled-repos, subscription-manager

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

No Match for argument: docker
No Match for argument: docker-client
No Match for argument: docker-client-latest
No Match for argument: docker-common
No Match for argument: docker-latest
No Match for argument: docker-latest-logrotate
No Match for argument: docker-logrotate
No Match for argument: docker-engine
No Packages marked for removal
[root@localhost software]# 

2.2 安装 Docker Engine-Community

在新主机上首次安装 Docker Engine-Community 之前,需要设置 Docker 仓库。之后,您可以从仓库安装和更新 Docker。

2.2.1 设置仓库

安装所需的软件包。yum-utils 提供了 yum-config-manager ,并且 device mapper 存储驱动程序需要 device-mapper-persistent-datalvm2

[root@localhost software]# yum install -y yum-utils device-mapper-persistent-data lvm2
Loaded plugins: fastestmirror, langpacks, 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: ftp.sjtu.edu.cn
 * extras: mirrors.bfsu.edu.cn
 * updates: ftp.sjtu.edu.cn
Package yum-utils-1.1.31-54.el7_8.noarch already installed and latest version
Package device-mapper-persistent-data-0.8.5-3.el7_9.2.x86_64 already installed and latest version
Package 7:lvm2-2.02.187-6.el7_9.5.x86_64 already installed and latest version
Nothing to do
[root@localhost software]# 

设置稳定的仓库:

  • 使用官方源地址(比较慢)

    [root@localhost software]# yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
    Loaded plugins: fastestmirror, langpacks, product-id, subscription-manager
    
    This system is not registered with an entitlement server. You can use subscription-manager to register.
    
    adding repo from: https://download.docker.com/linux/centos/docker-ce.repo
    grabbing file https://download.docker.com/linux/centos/docker-ce.repo to /etc/yum.repos.d/docker-ce.repo
    repo saved to /etc/yum.repos.d/docker-ce.repo
    [root@localhost software]# 
    
    
  • 选择国内的 阿里云 源地址:

    [root@localhost software]# yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
    Loaded plugins: fastestmirror, langpacks, product-id, subscription-manager
    
    This system is not registered with an entitlement server. You can use subscription-manager to register.
    
    adding repo from: http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
    grabbing file http://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
    [root@localhost software]# 
    
  • 选择国内的 清华大学 源地址:

    [root@localhost software]# yum-config-manager --add-repo https://mirrors.tuna.tsinghua.edu.cn/docker-ce/linux/centos/docker-ce.repo
    Loaded plugins: fastestmirror, langpacks, 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.tuna.tsinghua.edu.cn/docker-ce/linux/centos/docker-ce.repo
    grabbing file https://mirrors.tuna.tsinghua.edu.cn/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
    [root@localhost software]# 
    
2.2.2 安装 Docker Engine-Community
  • 安装最新版本的 Docker Engine-Communitycontainerd

    [root@localhost software]# yum install docker-ce docker-ce-cli containerd.io
    Loaded plugins: fastestmirror, langpacks, 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: ftp.sjtu.edu.cn
     * extras: mirrors.bfsu.edu.cn
     * updates: ftp.sjtu.edu.cn
    docker-ce-stable                                                                                 | 3.5 kB  00:00:00     
    Package 1:docker-ce-cli-20.10.17-3.el7.x86_64 already installed and latest version
    Package containerd.io-1.6.7-3.1.el7.x86_64 already installed and latest version
    Resolving Dependencies
    --> Running transaction check
    ---> Package docker-ce.x86_64 3:20.10.17-3.el7 will be installed
    --> Processing Dependency: docker-ce-rootless-extras for package: 3:docker-ce-20.10.17-3.el7.x86_64
    --> Running transaction check
    ---> Package docker-ce-rootless-extras.x86_64 0:20.10.17-3.el7 will be installed
    --> Finished Dependency Resolution
    
    Dependencies Resolved
    
    ========================================================================================================================
     Package                              Arch              Version                       Repository                   Size
    ========================================================================================================================
    Installing:
     docker-ce                            x86_64            3:20.10.17-3.el7              docker-ce-stable             22 M
    Installing for dependencies:
     docker-ce-rootless-extras            x86_64            20.10.17-3.el7                docker-ce-stable            8.2 M
    
    Transaction Summary
    ========================================================================================================================
    Install  1 Package (+1 Dependent package)
    
    Total download size: 31 M
    Installed size: 115 M
    Is this ok [y/d/N]: y
    Downloading packages:
    (1/2): docker-ce-rootless-extras-20.10.17-3.el7.x86_64.rpm                                       | 8.2 MB  00:00:28     
    (2/2): docker-ce-20.10.17-3.el7.x86_64.rpm                                                       |  22 MB  00:01:18     
    ------------------------------------------------------------------------------------------------------------------------
    Total                                                                                   400 kB/s |  31 MB  00:01:18     
    Running transaction check
    Running transaction test
    Transaction test succeeded
    Running transaction
      Installing : 3:docker-ce-20.10.17-3.el7.x86_64                                                                    1/2 
      Installing : docker-ce-rootless-extras-20.10.17-3.el7.x86_64                                                      2/2 
      Verifying  : docker-ce-rootless-extras-20.10.17-3.el7.x86_64                                                      1/2 
      Verifying  : 3:docker-ce-20.10.17-3.el7.x86_64                                                                    2/2 
    
    Installed:
      docker-ce.x86_64 3:20.10.17-3.el7                                                                                     
    
    Dependency Installed:
      docker-ce-rootless-extras.x86_64 0:20.10.17-3.el7                                                                     
    
    Complete!
    [root@localhost software]# 
    

    如果提示您接受 GPG 密钥,请选是。

    有多个 Docker 仓库吗?

    如果启用了多个 Docker 仓库,则在 yum installyum update 命令中指定版本的情况下,进行的安装或更新将始终安装最高版本,这可能不适合您的稳定性需求。

    Docker 安装完默认未启动。并且已经创建好 docker 用户组,但该用户组下没有用户。

  • 安装特定版本:

    安装特定版本的 Docker Engine-Community,请在存储库中列出可用版本,然后选择并安装。

    • 列出并排序您存储库中可用的版本。此示例按版本号(从高到低)对结果进行排序。

      [root@localhost software]# yum list docker-ce --showduplicates | sort -r
       * updates: ftp.sjtu.edu.cn
      This system is not registered with an entitlement server. You can use subscription-manager to register.
                    : subscription-manager
      Loading mirror speeds from cached hostfile
      Loaded plugins: fastestmirror, langpacks, product-id, search-disabled-repos,
      Installed Packages
       * extras: mirrors.bfsu.edu.cn
      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: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 
      ...
       * base: ftp.sjtu.edu.cn
      Available Packages
      
      
      [root@localhost software]# 
      
    • 通过其完整的软件包名称安装特定版本,该软件包名称是软件包名称(docker-ce)加上版本字符串(第二列),从第一个冒号(:)一直到第一个连字符,并用连字符(-)分隔。例如:docker-ce-18.09.1

      [root@localhost software]# yum install docker-ce-<VERSION_STRING> docker-ce-cli-<VERSION_STRING> containerd.io
      

3. Docker启动

启动 Docker:

[root@localhost software]# sudo systemctl start docker
[root@localhost software]# 

通过运行 hello-world 镜像来验证是否正确安装了 Docker Engine-Community 。

[root@localhost software]# docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
2db29710123e: Pull complete 
Digest: sha256:7d246653d0511db2a6b2e0436cfd0e52ac8c066000264b3ce63331ac66dca625
Status: Downloaded newer image for hello-world:latest

Hello from Docker!
This message shows that your installation appears to be working correctly.

To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
    (amd64)
 3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.
 4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.

To try something more ambitious, you can run an Ubuntu container with:
 $ docker run -it ubuntu bash

Share images, automate workflows, and more with a free Docker ID:
 https://hub.docker.com/

For more examples and ideas, visit:
 https://docs.docker.com/get-started/

[root@localhost software]# chkconfig docker on
Note: Forwarding request to 'systemctl enable docker.service'.
Created symlink from /etc/systemd/system/multi-user.target.wants/docker.service to /usr/lib/systemd/system/docker.service.
[root@localhost software]# 

4. Docker卸载

  1. **首先搜索已经安装的docker 安装包 **

    [root@localhost software]# yum list installed|grep docker
    containerd.io.x86_64                    1.6.7-3.1.el7                  @docker-ce-stable
    docker-ce.x86_64                        3:20.10.17-3.el7               @docker-ce-stable
    docker-ce-cli.x86_64                    1:20.10.17-3.el7               @docker-ce-stable
    docker-ce-rootless-extras.x86_64        20.10.17-3.el7                 @docker-ce-stable
    docker-compose-plugin.x86_64            2.6.0-3.el7                    @docker-ce-stable
    docker-scan-plugin.x86_64               0.17.0-3.el7                   @docker-ce-stable
    [root@localhost software]#
    
  2. 分别删除安装包

    [root@localhost software]# yum -y remove docker-ce.x86_64 
    Loaded plugins: fastestmirror, langpacks, product-id, search-disabled-repos, subscription-manager
    
    This system is not registered with an entitlement server. You can use subscription-manager to register.
    
    Resolving Dependencies
    --> Running transaction check
    ---> Package docker-ce.x86_64 3:20.10.17-3.el7 will be erased
    --> Processing Dependency: docker-ce for package: docker-ce-rootless-extras-20.10.17-3.el7.x86_64
    --> Running transaction check
    ---> Package docker-ce-rootless-extras.x86_64 0:20.10.17-3.el7 will be erased
    --> Finished Dependency Resolution
    
    Dependencies Resolved
    
    ========================================================================================================================
     Package                              Arch              Version                      Repository                    Size
    ========================================================================================================================
    Removing:
     docker-ce                            x86_64            3:20.10.17-3.el7             @docker-ce-stable             96 M
    Removing for dependencies:
     docker-ce-rootless-extras            x86_64            20.10.17-3.el7               @docker-ce-stable             19 M
    
    Transaction Summary
    ========================================================================================================================
    Remove  1 Package (+1 Dependent package)
    
    Installed size: 115 M
    Downloading packages:
    Running transaction check
    Running transaction test
    Transaction test succeeded
    Running transaction
      Erasing    : 3:docker-ce-20.10.17-3.el7.x86_64                                                                    1/2 
      Erasing    : docker-ce-rootless-extras-20.10.17-3.el7.x86_64                                                      2/2 
      Verifying  : docker-ce-rootless-extras-20.10.17-3.el7.x86_64                                                      1/2 
      Verifying  : 3:docker-ce-20.10.17-3.el7.x86_64                                                                    2/2 
    
    Removed:
      docker-ce.x86_64 3:20.10.17-3.el7                                                                                     
    
    Dependency Removed:
      docker-ce-rootless-extras.x86_64 0:20.10.17-3.el7                                                                     
    
    Complete!
    [root@localhost software]# yum -y remove docker-ce-cli.x86_64 
    Loaded plugins: fastestmirror, langpacks, product-id, search-disabled-repos, subscription-manager
    
    This system is not registered with an entitlement server. You can use subscription-manager to register.
    
    Resolving Dependencies
    --> Running transaction check
    ---> Package docker-ce-cli.x86_64 1:20.10.17-3.el7 will be erased
    --> Processing Dependency: docker-ce-cli for package: docker-scan-plugin-0.17.0-3.el7.x86_64
    --> Running transaction check
    ---> Package docker-scan-plugin.x86_64 0:0.17.0-3.el7 will be erased
    --> Finished Dependency Resolution
    
    Dependencies Resolved
    
    ========================================================================================================================
     Package                         Arch                Version                       Repository                      Size
    ========================================================================================================================
    Removing:
     docker-ce-cli                   x86_64              1:20.10.17-3.el7              @docker-ce-stable              140 M
    Removing for dependencies:
     docker-scan-plugin              x86_64              0.17.0-3.el7                  @docker-ce-stable               13 M
    
    Transaction Summary
    ========================================================================================================================
    Remove  1 Package (+1 Dependent package)
    
    Installed size: 153 M
    Downloading packages:
    Running transaction check
    Running transaction test
    Transaction test succeeded
    Running transaction
      Erasing    : 1:docker-ce-cli-20.10.17-3.el7.x86_64                                                                1/2 
      Erasing    : docker-scan-plugin-0.17.0-3.el7.x86_64                                                               2/2 
      Verifying  : docker-scan-plugin-0.17.0-3.el7.x86_64                                                               1/2 
      Verifying  : 1:docker-ce-cli-20.10.17-3.el7.x86_64                                                                2/2 
    
    Removed:
      docker-ce-cli.x86_64 1:20.10.17-3.el7                                                                                 
    
    Dependency Removed:
      docker-scan-plugin.x86_64 0:0.17.0-3.el7                                                                              
    
    Complete!
    
    [root@localhost software]# yum -y remove docker-compose-plugin.x86_64 
    Loaded plugins: fastestmirror, langpacks, product-id, search-disabled-repos, subscription-manager
    
    This system is not registered with an entitlement server. You can use subscription-manager to register.
    
    Resolving Dependencies
    --> Running transaction check
    ---> Package docker-compose-plugin.x86_64 0:2.6.0-3.el7 will be erased
    --> Finished Dependency Resolution
    
    Dependencies Resolved
    
    ========================================================================================================================
     Package                            Arch                Version                    Repository                      Size
    ========================================================================================================================
    Removing:
     docker-compose-plugin              x86_64              2.6.0-3.el7                @docker-ce-stable               25 M
    
    Transaction Summary
    ========================================================================================================================
    Remove  1 Package
    
    Installed size: 25 M
    Downloading packages:
    Running transaction check
    Running transaction test
    Transaction test succeeded
    Running transaction
      Erasing    : docker-compose-plugin-2.6.0-3.el7.x86_64                                                             1/1 
      Verifying  : docker-compose-plugin-2.6.0-3.el7.x86_64                                                             1/1 
    
    Removed:
      docker-compose-plugin.x86_64 0:2.6.0-3.el7                                                                            
    
    Complete!
    
    [root@localhost software]# yum -y remove containerd.io.x86_64 
    Loaded plugins: fastestmirror, langpacks, product-id, search-disabled-repos, subscription-manager
    
    This system is not registered with an entitlement server. You can use subscription-manager to register.
    
    Resolving Dependencies
    --> Running transaction check
    ---> Package containerd.io.x86_64 0:1.6.7-3.1.el7 will be erased
    --> Finished Dependency Resolution
    
    Dependencies Resolved
    
    ========================================================================================================================
     Package                      Arch                  Version                      Repository                        Size
    ========================================================================================================================
    Removing:
     containerd.io                x86_64                1.6.7-3.1.el7                @docker-ce-stable                125 M
    
    Transaction Summary
    ========================================================================================================================
    Remove  1 Package
    
    Installed size: 125 M
    Downloading packages:
    Running transaction check
    Running transaction test
    Transaction test succeeded
    Running transaction
      Erasing    : containerd.io-1.6.7-3.1.el7.x86_64                                                                   1/1 
      Verifying  : containerd.io-1.6.7-3.1.el7.x86_64                                                                   1/1 
    
    Removed:
      containerd.io.x86_64 0:1.6.7-3.1.el7                                                                                  
    
    Complete!
    [root@localhost software]# 
    
  3. **删除docker 镜像 **

    [root@localhost software]# rm -rf /var/lib/docker
    [root@localhost software]# 
    
  4. **再次check docker是否已经卸载成功 **

    [root@localhost software]# yum list installed|grep docker 
    [root@localhost software]# 
    

    如果没有,就表示卸载成功。

四、Docker使用

1. Docker Hello World

Docker 允许你在容器内运行应用程序, 使用 docker run 命令来在容器内运行一个应用程序。输出Hello world

[root@localhost software]# docker run ubuntu:15.10 /bin/echo "Hello world"
Hello world
[root@localhost software]# 

各个参数解析:

  • docker: Docker 的二进制执行文件。
  • run: 与前面的 docker 组合来运行一个容器。
  • ubuntu:15.10 指定要运行的镜像,Docker 首先从本地主机上查找镜像是否存在,如果不存在,Docker 就会从镜像仓库 Docker Hub 下载公共镜像。
  • /bin/echo “Hello world”: 在启动的容器里执行的命令

以上命令完整的意思可以解释为:Docker 以 ubuntu15.10 镜像创建一个新容器,然后在容器里执行 bin/echo “Hello world”,然后输出结果。

1.1 运行交互式的容器

通过 docker 的两个参数 -i -t,让 docker 运行的容器实现**“对话”**的能力:

[root@localhost software]# docker run -i -t ubuntu:15.10 /bin/bash
root@ed4a85705ff3:/# 

各个参数解析:

  • -t: 在新容器内指定一个伪终端或终端。
  • -i: 允许你对容器内的标准输入 (STDIN) 进行交互。

注意第二行 root@ed4a85705ff3:/#,此时我们已进入一个 ubuntu15.10 系统的容器

我们尝试在容器中运行命令 cat /proc/versionls分别查看当前系统的版本信息和当前目录下的文件列表

root@ed4a85705ff3:/# cat /proc/version
Linux version 3.10.0-862.el7.x86_64 (builder@kbuilder.dev.centos.org) (gcc version 4.8.5 20150623 (Red Hat 4.8.5-28) (GCC) ) #1 SMP Fri Apr 20 16:44:24 UTC 2018
root@ed4a85705ff3:/# ls
bin  boot  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
root@ed4a85705ff3:/# 

可以通过运行 exit 命令或者使用 CTRL+D 来退出容器。

root@ed4a85705ff3:/# exit
exit
[root@localhost software]# 

注意第三行中 [root@localhost software]# 表明我们已经退出了当前的容器,返回到当前的主机中。

1.2 启动容器(后台模式)

创建一个以进程方式运行的容器:

[root@localhost software]# docker run -d ubuntu:15.10 /bin/sh -c "while true; do echo hello world; sleep 1; done"
f8f69699ea5ee423c804656040a2512541dc1503320a19c573c5bf9a29bfb0a0
[root@localhost software]# 

在输出中,我们没有看到期望的 hello world,而是一串长字符

f8f69699ea5ee423c804656040a2512541dc1503320a19c573c5bf9a29bfb0a0

这个长字符串叫做容器 ID,对每个容器来说都是唯一的,我们可以通过容器 ID 来查看对应的容器发生了什么。

首先,我们需要确认容器有在运行,可以通过 docker ps 来查看:

[root@localhost software]# docker ps
CONTAINER ID   IMAGE          COMMAND                  CREATED          STATUS          PORTS     NAMES
f8f69699ea5e   ubuntu:15.10   "/bin/sh -c 'while t…"   59 seconds ago   Up 58 seconds             reverent_rubin
[root@localhost software]# 

输出详情介绍:

  • CONTAINER ID: 容器 ID。

  • IMAGE: 使用的镜像。

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

  • CREATED: 容器的创建时间。

  • STATUS: 容器状态。状态有7种:

    • created(已创建)

    • restarting(重启中)

    • running 或 Up(运行中)

    • removing(迁移中)

    • paused(暂停)

    • exited(停止)

    • dead(死亡)

  • PORTS: 容器的端口信息和使用的连接类型(tcp\udp)。

  • NAMES: 自动分配的容器名称。

在宿主主机内使用 docker logs 命令,查看容器内的标准输出:

[root@localhost software]# docker logs f8f69699ea5e
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
...

1.3 停止容器

使用 docker stop 命令来停止容器:

[root@localhost software]# docker stop f8f69699ea5e
f8f69699ea5e
[root@localhost software]# 

通过 docker ps 查看,容器已经停止工作:

[root@localhost software]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@localhost software]#

可以看到容器已经不在了。

也可以用下面的命令来停止:

[root@localhost software]# docker stop reverent_rubin
reverent_rubin
[root@localhost software]# 

2. Docker容器使用

2.1 Docker 客户端

docker 客户端非常简单 ,我们可以直接输入 docker 命令来查看到 Docker 客户端的所有命令选项。

[root@localhost software]# docker

Usage:  docker [OPTIONS] COMMAND

A self-sufficient runtime for containers

Options:
      --config string      Location of client config files (default "/root/.docker")
  -c, --context string     Name of the context to use to connect to the daemon (overrides DOCKER_HOST env var and
                           default context set with "docker context use")
  -D, --debug              Enable debug mode
  -H, --host list          Daemon socket(s) to connect to
  -l, --log-level string   Set the logging level ("debug"|"info"|"warn"|"error"|"fatal") (default "info")
      --tls                Use TLS; implied by --tlsverify
      --tlscacert string   Trust certs signed only by this CA (default "/root/.docker/ca.pem")
      --tlscert string     Path to TLS certificate file (default "/root/.docker/cert.pem")
      --tlskey string      Path to TLS key file (default "/root/.docker/key.pem")
      --tlsverify          Use TLS and verify the remote
  -v, --version            Print version information and quit

Management Commands:
  app*        Docker App (Docker Inc., v0.9.1-beta3)
  builder     Manage builds
  buildx*     Docker Buildx (Docker Inc., v0.8.2-docker)
  config      Manage Docker configs
  container   Manage containers
  context     Manage contexts
  image       Manage images
  manifest    Manage Docker image manifests and manifest lists
  network     Manage networks
  node        Manage Swarm nodes
  plugin      Manage plugins
  scan*       Docker Scan (Docker Inc., v0.17.0)
  secret      Manage Docker secrets
  service     Manage services
  stack       Manage Docker stacks
  swarm       Manage Swarm
  system      Manage Docker
  trust       Manage trust on Docker images
  volume      Manage volumes

Commands:
  attach      Attach local standard input, output, and error streams to a running container
  build       Build an image from a Dockerfile
  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
  events      Get real time events from the server
  exec        Run a command in a running container
  export      Export a container's filesystem as a tar archive
  history     Show the history of an image
  images      List images
  import      Import the contents from a tarball to create a filesystem image
  info        Display system-wide information
  inspect     Return low-level information on Docker objects
  kill        Kill one or more running containers
  load        Load an image from a tar archive or STDIN
  login       Log in to a Docker registry
  logout      Log out from a Docker registry
  logs        Fetch the logs of a container
  pause       Pause all processes within one or more containers
  port        List port mappings or a specific mapping for the container
  ps          List containers
  pull        Pull an image or a repository from a registry
  push        Push an image or a repository to a registry
  rename      Rename a container
  restart     Restart one or more containers
  rm          Remove one or more containers
  rmi         Remove one or more images
  run         Run a command in a new container
  save        Save one or more images to a tar archive (streamed to STDOUT by default)
  search      Search the Docker Hub for images
  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
  tag         Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE
  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
  version     Show the Docker version information
  wait        Block until one or more containers stop, then print their exit codes

Run 'docker COMMAND --help' for more information on a command.

To get more help with docker, check out our guides at https://docs.docker.com/go/guides/
[root@localhost software]# 

可以通过命令docker command --help 更深入的了解指定的 Docker 命令使用方法。

例如我们要查看 docker stats 指令的具体使用方法:

[root@localhost software]# docker stats --help

Usage:  docker stats [OPTIONS] [CONTAINER...]

Display a live stream of container(s) resource usage statistics

Options:
  -a, --all             Show all containers (default shows just running)
      --format string   Pretty-print images using a Go template
      --no-stream       Disable streaming stats and only pull the first result
      --no-trunc        Do not truncate output
[root@localhost software]# 

2.2 容器使用

2.2.1 获取镜像

如果本地没有 ubuntu 镜像,可以使用 docker pull 命令来载入 ubuntu 镜像:

[root@localhost software]# docker pull ubuntu
Using default tag: latest
latest: Pulling from library/ubuntu
d19f32bd9e41: Pull complete 
Digest: sha256:34fea4f31bf187bc915536831fd0afc9d214755bf700b5cdb1336c82516d154e
Status: Downloaded newer image for ubuntu:latest
docker.io/library/ubuntu:latest
[root@localhost software]# 
2.2.2 启动容器

以下命令使用 ubuntu 镜像启动一个容器,参数为以命令行模式进入该容器:

[root@localhost software]# docker run -it ubuntu /bin/bash
root@5358c9601c75:/# 

参数说明:

  • -i: 交互式操作。
  • -t: 终端。
  • ubuntu: ubuntu 镜像。
  • /bin/bash:放在镜像名后的是命令,这里我们希望有个交互式 Shell,因此用的是 /bin/bash。

要退出终端,直接输入 exit:

root@5358c9601c75:/# exit
exit
[root@localhost software]# 
2.2.3 启动已停止运行的容器

查看所有的容器命令如下:

[root@localhost software]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                  CREATED              STATUS                          PORTS     NAMES
5358c9601c75   ubuntu         "/bin/bash"              About a minute ago   Exited (0) About a minute ago   
[root@localhost software]# 

使用 docker start 启动一个已停止的容器:

[root@localhost software]# docker start 5358c9601c75
5358c9601c75
[root@localhost software]# 
2.2.4 后台运行

在大部分的场景下,希望 docker 的服务是在后台运行的,可以过 -d 指定容器的运行模式。

[root@localhost software]# docker run -itd --name ubuntu-test ubuntu /bin/bash
c293ba3fecac5d8f833bec90aca18670ba253fa0af7f7697990c9b8933902c23
[root@localhost software]# docker ps
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS              PORTS     NAMES
c293ba3fecac   ubuntu    "/bin/bash"   23 seconds ago   Up 22 seconds                 ubuntu-test
5358c9601c75   ubuntu    "/bin/bash"   4 minutes ago    Up About a minute         
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Kungs8

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值