龙空技术网

10年老架构,带你CentOS 7 Docker基本特性入门实践,上篇

程序员高级码农II 49

前言:

现在看官们对“centos72是什么系统”都比较关注,同学们都想要了解一些“centos72是什么系统”的相关知识。那么小编在网上网罗了一些关于“centos72是什么系统””的相关知识,希望姐妹们能喜欢,姐妹们一起来了解一下吧!

前言

Docker是一个开源的应用容器引擎,开发人员可以非常容易地打包已经开发好的应用,同时将应用相关的依赖包也打包到这样一个可移植的容器中,然后发布到任意的Linux主机系统上。

Docker是基于Linux Container(LXC)技术实现的一个轻量级虚拟化解决方案,用户可以直接使用容器(Container),来构建自己的应用程序,应用开发人员无需将注意力集中在容器的管理上。Docker的目标是“Build, Ship and Run Any App, Anywhere”,这说明了使用Docker能够实现应用运行的可移植性、便捷性,对开发人员非常友好,只要你的应用是基于Docker进行构建和部署的,在任何时候任何支持Docker的Linux发行版操作系统上都可以运行你的应用程序。

Docker是基于Go语言开发的, 代码开源,可以在Github上查看对应的源码:

基本构架

Docker基于Client-Server架构,Docker daemon是服务端,Docker client是客户端。Docker的基本架构,如下图所示:

上图中,除了展现了Docker的Client、Server、Containers、Images、Registry之间的关系,我们主要说明Docker daemon和Docker client,关于其他组件我们后面详述:

Docker daemon

Docker daemon运行在宿主机上,它是一个long-running进程,用户通过Docker client与Docker daemon进行交互。

Docker client

Docker client为用户提供了与Docker daemon交互的接口,在安装Docker的时候就已经安装,可以通过docker命令来操作。一个Docker client可以与同一个宿主机上的Docker daemon交互,也可以与远程的Docker daemon进行交互。

基本概念

Registry

Registry是一个服务,它负责管理一个或多个Repository(仓库),而Repository还包含公共仓库(Public Repository)和私有仓库(Private Repository)。默认的Registry是Docker Hub,它管理了按照不同用途分类的很多公共仓库,任何人都可以到Docker Hub上查找自己需要的Image,或者可以使用docker search命令来搜索对应Image,例如我们查询关键词hadoop,示例命令如下所示:

docker search hadoop

查询结果如下所示:

NAME                             DESCRIPTION                                     STARS     OFFICIAL   AUTOMATEDsequenceiq/hadoop-docker         An easy way to try Hadoop                       428                  [OK]sequenceiq/hadoop-ubuntu         An easy way to try Hadoop on Ubuntu             40                   [OK]uhopper/hadoop                   Base Hadoop image with dynamic configurati...   16                   [OK]ruo91/hadoop                     Apache hadoop 2.x - Pseudo-Distributed Mode     12                   [OK]harisekhon/hadoop                Apache Hadoop (HDFS + Yarn, tags 2.5 - 2.7)     8                    [OK]gelog/hadoop                     Use at your own risk.                           5                    [OK]athlinks/hadoop                  Distributed Highly Available Hadoop Cluste...   3                    [OK]dockmob/hadoop                   Docker images for Apache Hadoop (YARN, HDF...   3                    [OK]uhopper/hadoop-resourcemanager   Hadoop resourcemanager                          3                    [OK]harisekhon/hadoop-dev            Apache Hadoop (HDFS + Yarn) + Dev Tools + ...   3                    [OK]izone/hadoop                     Hadoop 2.7.3 Ecosystem fully distributed, ...   3                    [OK]uhopper/hadoop-namenode          Hadoop namenode                                 2                    [OK]singularities/hadoop             Apache Hadoop                                   2                    [OK]uhopper/hadoop-datanode          Hadoop datanode                                 2                    [OK]uhopper/hadoop-nodemanager       Hadoop nodemanager                              2                    [OK]lewuathe/hadoop-master           Multiple node hadoop cluster on Docker.         2                    [OK]robingu/hadoop                   hadoop 2.7                                      1                    [OK]mcapitanio/hadoop                Docker image running Hadoop in psedo-distr...   1                    [OK]takaomag/hadoop                  docker image of archlinux (hadoop)              1                    [OK]ymian/hadoop                     hadoop                                          0                    [OK]2breakfast/hadoop                hadoop in docker                                0                    [OK]ading1977/hadoop                 Docker image for multi-node hadoop cluster.     0                    [OK]meteogroup/hadoop                Apache™ Hadoop® in a docker image.              0                    [OK]hegand/hadoop-base               Hadoop base docker image                        0                    [OK]elek/hadoop                      Base image for hadoop components (yarn/hdfs)    0                    [OK]

上面可以看到,与hadoop相关的Image都被列出来了,可以根据自己的需要选择对应的Image下载并构建应用。

Image

Docker Image是Docker Container的基础,一个Image是对一个Root文件系统的执行变更操作的有序集合,也包括在运行时一个Container内部需要执行的参数的变化。一个Image是静态的、无状态的,它具有不变性。如果想要修改一个Image,实际是重新创建了新的Image,在原来Image基础上修改后的一个副本。所以,往往我们制作一个Image的时候,可以基于已经存在的Image来构建新的的Image,然后Push到Repository中。

Repository

一个Repository是Docker Image的集合,它可以被Push到Registry而被共享,在Docker Hub就可以看到很多组织或个人贡献的Image,供大家共享。当然,你也可以将自己构建的Image Push到私有的Repository中。在Repository中不同的Image是通过tag来识别的,例如latest 、5.5.0等等。

Container

Container是一个Docker Image的运行时实例,从一个Image可以创建多个包含该应用的Container。一个Container包含如下几个部分:

一个Docker Image执行环境一个标准指令的集合

安装启动Docker

我使用了CentOS 7操作系统,可以非常容易地安装Docker环境。假设,下面我们都是用root用户进行操作,执行如下命令进行准备工作:

yum install -y yum-utilsyum-config-manager \    --add-repo \ ;yum makecache fast

上面首先安装了yum-utils,它提供了yum-config-manager管理工具,然后安装了最新稳定版本的Repository文件,最后更新yum的package索引。安装最新版本的Docker,当前是1.13.1,执行如下命令:

sudo yum -y install docker-engine

首次安装docker-engine,输出类似如下日志信息:

Loaded plugins: fastestmirror, langpacksLoading mirror speeds from cached hostfile * base: mirrors.btte.net * extras: mirrors.btte.net * updates: mirrors.btte.netResolving Dependencies--> Running transaction check---> Package docker-engine.x86_64 0:1.13.1-1.el7.centos will be installed--> Processing Dependency: docker-engine-selinux >= 1.13.1-1.el7.centos for package: docker-engine-1.13.1-1.el7.centos.x86_64--> Running transaction check---> Package docker-engine-selinux.noarch 0:1.13.1-1.el7.centos will be installed--> Finished Dependency Resolution Dependencies Resolved ================================================================================================================================================================================================================= Package                                                  Arch                                      Version                                                 Repository                                      Size=================================================================================================================================================================================================================Installing: docker-engine                                            x86_64                                    1.13.1-1.el7.centos                                     docker-main                                     19 MInstalling for dependencies: docker-engine-selinux                                    noarch                                    1.13.1-1.el7.centos                                     docker-main                                     28 k Transaction Summary=================================================================================================================================================================================================================Install  1 Package (+1 Dependent package) Total download size: 19 MInstalled size: 65 MDownloading packages:warning: /var/cache/yum/x86_64/7/docker-main/packages/docker-engine-selinux-1.13.1-1.el7.centos.noarch.rpm: Header V4 RSA/SHA512 Signature, key ID 2c52609d: NOKEY             ] 1.2 MB/s | 944 kB  00:00:14 ETAPublic key for docker-engine-selinux-1.13.1-1.el7.centos.noarch.rpm is not installed(1/2): docker-engine-selinux-1.13.1-1.el7.centos.noarch.rpm                                                                                                                               |  28 kB  00:00:01    (2/2): docker-engine-1.13.1-1.el7.centos.x86_64.rpm                                                                                                                                       |  19 MB  00:00:04    -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Total                                                                                                                                                                            4.5 MB/s |  19 MB  00:00:04    Retrieving key from  GPG key 0x2C52609D: Userid     : "Docker Release Tool (releasedocker) <docker@docker.com>" Fingerprint: 5811 8e89 f3a9 1289 7c07 0adb f762 2157 2c52 609d From       :  transaction checkRunning transaction testTransaction test succeededRunning transaction  Installing : docker-engine-selinux-1.13.1-1.el7.centos.noarch                                                                                                                                              1/2libsemanage.semanage_direct_install_info: Overriding docker module at lower priority 100 with module at priority 400.restorecon:  lstat(/var/lib/docker) failed:  No such file or directorywarning: %post(docker-engine-selinux-1.13.1-1.el7.centos.noarch) scriptlet failed, exit status 255Non-fatal POSTIN scriptlet failure in rpm package docker-engine-selinux-1.13.1-1.el7.centos.noarch  Installing : docker-engine-1.13.1-1.el7.centos.x86_64                                                                                                                                                      2/2  Verifying  : docker-engine-selinux-1.13.1-1.el7.centos.noarch                                                                                                                                              1/2  Verifying  : docker-engine-1.13.1-1.el7.centos.x86_64                                                                                                                                                      2/2 Installed:  docker-engine.x86_64 0:1.13.1-1.el7.centos                                                                                                                                                                     Dependency Installed:  docker-engine-selinux.noarch 0:1.13.1-1.el7.centos                                                                                                                                                             Complete!

可见,Docker已经成功安装。下面,我们就可以启动Docker了,执行如下命令,启动Docker(Docker Engine):

systemctl start docker

可以查看一下当前系统上的进程,执行ps -ef | grep docker确认Docker已经启动:

root       2717      1  8 21:52 ?        00:00:00 /usr/bin/dockerdroot       2723   2717  1 21:52 ?        00:00:00 docker-containerd -l unix:///var/run/docker/libcontainerd/docker-containerd.sock --metrics-interval=0 --start-timeout 2m --state-dir /var/run/docker/libcontainerd/containerd --shim docker-containerd-shim --runtime docker-runcroot       2920   2645  0 21:52 pts/0    00:00:00 grep --color=auto docker

下面,我们验证一下,Docker启动了,应该就可以在一个Container中运行一个准备好的应用,执行如下命令:

docker run hello-world

基于一个名称为hello-world的Image,启动Container并运行它,启动过程如下所示:

Unable to find image 'hello-world:latest' locallylatest: Pulling from library/hello-world78445dd45222: Pull completeDigest: sha256:c5515758d4c5e1e838e9cd307f6c6a0d620b5e07e6f927b07d05f6d12a1ac8d7Status: 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. 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: ;For more examples and ideas, visit: 

首先可以看到,因为本地没有下载过该Image,所以会先从Docker Hub上下载,对应的tag是latest。另外,也可以看到提示信息“Hello from Docker! ”,表示我们的环境配置没问题,可以启动Container运行应用程序。这里,还给出了运行我们这个名称为hello-world的示例Image在Container中运行过程中,Docker的基本运行机制如下所示:

Docker Client连接到Docker daemonDocker daemon从Docker Hub上下载名称为hello-world的ImageDocker daemon基于这个Image创建了一个新的Container,并运行应用程序,输出“Hello from Docker!”Docker daemon将结果输出到Docker Client,也就是我们的终端上

现在,我们可能想知道hello-world这个Image是如何构建,才能够最终在我们的Docker Container中运行,请看下文。

构建Image

通过创建Dockerfile可以构建Image,Docker会从一个Dockerfile中读取一系列指令来构建Image。一个Dockerfile是一个文本文件,它包含了一组能够运行的命令行,这些命令行就组装成了一个Docker Image。下面,我们看一下前面提到的名称为hello-world的Image是如何构建,可以在Github上看到该Image的代码,链接在这里:。hello-world一定对应一个Dockerfile,内容如下所示:

FROM scratchCOPY hello /CMD ["/hello"]

上面这3条命令,就对应着hello-world这个Image:第一行,FROM命令:是从一个已知的基础Image来构建新的Image,这里scratch是一个显式指定的空Image;第二行,COPY命令:是将指定的新文件或目录,拷贝到Container中指定的目录下面,这里讲hello这个可执行文件复制到Container中的根路径/下面;第三行,CMD命令:是运行指定的命令行,包含指定的命令名称、参数列表可见,上面的hello可执行文件是已经构编译好的文件,它是从一个C程序文件(Github链接:)编译而来的,源码文件hello.c内容如下所示:

#include <sys/syscall.h> #ifndef DOCKER_IMAGE    #define DOCKER_IMAGE "hello-world"#endif #ifndef DOCKER_GREETING    #define DOCKER_GREETING "Hello from Docker!"#endif const char message[] =    "\n"    DOCKER_GREETING "\n"    "This message shows that your installation appears to be working correctly.\n"    "\n"    "To generate this message, Docker took the following steps:\n"    " 1. The Docker client contacted the Docker daemon.\n"    " 2. The Docker daemon pulled the \"" DOCKER_IMAGE "\" image from the Docker Hub.\n"    " 3. The Docker daemon created a new container from that image which runs the\n"    "    executable that produces the output you are currently reading.\n"    " 4. The Docker daemon streamed that output to the Docker client, which sent it\n"    "    to your terminal.\n"    "\n"    "To try something more ambitious, you can run an Ubuntu container with:\n"    " $ docker run -it ubuntu bash\n"    "\n"    "Share images, automate workflows, and more with a free Docker ID:\n"    " \n"    "\n"    "For more examples and ideas, visit:\n"    " \n"    "\n"; void _start() {    //write(1, message, sizeof(message) - 1);    syscall(SYS_write, 1, message, sizeof(message) - 1);     //_exit(0);    syscall(SYS_exit, 0);}

编译生成可执行文件hello,然后可以使用Docker的build命令来构建生成Image:

docker build -t hello-world

现在,hello-world是如何构建Image的就已经非常清楚了。下面,我们通过参考官网的用户指南,编写一个Dockerfile来制作一个Image,了解如何实现自己的应用:

编写Dockerfile

首先,创建一个单独的目录来存放我们将要构建的Dockerfile文件:

mkdir mydockerbuildcd mydockerbuildvi Dockerfile

在Dockerfile中输入如下内容:

FROM docker/whalesay:latestRUN apt-get -y update && apt-get install -y fortunesCMD /usr/games/fortune -a | cowsay

上面FROM命令表示,Docker基于该docker/whalesay:latest来构建新的Image,这个Image在Docker Hub上,链接在这里:,对应的源码可以看Github:。RUN命令行表示安装fortunes程序包,最后的CMD命令指示将运行/usr/games/fortune命令。

构建Image

保存上述3行命令到文件中,在当前mydockerbuild目录中执行构建Image的命令:

docker build -t docker-whale 

构建过程,输出信息如下:

Sending build context to Docker daemon 2.048 kBStep 1/3 : FROM docker/whalesay:latest ---> 6b362a9f73ebStep 2/3 : RUN apt-get -y update && apt-get install -y fortunes ---> Running in bfddc2134d23Ign  trusty InReleaseGet:1  trusty-updates InRelease [65.9 kB]Get:2  trusty-security InRelease [65.9 kB]Hit  trusty Release.gpgGet:3  trusty-updates/main Sources [485 kB]Get:4  trusty-updates/restricted Sources [5957 B]Get:5  trusty-updates/universe Sources [220 kB]Get:6  trusty-updates/main amd64 Packages [1197 kB]Get:7  trusty-updates/restricted amd64 Packages [20.4 kB]Get:8  trusty-updates/universe amd64 Packages [516 kB]Get:9  trusty-security/main Sources [160 kB]Get:10  trusty-security/restricted Sources [4667 B]Get:11  trusty-security/universe Sources [59.4 kB]Get:12  trusty-security/main amd64 Packages [730 kB]Get:13  trusty-security/restricted amd64 Packages [17.0 kB]Get:14  trusty-security/universe amd64 Packages [199 kB]Hit  trusty ReleaseHit  trusty/main SourcesHit  trusty/restricted SourcesHit  trusty/universe SourcesHit  trusty/main amd64 PackagesHit  trusty/restricted amd64 PackagesHit  trusty/universe amd64 PackagesFetched 3745 kB in 55s (67.1 kB/s)Reading package lists...Reading package lists...Building dependency tree...Reading state information...The following extra packages will be installed:  fortune-mod fortunes-min librecode0Suggested packages:  x11-utils bsdmainutilsThe following NEW packages will be installed:  fortune-mod fortunes fortunes-min librecode00 upgraded, 4 newly installed, 0 to remove and 92 not upgraded.Need to get 1961 kB of archives.After this operation, 4817 kB of additional disk space will be used.Get:1  trusty/main librecode0 amd64 3.6-21 [771 kB]Get:2  trusty/universe fortune-mod amd64 1:1.99.1-7 [39.5 kB]Get:3  trusty/universe fortunes-min all 1:1.99.1-7 [61.8 kB]Get:4  trusty/universe fortunes all 1:1.99.1-7 [1089 kB]debconf: unable to initialize frontend: Dialogdebconf: (TERM is not set, so the dialog frontend is not usable.)debconf: falling back to frontend: Readlinedebconf: unable to initialize frontend: Readlinedebconf: (This frontend requires a controlling tty.)debconf: falling back to frontend: Teletypedpkg-preconfigure: unable to re-open stdin:Fetched 1961 kB in 5s (340 kB/s)Selecting previously unselected package librecode0:amd64.(Reading database ... 13116 files and directories currently installed.)Preparing to unpack .../librecode0_3.6-21_amd64.deb ...Unpacking librecode0:amd64 (3.6-21) ...Selecting previously unselected package fortune-mod.Preparing to unpack .../fortune-mod_1%3a1.99.1-7_amd64.deb ...Unpacking fortune-mod (1:1.99.1-7) ...Selecting previously unselected package fortunes-min.Preparing to unpack .../fortunes-min_1%3a1.99.1-7_all.deb ...Unpacking fortunes-min (1:1.99.1-7) ...Selecting previously unselected package fortunes.Preparing to unpack .../fortunes_1%3a1.99.1-7_all.deb ...Unpacking fortunes (1:1.99.1-7) ...Setting up librecode0:amd64 (3.6-21) ...Setting up fortune-mod (1:1.99.1-7) ...Setting up fortunes-min (1:1.99.1-7) ...Setting up fortunes (1:1.99.1-7) ...Processing triggers for libc-bin (2.19-0ubuntu6.6) ... ---> 98403143b081Removing intermediate container bfddc2134d23Step 3/3 : CMD /usr/games/fortune -a | cowsay ---> Running in 8831a7231adc ---> 08d234c4ee26Removing intermediate container 8831a7231adcSuccessfully built 08d234c4ee26

或者,可以通过-f选项,直接指定Dockerfile文件的绝对路径,构建命令如下所示:

docker build -f ~/mydockerbuild/Dockerfile -t docker-whale .

这样我们自己的Image就构建好了,名称为docker-whale。下面,看下构建我们这个Image的基本流程流程:

Docker检查确保当前Dockerfile中是否有需要build的内容Docker检查是否存在whalesay这个ImageDocker会启动一个临时的容器6b362a9f73eb,来运行whalesay这个image。在这个临时的Container中,Docker会执行RUN这行命令,安装fortune程序包一个新的中间container被创建8831a7231adc,在Dockerfile中增加了一个CMD层(Layer),对应一个Container,然后中间container8831a7231adc被删除

我们在构建一个Image时,会自动下载依赖的Docker Image,其实也可以预先下载对应的Image,使用类似下面的命令:

docker pull mysql:5.5

这样就可以下载MySQL 5.5的Image到本地。

查看构建的Image

查看当前image列表,其中包含我们刚刚构建好的Image,执行docker images命令,结果如下所示:

REPOSITORY          TAG                 IMAGE ID            CREATED             SIZEdocker-whale        latest              08d234c4ee26        9 minutes ago       256 MBubuntu              latest              f49eec89601e        5 weeks ago         129 MBhello-world         latest              48b5124b2768        6 weeks ago         1.84 kBdocker/whalesay     latest              6b362a9f73eb        21 months ago       247 MB

第一个docker-whale,就是我们自己创建的。

启动Docker Container

接着,基于我们已经构建好的Image,在Docker Container中运行这个应用,执行命令:

docker run docker-whale

运行结果,如下所示:

_____________________________/ IBM:                         \|                              || I've Been Moved              ||                              || Idiots Become Managers       ||                              || Idiots Buy More              ||                              || Impossible to Buy Machine    ||                              || Incredibly Big Machine       ||                              || Industry's Biggest Mistake   ||                              || International Brotherhood of || Mercenaries                  ||                              || It Boggles the Mind          ||                              || It's Better Manually         ||                              |\ Itty-Bitty Machines          / ------------------------------    \     \      \                        ##        .                        ## ## ##       ==                     ## ## ## ##      ===                 /""""""""""""""""___/ ===        ~~~ {~~ ~~~~ ~~~ ~~~~ ~~ ~ /  ===- ~~~         \______ o          __/                  \    \        __/                      \____\______/  

另外,我们可以进入到Docker Hub:,创建一个自己的账号,然后创建自己的Image,当然也可以找到各种免费共享的Image,可以基于这些Image来构建自己的Image。Docker Hub页面,如下所示:

下面是一个例子,可以在启动Docker Container时,通过命令行直接向Container内部应用传递参数值,命令行如下所示:

docker run docker/whalesay cowsay boodocker run docker/whalesay cowsay boo-boo

可以看到,输出的内容根据启动Container传递的参数值而变化。

查看Docker Container

查看当前主机上所有状态的Docker Container,可以执行如下命令(下面的命令都是等价的):

docker ps -adocker container ps -adocker container ls -a

示例结果,如下所示:

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES5ab157767bbd        training/postgres   "su postgres -c '/..."   6 seconds ago       Up 5 seconds        5432/tcp            pgdbda91889d6313        training/postgres   "su postgres -c '/..."   49 seconds ago       Up 2 seconds        5432/tcp            webappdb5d86616e9a1d        docker-whale        "/bin/sh -c '/usr/..."   24 minutes ago       Exited (0) 7 seconds ago                             elastic_mcnultyabec6410bcac        docker/whalesay     "cowsay boo"             27 minutes ago       Exited (0) 27 minutes ago                            upbeat_edison72d0b2bb5d6a        training/postgres   "su postgres -c '/..."   4 hours ago         Up 4 hours          5432/tcp            dbfc9b0bb6ae8e        ubuntu              "/bin/bash"              4 hours ago         Up 4 hours                              networktestfc9b0bb6ae8e        ubuntu              "/bin/bash"              7 days ago           Exited (255) 3 days ago                              networktest

查看当前运行中的Container,可以执行如下命令查看(下面的命令都是等价的):

docker psdocker container psdocker container ls

本文作者时延军,原文点击了解更多↓↓↓

感谢大家支持,多多转发关注不迷路~

标签: #centos72是什么系统 #centos65升级docker #centos65入门 #centos semanage #centos7anzhuandeb