Docker基础

一、安装docker

1、容器(Container)

所谓的容器,是一种基础工具,泛指任何可以用于容纳其他物品的工具,可以部分或完全封闭,被用于容纳、储存、运输物品;物体可以被放置在容器中,而容器则可以保护其内容物。

人类使用容器的历史至少有十万年,甚至数百万年。

容器的类型有:瓶、罐、箱、篮、桶、袋、柜、碗等等。

2docker介绍

docker是一种开源的容器引擎,可以让开发者打包应用以及依赖的库,然后发布到任何流行的Linux发行版上,移植很方便。

·docker由go语言编写,基于Apache2.0协议发布。

·基于Linux内核,要想在Windows中运行需要使用虚拟机来实现。

·从1.13开始,版本分docker-ee(商业版)、docker-ce(社区版)。

最新版为:18.06,18指的是2018年。

docker优势:

启动非常快,秒级实现;

资源利用率高,一台高配置服务器可以跑上千个docker容器;

更快的交付和部署,一次创建和配置后,可以在任意地方运行;

内核级别的虚拟化,不需要额外的hypervisor支持,会有更高的性能和效率;

易迁移,平台依赖性不强。

Docker与虚拟机的对比:

特性

容器

虚拟机

启动

秒级

分钟级

硬盘使用

一般为MB

一般为GB

性能

接近原生

弱于

系统支持量

单机支持上千个容器

一般为几十个

Docker与OpenStack对比:

类别

Docker

OpenStack

部署难度

相对简单

组件多,部署复杂

启动速度

秒级

分钟级

执行性能

和物理系统几乎一致

VM会占用一些资源

镜像体积

镜像是MB级别

虚拟机镜像GB级别

管理效率

管理简单

组件相互依赖,管理复杂

隔离性

隔离性高

彻底隔离

可管理性

单进程,不建议启动ssh

完整的系统管理

网络连接

比较弱

借助Neutron可以灵活组建各类网络架构

docker核心概念:

镜像:是一个只读的模版,类似于安装系统用到的那个iso文件,在docker中,通过镜像来完成各种应用的部署。

容器:镜像类似于操作系统,而容器类似于虚拟机本身。容器可以被启动、开始、停止、删除等操作,每个容器都是相互隔离的。

仓库:镜像的场所,仓库分为公开仓库和私有仓库。最大的公开仓库是Docker hub(hub.docker.com),国内公开仓库:dockerpool.com

实验环境:RHEL 7.5系统

2、下载docker-cerepo文件

清华大学镜像站:

https://mirrors.tuna.tsinghua.edu.cn/docker-ce/linux/centos/docker-ce.repo

阿里云镜像站:https://mirrors.aliyun.com/docker-ce/linux/centos/

将repo文件下载到/etc/yum.repos.d/

[root@lb01 ~]# cd /etc/yum.repos.d/
[root@lb01 yum.repos.d]# curl -O https://mirrors.tuna.tsinghua.edu.cn/docker-ce/linux/centos/docker-ce.repo

修改repo文件的url:

[root@lb01 yum.repos.d]# sed -i 's@https://download.docker.com/@https://mirrors.tuna.tsinghua.edu.cn/docker-ce/@g' docker-ce.repo
[root@lb01 yum.repos.d]# yum repolist

3、安装docker-ce

[root@lb01 yum.repos.d]# yum install docker-ce -y

4、查看各个版本

[root@lb01 ~]# yum list docker-ce --showduplicates
Loaded plugins: product-id, search-disabled-repos, subscription-manager
This system is not registered with an entitlement server. You can use subscription-manager to register.
Installed Packages
docker-ce.x86_64                     18.06.0.ce-3.el7                             @docker-ce-stable
Available Packages
docker-ce.x86_64                     17.03.0.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.2.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.06.0.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.2.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.09.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.12.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                     18.03.1.ce-1.el7.centos                      docker-ce-stable 
docker-ce.x86_64                     18.06.0.ce-3.el7                             docker-ce-stable 
docker-ce.x86_64                     18.06.1.ce-3.el7                             docker-ce-stable 
[root@lb01 ~]# 

5、安装指定版本的docker

比如:yum install -y docker-ce-17.06.0.ce 

二、docker加速器

创建/etc/docker/daemon.json文件

docker-ce配置文件:/etc/docker/daemon.json,默认不存在。


[root@lb01 ~]# mkdir /etc/docker -p

[root@lb01 ~]#vim /etc/docker/daemon.json

{

 "registry-mirrors": ["https://registry.docker-cn.com"]

}

或者:

{

 "registry-mirrors": ["https://registry.docker-cn.com","https://dhq9bx4f.mirror.aliyuncs.com"]

}

三、docker基础

1、启动docker

[root@lb01 ~]# systemctl start docker

2、查看docker版本

[root@lb01 ~]# docker version

Client:

 Version:           18.06.0-ce

 API version:       1.38

 Go version:        go1.10.3

 Git commit:        0ffa825

...

[root@lb01 ~]# docker info

Containers: 0

 Running: 0

 Paused: 0

 Stopped: 0

Images: 0

Server Version: 18.06.0-ce

Storage Driver: overlay2

 Backing Filesystem: xfs

 Supports d_type: true

...

3docker命令用法

Usage: docker [OPTIONS] COMMAND

新版的docker中COMMAND分为:Management Commands和Commands两种。

四、镜像管理

1、下载一个centos镜像

[root@lb01 ~]# docker pull centos

2、查看镜像

[root@lb01 ~]# docker image ls

REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE

centos              latest              5182e96772bf        2 weeks ago         200MB

[root@lb01 ~]#

3、查找镜像

docker search 镜像名

[root@lb01 ~]#docker search jumpserver

4、给镜像打标签

docker tag 镜像名 自定义的标签

[root@lb01 ~]# docker tag centos my_centos
[root@lb01 ~]# 

打完标签后查看一下:

[root@lb01 ~]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
centos              latest              5182e96772bf        3 weeks ago         200MB
my_centos           latest              5182e96772bf        3 weeks ago         200MB
[root@lb01 ~]# 

结果显示TAG都是一样的,可以在打标签的时候修改TAG:

[root@lb01 ~]# docker tag centos my_centos2:20180829
[root@lb01 ~]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
centos              latest              5182e96772bf        3 weeks ago         200MB
my_centos2          20180829            5182e96772bf        3 weeks ago         200MB
my_centos           latest              5182e96772bf        3 weeks ago         200MB
[root@lb01 ~]# docker tag centos my_centos2:8888
[root@lb01 ~]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
centos              latest              5182e96772bf        3 weeks ago         200MB
my_centos2          20180829            5182e96772bf        3 weeks ago         200MB
my_centos2          8888                5182e96772bf        3 weeks ago         200MB
my_centos           latest              5182e96772bf        3 weeks ago         200MB
[root@lb01 ~]# 

5、把镜像启动为容器

docker run -itd  镜像名

选项:-i:表示让容器的标准输入打开

-t:表示分配一个伪终端

-d:表示后台启动。

启动centos镜像:

[root@lb01 ~]# docker run -itd centos
9115663499d47ff55ce97f9af3ad27e76307e6f88dd7ac56595e6a089257118c
[root@lb01 ~]# 

6、查看运行的镜像

docker ps:查看

[root@lb01 ~]# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
9115663499d4        centos              "/bin/bash"         2 minutes ago       Up 2 minutes                            compassionate_boyd
[root@lb01 ~]# 

7、删除镜像

删除镜像的3个命令:

docker rmi 镜像名

docker rmi 镜像名:TAG

docker rmi IMAGE ID

最后一条命令是删除整个镜像。
例如:

[root@lb01 ~]# docker rmi my_centos
Untagged: my_centos:latest
[root@lb01 ~]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
my_centos2          20180829            5182e96772bf        3 weeks ago         200MB
my_centos2          8888                5182e96772bf        3 weeks ago         200MB
centos              latest              5182e96772bf        3 weeks ago         200MB
[root@lb01 ~]#

OK,my_centos删除成功。

docker rmi 镜像名:TAG

[root@lb01 ~]# docker rmi my_centos2:20180829
Untagged: my_centos2:20180829
[root@lb01 ~]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
centos              latest              5182e96772bf        3 weeks ago         200MB
my_centos2          8888                5182e96772bf        3 weeks ago         200MB
[root@lb01 ~]# 

8、停止容器

docker stop 容器id

例如:

[root@lb01 ~]# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
9115663499d4        centos              "/bin/bash"         15 minutes ago      Up 15 minutes                           compassionate_boyd
[root@lb01 ~]# docker stop 9115663499d4
9115663499d4
[root@lb01 ~]#

五、通过容器创建镜像

docker run启动容器后,可以使用“docker  exec -it 容器id  bash ”命令进入容器。

容器id可以使用docker ps查看。bash为进入容器后要执行的命令。

1、启动容器:

[root@lb01 ~]# docker run -itd centos
a7c0b6849212860c1e653b4eb46b9fa898848c9ea3b84750c9839a283834c51c
[root@lb01 ~]# 

2、进入容器:

[root@lb01 ~]# docker ps 
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
a7c0b6849212        centos              "/bin/bash"         40 seconds ago      Up 39 seconds                           goofy_stallman
[root@lb01 ~]# docker exec -it a7c0b68 bash
[root@a7c0b6849212 /]# 

OK,进入容器成功。进入容器后,可以运行Linux一些命令比如:

[root@a7c0b6849212 /]# ls
anaconda-post.log  bin  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
[root@a7c0b6849212 /]# 

可以安装一些软件,比如:

[root@a7c0b6849212 /]# yum install net-tools -y

3、退出容器

可以使用键盘组合键ctrl +d退出容器或者直接输入exit退出容器

4、保存变更过的容器

前面中,已经在容器里执行了安装net-tools,要想保存变更过的容器,可以使用以下命令:

docker commit -m "描述" -a "描述"  容器id  新的容器名

-m:描述,可以写一些变更的信息

-a:描述,可以指定作者相关信息

当然,-a可以省略

例如:

[root@a7c0b6849212 /]# exit
[root@lb01 ~]# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
a7c0b6849212        centos              "/bin/bash"         2 minutes ago       Up 2 minutes                            goofy_stallman
[root@lb01 ~]# docker commit -m "install net-tools" -a "haha" a7c0b6849212 centos_with_net-tools
sha256:ea181d22105023ce2fd8a0c60a69fafc52ce5011f5702c665b28f4c38ab169ce
[root@lb01 ~]# 

查看一下:

[root@lb01 ~]# docker images
REPOSITORY              TAG                 IMAGE ID            CREATED             SIZE
centos_with_net-tools   latest              ea181d221050        23 seconds ago      293MB
centos                  latest              5182e96772bf        3 weeks ago         200MB
[root@lb01 ~]# 

OK,成功。运行centos_with_net-tools并进入容器:

[root@lb01 ~]# docker run -it centos_with_net-tools
[root@c4d9dffc35ea /]# ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 172.17.0.3  netmask 255.255.0.0  broadcast 172.17.255.255
        ether 02:42:ac:11:00:03  txqueuelen 0  (Ethernet)
        RX packets 5  bytes 418 (418.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

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

[root@c4d9dffc35ea /]# 

不加-d选项表示直接在前台运行。

六、通过模版创建镜像

1、下载一个模版

模版下载地址:https://download.openvz.org/template/precreated/

这里下载centos-7-x86_64-minimal.tar.gz作演示。

[root@lb01 ~]# curl -O https://download.openvz.org/template/precreated/centos-7-x86_64-minimal.tar.gz

2、导入模版

导入命令:cat  模版  |  docker  import  -  镜像名称

[root@lb01 ~]# cat centos-7-x86_64-minimal.tar.gz | docker import - centos7
sha256:4bf52e8acd32a43e563ec372371ad9838fd29ab471ac1a16535737abede4521a
[root@lb01 ~]# 
[root@lb01 ~]# docker images
REPOSITORY              TAG                 IMAGE ID            CREATED              SIZE
centos7                 latest              4bf52e8acd32        About a minute ago   435MB
centos_with_net-tools   latest              ea181d221050        22 minutes ago       293MB
centos                  latest              5182e96772bf        3 weeks ago          200MB
[root@lb01 ~]# 

OK,导入成功。

3、导出镜像

docker save -o 导出的文件名  要导出的镜像

例如:

[root@lb01 ~]# docker save -o my-cetnos7.tar  centos7

4、恢复本地镜像

docker load --input 本地镜像文件

或者:

docke  load < 本地镜像文件

[root@lb01 ~]# docker load --input my-cetnos7.tar 
Loaded image: centos7:latest
[root@lb01 ~]# 

5、镜像推送

[root@lb01 ~]# docker push centos7
The push refers to repository [docker.io/library/centos7]
788edba9eaa8: Preparing 
denied: requested access to the resource is denied
[root@lb01 ~]# 

要推送镜像,得到dockerhub官网注册账号后可以推送。这里不演示。

七、容器管理

1、容器的创建与启动

创建容器:docker create -it 镜像名 bash,此命令可以创建容器,但没有启动

启动容器:docker  start  容器的id

stop、restart:停止、重启

之前我们使用的docker  run命令,相当于先create再start。比如:

[root@lb01 ~]# docker run -it centos bash
[root@0fc31010e468 /]# 

直接可以进入容器了。要想退出可以使用exit命令或者ctrl+d组合键,退出后容器也就停止了。

2、后台运行容器

要想让容器在后台运行,则可以使用-d选项,比如:

[root@lb01 ~]# docker run -d centos bash
d45309095f0622d042cad7bc932e94c0d2f712071229c91efd347e6f9ac4c3f1
[root@lb01 ~]# 

3、停止容器

docker  stop 容器id,比如:

[root@lb01 ~]# docker stop d45309095f0

4、其他选项

--name:自定义容器名

[root@lb01 ~]# docker run --name myhaha -itd centos bash
59c267dc3e13f1b14280d37f81970af7cf9d32d4956f71fd55443c40d0f90394
[root@lb01 ~]# 

--rm:容器退出后直接删除

[root@lb01 ~]# docker run --rm -itd centos bash  -c "sleep 5"
7702b547895fdc20b7aeade9132a16e90903d16c741bfcd0e96049df4e6f686a
[root@lb01 ~]# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
[root@lb01 ~]# 

5、获取容器的历史信息

docker logs  容器id

[root@lb01 ~]# docker run -itd centos bash -c "echo 123"
def3015a7989640bc593006b1979ecd86f47083f98a1ee06c03065c5a898279b
[root@lb01 ~]# docker logs def3015a7989
123
[root@lb01 ~]# 

6、进入后台运行的容器

[root@lb01 ~]# docker run --name  haha -itd centos
785f399399fb75fd02976facfb91a3905bd3391ebee5d1f38e7865cca06f0124
[root@lb01 ~]# docker attach haha 
[root@785f399399fb /]# 

此方法不太好,因为退出之后,容器也退出了。所以建议使用exec选项:

[root@lb01 ~]# docker run -itd centos bash
aca1293cc88e97d590ee133d8a9bd7cf74f0725a3a6b86f0470578b899e11d76
[root@lb01 ~]# docker exec -it aca1293cc88e97d bash
[root@aca1293cc88e /]# 

7、删除容器

docker  rm  -f  容器id,-f强制删除

[root@lb01 ~]# 
[root@lb01 ~]# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED              STATUS              PORTS               NAMES
aca1293cc88e        centos              "bash"              About a minute ago   Up About a minute                       vigorous_colden
[root@lb01 ~]# docker rm -f aca1293cc88e
aca1293cc88e
[root@lb01 ~]# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
[root@lb01 ~]# 

8、容器的导出与导入

导出:

docker export 容器id > 文件名.tar

例如:

[root@lb01 ~]# docker run -itd centos bash
fdaa98ae30d85ac18fa0b168a4824c3f4e208e5e53974e60fcc0543a5f6e7dd6
[root@lb01 ~]# docker export fdaa98ae30d85a > mycentos.tar
[root@lb01 ~]# 

导入:cat 文件名 | docker import  -  自定义的容器名

[root@lb01 ~]# cat mycentos.tar | docker import - test
sha256:5ccd383c250d1d64632fe8ee9005ef17efa8a21ef06ca7382bb77f8c391ac346
[root@lb01 ~]# 

八、仓库管理

1、下载镜像

docker  pull  镜像名

使用registry搭建本地私有仓库。

[root@lb01 ~]# docker pull registry
Using default tag: latest
latest: Pulling from library/registry
4064ffdc82fe: Pull complete 
c12c92d1c5a2: Pull complete 
4fbc9b6835cc: Pull complete 
765973b0f65f: Pull complete 
3968771a7c3a: Pull complete 
Digest: sha256:51bb55f23ef7e25ac9b8313b139a8dd45baa832943c8ad8f7da2ddad6355b3c8
Status: Downloaded newer image for registry:latest
[root@lb01 ~]# 

2、启动registry

[root@lb01 ~]# docker run -d -p 5000:5000 registry
49710c759f531f342f490f422a6a72d60e6758a8fd95b95e4c477bc83ed5feea
[root@lb01 ~]# 

-p:端口映射,宿主机的端口:容器监听的端口。

[root@lb01 ~]# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                    NAMES
49710c759f53        registry            "/entrypoint.sh /etc…"   5 minutes ago       Up 5 minutes        0.0.0.0:5000->5000/tcp   determined_lichterman
[root@lb01 ~]# 

3、访问

[root@lb01 ~]# curl 127.0.0.1:5000/v2/_catalog
{"repositories":[]}
[root@lb01 ~]# 

仓库是新建的,为空。

4、把镜像传到仓库。

先把要上传的镜像打标签:

[root@lb01 ~]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
centos              latest              5182e96772bf        3 weeks ago         200MB
registry            latest              b2b03e9146e1        8 weeks ago         33.3MB
[root@lb01 ~]# docker tag centos 192.168.10.101:5000/centos7
[root@lb01 ~]# 
[root@lb01 ~]# 
[root@lb01 ~]# docker images
REPOSITORY                    TAG                 IMAGE ID            CREATED             SIZE
centos                        latest              5182e96772bf        3 weeks ago         200MB
192.168.10.101:5000/centos7   latest              5182e96772bf        3 weeks ago         200MB
registry                      latest              b2b03e9146e1        8 weeks ago         33.3MB
[root@lb01 ~]#

上传:

[root@lb01 ~]# docker push 192.168.10.101:5000/centos7
The push refers to repository [192.168.10.101:5000/centos7]
Get https://192.168.10.101:5000/v2/: http: server gave HTTP response to HTTPS client
[root@lb01 ~]# 

报错,修改配置文件/etc/docker/daemon.json ,添加私有仓库地址:"insecure-registries": ["192.168.10.101:5000"]

[root@lb01 ~]# vim /etc/docker/daemon.json 
{
 "registry-mirrors": ["https://registry.docker-cn.com","https://dhq9bx4f.mirror.aliyuncs.com"],
 "insecure-registries": ["192.168.10.101:5000"]
}

重启docker:

[root@lb01 ~]# systemctl restart docker

启动容器,重新推送:

因为前面重启了docker,所以容器会停止,必须启动容器才能推送。

[root@lb01 ~]# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                      PORTS               NAMES
49710c759f53        registry            "/entrypoint.sh /etc…"   30 minutes ago      Exited (2) 14 minutes ago                       determined_lichterman
[root@lb01 ~]# docker start 49710c759f53
49710c759f53
[root@lb01 ~]# docker push 192.168.10.101:5000/centos7
The push refers to repository [192.168.10.101:5000/centos7]
1d31b5806ba4: Pushed 
latest: digest: sha256:fc2476ccae2a5186313f2d1dadb4a969d6d2d4c6b23fa98b6c7b0a1faad67685 size: 529
[root@lb01 ~]# 

查看一下:

[root@lb01 ~]# curl 127.0.0.1:5000/v2/_catalog
{"repositories":["centos7"]}
[root@lb01 ~]# 

OK,推送成功。

推送一个ubuntu:

[root@lb01 ~]# docker run -d ubuntu
Unable to find image 'ubuntu:latest' locally
latest: Pulling from library/ubuntu
124c757242f8: Pull complete 
2ebc019eb4e2: Pull complete 
dac0825f7ffb: Pull complete 
82b0bb65d1bf: Pull complete 
ef3b655c7f88: Pull complete 
Digest: sha256:72f832c6184b55569be1cd9043e4a80055d55873417ea792d989441f207dd2c7
Status: Downloaded newer image for ubuntu:latest
010382d2103d252cf1e1155153aa9ecbcc01b975b1baa7bb93400eee5d4ff30c
[root@lb01 ~]# docker tag ubuntu 192.168.10.101:5000/ubuntu
[root@lb01 ~]# docker images
REPOSITORY                    TAG                 IMAGE ID            CREATED             SIZE
192.168.10.101:5000/ubuntu    latest              16508e5c265d        10 days ago         84.1MB
ubuntu                        latest              16508e5c265d        10 days ago         84.1MB
192.168.10.101:5000/centos7   latest              5182e96772bf        3 weeks ago         200MB
centos                        latest              5182e96772bf        3 weeks ago         200MB
registry                      latest              b2b03e9146e1        8 weeks ago         33.3MB
[root@lb01 ~]# docker push 192.168.10.101:5000/ubuntu 
The push refers to repository [192.168.10.101:5000/ubuntu]
ec8257ff6a7a: Pushed 
7422efa72a14: Pushed 
b6a02001ba33: Pushed 
a26724645421: Pushed 
a30b835850bf: Pushed 
latest: digest: sha256:ac533e4ead4110211a4d67cbf44ed8b7d1aca2b8e6f15d1e8768eadaf433dd31 size: 1357
[root@lb01 ~]# 

查看一下:

[root@lb01 ~]# curl 127.0.0.1:5000/v2/_catalog
{"repositories":["centos7","ubuntu"]}
[root@lb01 ~]# 

私有仓库创建成功。

5、下载私有仓库的镜像

[root@lb01 ~]# docker pull 192.168.10.101:5000/ubuntu
Using default tag: latest
latest: Pulling from ubuntu
Digest: sha256:ac533e4ead4110211a4d67cbf44ed8b7d1aca2b8e6f15d1e8768eadaf433dd31
Status: Image is up to date for 192.168.10.101:5000/ubuntu:latest
[root@lb01 ~]# 

九、数据管理

在容器里的数据,一旦容器停止或者删除,则数据就丢失了,因此可以挂载宿主机的目录到容器里面,这样就可以把容器的数据保存在宿主机了。

1、挂载本地目录到容器里

[root@lb01 ~]# mkdir /data
[root@lb01 ~]# touch haha > /data/1.txt
[root@lb01 ~]# docker run -tid -v /data/:/mydata centos bash
6f012a696f55044db07281df2bf58b31933c2e218ba86743b12b82d8eaae7400
[root@lb01 ~]# 

-v:指定挂载目录,:前面的是宿主机本地目录,:后面的是容器的目录,会自动创建,无需事先创建。

进入容器,查看一下:

[root@lb01 ~]# docker exec -it 6f012a696f55044d bash
[root@6f012a696f55 /]# ls
anaconda-post.log  dev  home  lib64  mnt     opt   root  sbin  sys  usr
bin                etc  lib   media  mydata  proc  run   srv   tmp  var
[root@6f012a696f55 /]# ls /mydata/
1.txt
[root@6f012a696f55 /]# 
[root@6f012a696f55 /]# mkdir /mydata/haha

挂载成功。

本地查看:

[root@lb01 ~]# ll /data/
total 0
-rw-r--r-- 1 root root 0 Sep  2 20:48 1.txt
drwxr-xr-x 2 root root 6 Sep  2 20:54 haha
[root@lb01 ~]# 

2、挂载数据卷

挂载目录的时候,可以指定容器的name,如果不指定则会随机定义。可以使用docker ps查看,即最右侧一列。

[root@lb01 ~]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS          
6f012a696f55        centos              "bash"                   3 minutes ago       Up 3 minutes                       
49710c759f53        registry            "/entrypoint.sh /etc…"   About an hour ago   Up 28 minutes       0.0.0.0:5000->5
[root@lb01 ~]#  

挂载数据卷:

[root@lb01 ~]# docker run -itd --volumes-from clever_haibt centos bash
deccddfea62a7fde58a1f372746107aa99342b0c024a88dfdcd1d1b0c4595c69
[root@lb01 ~]# 

进入容器:

[root@lb01 ~]# docker exec -it deccddfea62a bash
[root@deccddfea62a /]# ls /mydata/
1.txt  haha
[root@deccddfea62a /]# 

这样使用centos镜像创建了新的容器,并且使用clever_haibt容器的数据卷

3、定义数据卷容器

有时候需要多个容器之间相互共享数据,类似于Linux的nfs,所以可以搭建一个专门的数据卷容器,然后其他容器之间挂载该数据卷,

(1)建立数据卷容器

[root@lb01 ~]# docker run -itd -v /mydata/ --name testvol centos bash
54ab6e37e1f49fa50c805a031655f14d76b9564cbc3aa8e288588ca11b17b835
[root@lb01 ~]# 

注意:这里的/mydata是容器里的目录,并非宿主机本地的目录。

(2)其他容器挂载此数据卷

[root@lb01 ~]# docker run -itd --volumes-from testvol centos bash
3139554287b1b5f1aab00f842a808906c3747eb395de9368d2da47c3b8ab6936
[root@lb01 ~]# 

十、数据卷备份恢复

1、备份:

(1)宿主机创建一个备份目录

[root@lb01 ~]# mkdir /vol_data_backup
[root@lb01 ~]# 

(2)创建一个容器

首先是要testvol数据卷新开一个容器,同时还需把宿主机本地的/vol_data_backup目录挂载到该容器的/backup目录中,然后再把/home目录的文件打包成data.tar文件放到/backup目录中。

[root@lb01 ~]# docker run --volumes-from testvol -v /vol_data_backup:/backup centos tar cvf /backup/data.tar /home/
tar: Removing leading `/' from member names
/home/
[root@lb01 ~]# ls /vol_data_backup/
data.tar
[root@lb01 ~]# 

2、恢复

先新建一个数据卷容器,再建一个新的容器并挂载该数据卷容器,然后把tar包解包。

创建新的数据卷容器(创建的数据卷目录名称必须和备份的数据卷名称一致):

[root@lb01 ~]# docker run -itd -v /backup --name testvol2 centos bash
7e714ebf30d4762081de63b03e7322ddbe0be83ec94049ea3e62c89b199e0c73
[root@lb01 ~]#  

挂载数据卷新建容器,并解包:

[root@lb01 ~]#  docker run -it --volumes-from testvol2 -v /vol_data_backup/:/backup  centos bash
[root@7228517f780c /]# ls
anaconda-post.log  backup  bin  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
[root@7228517f780c /]# mkdir haha
[root@7228517f780c /]# tar xf backup/data.tar -C haha/
[root@7228517f780c /]# ls haha/
home
[root@7228517f780c /]# 

十一、docker网络模式

docker网络模式有host、none、container、bridge模式。

·host模式,使用docker run时使用--net=host可以指定。docker使用的网络实际上和宿主机的一样,在容器内看到的网卡ip是宿主机的ip。

·container模式,设置:--net=container:容器id/容器名,多个容器使用共同的网络,看到的ip是一样的

·none模式,设置:--net=none,此模式下,不会配置任何网络

bridge模式,设置:--net=bridge。不指定模式,默认情况下就使用bridge模式。此模式会为每个容器分配一个独立的Network Namespace。类似于vmware的nat网络模式。同一个宿主机上的所有容器会在同一个网段下,相互之间可以通信。

1、外面网络访问容器

(1)新建一个容器。使用默认网络模式。

[root@lb01 ~]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
centos              latest              5182e96772bf        4 weeks ago         200MB
registry            latest              b2b03e9146e1        2 months ago        33.3MB
[root@lb01 ~]# docker run -itd 5182e96772bf bash
WARNING: IPv4 forwarding is disabled. Networking will not work.
0188a583b930bfe00d42d65e3c13c343c4bb14b906321f824d59ec420f9bb4c5
[root@lb01 ~]# 

警告:IPv4转发没打开。解决方法:

在/usr/lib/sysctl.d/50-default.conf文件中添加一行:net.ipv4.ip_forward = 1

[root@lb01 ~]# vim /usr/lib/sysctl.d/50-default.conf 
net.ipv4.ip_forward = 1
[root@lb01 ~]# sysctl -p
[root@lb01 ~]# systemctl restart network
[root@lb01 ~]# systemctl restart docker 

重新运行一个容器:

[root@lb01 ~]# docker run -itd centos bash
0659ac5d67273f0ee64aedf6cc8d434e5e2131fe83281a6e8d2a7aa53bd24d94
[root@lb01 ~]#

(2)进入容器,安装nginx服务

[root@lb01 ~]# docker exec -it 0659ac5d67273 bash
[root@0659ac5d6727 /]# yum install -y epel-release
[root@0659ac5d6727 /]# yum install -y nginx

(3)退出容器,把容器导出为镜像

[root@0659ac5d6727 /]# exit
exit
[root@lb01 ~]# docker commit -m "install nginx"  -a "haha" 0659ac5d6727 centos_with_nginx
sha256:30371a3263a70f64ef47f0e464cdd333227ae7d956c8dca3f83c77d33a1c178f
[root@lb01 ~]# 

查看一下:

[root@lb01 ~]# docker images 
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
centos_with_nginx   latest              30371a3263a7        23 seconds ago      408MB
centos              latest              5182e96772bf        4 weeks ago         200MB
registry            latest              b2b03e9146e1        2 months ago        33.3MB
[root@lb01 ~]# 

成功。

(4)使用刚才导出的镜像创建容器,并做端口映射

将宿主机的8088端口映射到容器的80端口。

[root@lb01 ~]# docker run -itd -p 8088:80 centos_with_nginx bash
cc4823f4e7756f7c922a5b43475ef04e02ceaf9300b1dde7832478fb77de0f74
[root@lb01 ~]# 

十二、operation not permitted

新建的容器,启动nginx或httpd服务时会报错,如下所示:

[root@lb01 ~]# docker run -itd -p 8088:80 centos_with_nginx bash
cc4823f4e7756f7c922a5b43475ef04e02ceaf9300b1dde7832478fb77de0f74
[root@lb01 ~]# docker exec -it cc4823f4e7756f7c9 bash
[root@cc4823f4e775 /]# systemctl start nginx
Failed to get D-Bus connection: Operation not permitted
[root@cc4823f4e775 /]# 

报错:Failed to get D-Bus connection: Operation not permitted。

这是因为dbus-daemon没有启动。解法方法:启动容器时加上:--privileged -e "container=docker",并且最后的命令bash改为/usr/sbin/init

例如:

把上面创建的容器(cc4823f4e7756f7c9 )删除之后再创建新的容器。

[root@lb01 ~]# docker rm -f cc4823f4e7756f7c9
[root@lb01 ~]# docker run -itd --privileged -e "container=docker"  -p 8088:80 centos_with_nginx /usr/sbin/init
f35e60d5b9d5525fc001007639cd610c32d3871db7014d70ad2ba3a6bcff88f6
[root@lb01 ~]# 

进入容器,启动nginx:

[root@lb01 ~]# docker exec -it f35e60d5b9d552 bash
[root@f35e60d5b9d5 /]# systemctl start nginx
[root@f35e60d5b9d5 /]# 

OK,nginx启动成功。

十三、配置桥连网络

为了使用本地网络中的机器和docker容器更方便的通信,通常会有将docker容器配置到和主机同一网段的需求。

只要将docker容器和宿主机的网卡桥连起来,再给docker容器配置ip即可。

1、宿主机网络配置

修改ens33的配置文件,配置br0文件。

[root@lb01 ~]# cd /etc/sysconfig/network-scripts/
[root@lb01 network-scripts]# cp ifcfg-ens33 ifcfg-br0
[root@lb01 network-scripts]# 

ens33配置文件:

[root@lb01 network-scripts]# vim ifcfg-ens33
TYPE=Ethernet
BOOTPROTO=none
NAME=ens33
DEVICE=ens33
ONBOOT=yes
BRIDGE=br0

br0配置文件:

注意:TYPE=Bridge

[root@lb01 network-scripts]# vim ifcfg-br0
TYPE=Bridge
BOOTPROTO=none
NAME=br0
DEVICE=br0
ONBOOT=yes
IPADDR=192.168.10.101
PREFIX=24
GATEWAY=192.168.10.2
DNS1=119.29.29.29
DNS2=182.254.116.116

重启网络:

[root@lb01 network-scripts]# systemctl restart network

查看网络:

[root@lb01 ~]# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast master br0 state UP group default qlen 1000
    link/ether 00:0c:29:65:26:e7 brd ff:ff:ff:ff:ff:ff
3: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default 
    link/ether 02:42:df:dc:cc:a6 brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
       valid_lft forever preferred_lft forever
5: br0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default qlen 1000
    link/ether 00:0c:29:65:26:e7 brd ff:ff:ff:ff:ff:ff
    inet 192.168.10.101/24 brd 192.168.10.255 scope global noprefixroute br0
       valid_lft forever preferred_lft forever
    inet6 fe80::20c:29ff:fe65:26e7/64 scope link 
       valid_lft forever preferred_lft forever
[root@lb01 ~]#

OK,网络配置成功。

2、安装pipework

安装git

[root@lb01 ~]# yum install git -y

使用git下载pipework

[root@lb01 ~]# git clone https://github.com/jpetazzo/pipework
Cloning into 'pipework'...
remote: Counting objects: 501, done.
remote: Total 501 (delta 0), reused 0 (delta 0), pack-reused 501
Receiving objects: 100% (501/501), 172.97 KiB | 70.00 KiB/s, done.
Resolving deltas: 100% (264/264), done.
[root@lb01 ~]# 

将pipework命令放到/usr/local/bin目录中

[root@lb01 ~]# cd pipework/
[root@lb01 pipework]# cp pipework /usr/local/bin/
[root@lb01 pipework]# 

3、使用centos_with_nginx镜像创建一个none模式的容器

[root@lb01 ~]# docker run -itd --net=none centos_with_nginx bash
459f59a8619730461b9fa8e4748bb59e0510340ae076e28ab204224a26f08a32
[root@lb01 ~]#

4、使用pipework命令设置网络

第3步中创建的容器使用none模式,没有网络,所以使用pipework创建桥连,用法:

pipework    桥连网卡名     容器id     自定义ip/掩码@网关

如下:

[root@lb01 ~]# pipework br0 459f59a861973046 192.168.10.88/24@192.168.10.2
[root@lb01 ~]# 

进入容器查看网络信息:

[root@lb01 ~]# docker exec -it 459f59a861973046 bash
[root@459f59a86197 /]# ifconfig
bash: ifconfig: command not found
[root@459f59a86197 /]# yum install net-tools -y
[root@459f59a86197 /]# 
[root@459f59a86197 /]# ifconfig
eth1: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.10.88  netmask 255.255.255.0  broadcast 192.168.10.255
        ether 52:c3:e8:d1:f2:4e  txqueuelen 1000  (Ethernet)
        RX packets 181  bytes 325541 (317.9 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 184  bytes 11175 (10.9 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

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

[root@459f59a86197 /]# 

OK,ip已经设置上了。

看看可不可以连外网:

[root@459f59a86197 /]# ping www.baidu.com
PING www.a.shifen.com (14.215.177.39) 56(84) bytes of data.
64 bytes from 14.215.177.39 (14.215.177.39): icmp_seq=1 ttl=128 time=14.7 ms
64 bytes from 14.215.177.39 (14.215.177.39): icmp_seq=2 ttl=128 time=13.7 ms

OK,能ping通百度。

十四、dockerfile

dockerfile的格式

1、FROM  //指定基于哪个基础镜像

格式:FROM  镜像,或者,FROM  镜像:标签

如:FROM centos、FROM centos:latest

2、MAITAINER  //指定作者的信息

比如:MAITAINER haha  haha@haha,com

3、RUN  //镜像操作指令

格式:RUN 命令,或者,RUN  ["executable","param1","param2"],比如:

RUN yum install httpd -y

RUN ["/bin/bash","-c","echo hello"]

4、CMD //跟RUN很像

3种格式:

CMD  ["executable","param1","param2"]

CMD command  param1  param2

CMD ["param1","param2"]

CMD用了指定容器启动时用到的命令,只能有一条。比如:

CMD ["/bin/bash","/usr/local/nginx/sbin/nginx","-c","/usr/local/nginx/conf/nginx.conf"]

5、EXPOSE

格式:EXPOSE <port> [<port>...],比如

EXPORT 22 80 3306

用了指定要映射出去的端口。启动容器时使用-P则自动分配端口,-p则手动设置端口映射。

6、ENV  //定义变量

格式:ENV <key><value>

比如:ENV PATH /usr/local/mysql/bin:$PATH

主要是为后续的RUN指令提供一个环境变量。当然也可以自定义变量。比如

ENV MYSQL_version 5.6

7、ADD 拷贝文件或目录到某个目录

格式:ADD <src><dest>

其中src支持url。

8、COPY

格式与ADD一样,但不同的是,不支持url

9、ENTRYPOINT

格式类似CMD,容器启动时要执行的命令,与CMD很像,也是只有一条生效。如果写多条,只有最后一条生效。和CMD不同的是:

CMD可以被docker run指定覆盖,而ENTRYPOINT不能覆盖。比如,容器名为mycentos,在Dockerfile中定义CMD如下:

CMD ["/bin/echo","test"]

启动容器的命令:docker run mycentos 这会输出test。

如果使用:docker  run -it mycentos /bin/bash 什么都不会输出。

ENTRYPOINT不会被覆盖,而且比CMD或者docker run指定的命令要靠前执行。

ENTRYPOINT ["echo","test"]

docker run -it mycentos 123,则会输出test  123,这相当于执行命令echo test 123

10、VOLUME 指定挂载点

格式:VOLUME ["/目录"]

创建一个可以从本地主机或其他容器挂载的挂载点

11、USER

格式:USER daemon

指定运行容器的用户,很少用,一般都是root用户运行容器。

12、WORKDIR

格式:WORKDIR 目录

为后续的RUN、CMD或者ENTRYPOINT指定工作的目录

十五、Dockerfile示例(安装nginx)

1、在写Dockerfile之前先准备好nginx的配置文件

主配置文件:nginx.conf,虚拟主机配置文件:server.conf

nginx.conf文件内容:

user  nginx  nginx;
worker_processes  1;
worker_rlimit_nofile 65535;
error_log  /var/log/nginx/error.log notice;
events {
    use epoll;
    worker_connections  65535;
}
http {
    include mime.types;
    default_type application/octet-stream;
    server_names_hash_bucket_size 3526;
    server_names_hash_max_size 4096;
    log_format combined_realip '$remote_addr $http_x_forwarded_for [$time_local]'
    ' $host "$request_uri" $status'
    ' "$http_referer" "$http_user_agent"';
    sendfile on;
    tcp_nopush on;
    keepalive_timeout 30;
    client_header_timeout 3m;
    client_body_timeout 3m;
    send_timeout 3m;
    connection_pool_size 256;
    client_header_buffer_size 1k;
    large_client_header_buffers 8 4k;
    request_pool_size 4k;
    output_buffers 4 32k;
    postpone_output 1460;
    client_max_body_size 10m;
    client_body_buffer_size 256k;
    client_body_temp_path /usr/local/nginx/client_body_temp;
    proxy_temp_path /usr/local/nginx/proxy_temp;
    fastcgi_temp_path /usr/local/nginx/fastcgi_temp;
    fastcgi_intercept_errors on;
    tcp_nodelay on;
    gzip on;
    gzip_min_length 1k;
    gzip_buffers 4 8k;
    gzip_comp_level 5;
    gzip_http_version 1.1;
    gzip_types text/plain application/x-javascript text/css text/htm 
    application/xml;
    

    include /usr/local/nginx/conf.d/*.conf;

}

server.conf文件内容:

server {
listen       80;
server_name  localhost;
location / {
    root   /usr/local/nginx/html;
    index  index.php index.html index.htm;
}
error_page   500 502 503 504  /50x.html;
location = /50x.html {
    root   /usr/local/nginx/html;
}

#location ~ \.php$ {
#    root           /usr/local/nginx/html;
#    fastcgi_pass   127.0.0.1:9000;
#    fastcgi_index  index.php;
#    fastcgi_param  SCRIPT_FILENAME   /usr/local/nginx/html$fastcgi_script_name;
#    include        fastcgi_params;
#}

}

2、创建Dockerfile文件

Dockerfile、nginx.conf、server.conf三个文件都放在/root目录中。

[root@lb01 ~]# vim Dockerfile
###  Set the base image to CentOS
FROM centos

#File Author / Maintainer
MAINTAINER caomuzhong www.logmm.com

#Install necessary tools
RUN yum install -y gcc gcc-c++ pcre-devel openssl-devel libxml2-devel openssl libcurl-devel make zlib zlib-devel gd-devel

#Install Nginx
RUN useradd -r -s /sbin/nologin nginx
RUN mkdir -p /usr/local/nginx/
RUN mkdir -p /var/log/nginx
RUN chown nginx.nginx /var/log/nginx
RUN touch /var/log/nginx/error.log
RUN chown nginx.nginx /var/log/nginx/error.log
ADD http://nginx.org/download/nginx-1.14.0.tar.gz .
RUN tar xzvf nginx-1.14.0.tar.gz
RUN cd nginx-1.14.0 && ./configure --prefix=/usr/local/nginx     --user=nginx     --group=nginx     --http-log-path=/mydata/logs/nginx/access.log     --error-log-path=/mydata/logs/nginx/error.log     --with-http_ssl_module     --with-http_realip_module     --with-http_flv_module     --with-http_mp4_module     --with-http_gunzip_module     --with-http_gzip_static_module     --with-http_image_filter_module     --with-http_stub_status_module &&  make && make install
RUN rm -f /usr/local/nginx/conf/nginx.conf
RUN mkdir /usr/local/nginx/conf.d/
COPY nginx.conf  /usr/local/nginx/conf/nginx.conf
COPY server.conf /usr/local/nginx/conf.d/

#Expose ports
EXPOSE 80

#Set the default command to execute when creating a new container
ENTRYPOINT /usr/local/nginx/sbin/nginx && tail -f /etc/passwd

3、创建镜像

[root@lb01 ~]# docker build -t centos_nginx .
Sending build context to Docker daemon  910.7MB
...
Successfully built f3f68e71836d
Successfully tagged centos_nginx:latest
[root@lb01 ~]# 

查看镜像:

[root@lb01 ~]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
centos_nginx        latest              f3f68e71836d        22 seconds ago      499MB
centos_with_nginx   latest              30371a3263a7        24 hours ago        408MB
centos              latest              5182e96772bf        4 weeks ago         200MB
registry            latest              b2b03e9146e1        2 months ago        33.3MB
[root@lb01 ~]# 

OK,镜像创建成功。

4、启动容器

启动容器,进入查看nginx:

[root@lb01 ~]# docker run -itd -p 81:80 centos_nginx bash
e03a016801683c686e669587523f77d14aa32e9ba6bac851146fe01dc4faa0e6
[root@lb01 ~]# docker exec -it e03a016801 bash
[root@e03a01680168 /]# ps aux | grep nginx
root          1  0.0  0.0  11680  1352 pts/0    Ss+  14:45   0:00 /bin/sh -c /usr/local/nginx/sbinnginx && tail -f /etc/passwd bash
root          7  0.0  0.0  72928  1316 ?        Ss   14:45   0:00 nginx: master process /usr/localnginx/sbin/nginx
nginx         9  0.0  1.4 100064 28616 ?        S    14:45   0:00 nginx: worker process
root         24  0.0  0.0   9088   660 pts/1    S+   14:45   0:00 grep --color=auto nginx
[root@e03a01680168 /]# 

OK,成功。宿主机的81端口映射到容器的80端口。

宿主机ip:192.168.10.101,浏览器打开:192.168.10.101:81

5570b1c92b6e34d4ec82a7f9f2ea2da7f72.jpg

十六、使用docker compose部署服务

docker compose可以方便我们快捷高效地管理容器的启动、停止、重启等操作,它类似于Linux的shell脚本,基于yaml语法,在该文件里可以描述应用的框架,比如用什么镜像、数据卷、网络模式、监听端口等信息。

我们可以在一个compose文件中定义一个多容器的应用,然后通过该compose来启动这个应用。

1、下载docker-compose

安装方法:https://docs.docker.com/compose/install/#install-compose

下载地址:https://github.com/docker/compose/releases

[root@lb01 ~]# curl -L https://github.com/docker/compose/releases/download/1.22.0/docker-compose-$(uname -s)-$(uname -m) -o /usr/local/bin/docker-compose

2、添加可执行权限

[root@lb01 ~]# chmod +x /usr/local/bin/docker-compose

3、查看docker-compose版本信息

[root@lb01 ~]# docker-compose version
docker-compose version 1.22.0, build f46880fe
docker-py version: 3.4.1
CPython version: 3.6.6
OpenSSL version: OpenSSL 1.1.0f  25 May 2017
[root@lb01 ~]# 

十七、docker compose示例

查看一下有哪些镜像:

[root@lb01 ~]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
centos_nginx        latest              f3f68e71836d        31 minutes ago      499MB
centos_with_nginx   latest              30371a3263a7        25 hours ago        408MB
centos              latest              5182e96772bf        4 weeks ago         200MB
registry            latest              b2b03e9146e1        2 months ago        33.3MB
[root@lb01 ~]#

1、创建compose文件

这里使用centos_nginx、centos两个镜像创建一个compose文件:

[root@lb01 ~]# vim docker-compose.yml
version: "2"
services:
  app1:
     image: centos_nginx
     ports:
       - "82:80"
     networks:
       - "net1"
     volumes:
       - /app1/:/app1
  app2:
     image: centos
     networks:
       - "net2"
     volumes:
       - /app2/:/app2
     entrypoint: tail -f /etc/passwd
networks:
  net1:
     driver: bridge
  net2:
     driver: bridge

注意缩进。

2、运行:

[root@lb01 ~]# docker-compose up -d 
Creating network "root_net1" with driver "bridge"
Creating network "root_net2" with driver "bridge"
Creating root_app1_1 ... done
Creating root_app2_1 ... done
[root@lb01 ~]# 

查看一下容器运行情况:

[root@lb01 ~]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                NAMES
1119eba47792        centos              "tail -f /etc/passwd"    50 seconds ago      Up 49 seconds                            root_app2_1
5651b4fc7d0d        centos_nginx        "/bin/sh -c '/usr/lo…"   50 seconds ago      Up 49 seconds       0.0.0.0:82->80/tcp   root_app1_1
e03a01680168        centos_nginx        "/bin/sh -c '/usr/lo…"   39 minutes ago      Up 39 minutes       0.0.0.0:81->80/tcp   sleepy_goldberg
[root@lb01 ~]# 

app1、app2均已运行。

3、停止

[root@lb01 ~]# docker-compose stop
Stopping root_app2_1 ... done
Stopping root_app1_1 ... done
[root@lb01 ~]#

4、帮助信息

直接执行docker-compose命令,可以查看相关帮助信息

[root@lb01 ~]# docker-compose
Define and run multi-container applications with Docker.

Usage:
  docker-compose [-f <arg>...] [options] [COMMAND] [ARGS...]
  docker-compose -h|--help

Options:
  -f, --file FILE             Specify an alternate compose file
                              (default: docker-compose.yml)
  -p, --project-name NAME     Specify an alternate project name
                              (default: directory name)
  --verbose                   Show more output
  --log-level LEVEL           Set log level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
  --no-ansi                   Do not print ANSI control characters
  -v, --version               Print version and exit
  -H, --host HOST             Daemon socket to connect to

  --tls                       Use TLS; implied by --tlsverify
  --tlscacert CA_PATH         Trust certs signed only by this CA
  --tlscert CLIENT_CERT_PATH  Path to TLS certificate file
  --tlskey TLS_KEY_PATH       Path to TLS key file
  --tlsverify                 Use TLS and verify the remote
  --skip-hostname-check       Don't check the daemon's hostname against the
                              name specified in the client certificate
  --project-directory PATH    Specify an alternate working directory
                              (default: the path of the Compose file)
  --compatibility             If set, Compose will attempt to convert deploy
                              keys in v3 files to their non-Swarm equivalent

Commands:
  build              Build or rebuild services
  bundle             Generate a Docker bundle from the Compose file
  config             Validate and view the Compose file
  create             Create services
  down               Stop and remove containers, networks, images, and volumes
  events             Receive real time events from containers
  exec               Execute a command in a running container
  help               Get help on a command
  images             List images
  kill               Kill containers
  logs               View output from containers
  pause              Pause services
  port               Print the public port for a port binding
  ps                 List containers
  pull               Pull service images
  push               Push service images
  restart            Restart services
  rm                 Remove stopped containers
  run                Run a one-off command
  scale              Set number of containers for a service
  start              Start services
  stop               Stop services
  top                Display the running processes
  unpause            Unpause services
  up                 Create and start containers
  version            Show the Docker-Compose version information

docker-compose语法文档:http://www.web3.xin/index/article/182.html

十八、Harbor安装使用

Harbor是一个用于存储和分发Docker镜像的企业级Registry服务器。

镜像的存储harbor使用的是官方的docker registry(v2命名是distribution)服务去完成。harbor在docker distribution的基础上增加了一些安全、访问控制、管理的功能以满足企业对于镜像仓库的需求。harbor以docker-compose的规范形式组织各个组件,并通过docker-compose工具进行启停。

docker的registry是用本地存储或者s3都是可以的,harbor的功能是在此之上提供用户权限管理、镜像复制等功能,提高使用的registry的效率。Harbor的镜像拷贝功能是通过docker registry的API去拷贝,这种做法屏蔽了繁琐的底层文件操作、不仅可以利用现有docker registry功能不必重复造轮子,而且可以解决冲突和一致性的问题。

(1)安装harbor

1、下载并解压harbor

下载地址:https://storage.googleapis.com/harbor-releases/release-1.6.0/harbor-offline-installer-v1.6.0-rc3.tgz

安装装harbor之前,必须先安装好docker-compose。

docker-compose在前面已经安装好了。

[root@lb01 ~]# tar xf harbor-offline-installer-v1.6.0-rc3.tgz 

2、修改配置文件

进入解压后的目录,修改harbor.cfg文件,修改过hostname = 192.168.10.101

[root@lb01 ~]# cd harbor/
[root@lb01 harbor]# vim  harbor.cfg
hostname = 192.168.10.101

说明:

配置文件说明:

## Configuration file of Harbor

# hostname设置访问地址,可以使用ip、域名,不可以设置为127.0.0.1或localhost
hostname = 192.168.10.101

# 访问协议,默认是http,也可以设置https,如果设置https,则nginx ssl需要设置on
ui_url_protocol = http

# mysql数据库root用户默认密码root123,实际使用时修改下
db_password = root123

max_job_workers = 3 
customize_crt = on
ssl_cert = /data/cert/server.crt
ssl_cert_key = /data/cert/server.key
secretkey_path = /data
admiral_url = NA

# 邮件设置,发送重置密码邮件时使用
email_identity = 
email_server = smtp.mydomain.com
email_server_port = 25
email_username = sample_admin@mydomain.com
email_password = abc
email_from = admin <sample_admin@mydomain.com>
email_ssl = false

# 启动Harbor后,管理员UI登录的密码,默认是Harbor12345
harbor_admin_password = Harbor12345

# 认证方式,这里支持多种认证方式,如LADP、本次存储、数据库认证。默认是db_auth,mysql数据库认证
auth_mode = db_auth

# LDAP认证时配置项
#ldap_url = ldaps://ldap.mydomain.com
#ldap_searchdn = uid=searchuser,ou=people,dc=mydomain,dc=com
#ldap_search_pwd = password
#ldap_basedn = ou=people,dc=mydomain,dc=com
#ldap_filter = (objectClass=person)
#ldap_uid = uid 
#ldap_scope = 3 
#ldap_timeout = 5

# 是否开启自注册
self_registration = on

# Token有效时间,默认30分钟
token_expiration = 30

# 用户创建项目权限控制,默认是everyone(所有人),也可以设置为adminonly(只能管理员)
project_creation_restriction = everyone

verify_remote_cert = on

3、修改 /etc/docker/daemon.json文件

[root@lb01 ~]# vim /etc/docker/daemon.json
{
  "insecure-registries": ["192.168.10.101"]
}

然后重启dokcer服务。

[root@lb01 ~]# systemctl restart docker

4、安装harbor

在harbor解压目录中执行./install..sh命令

[root@lb01 harbor]# ./install.sh
.....
✔ ----Harbor has been installed and started successfully.----

Now you should be able to visit the admin portal at http://192.168.10.101. 
For more details, please visit https://github.com/goharbor/harbor .

[root@lb01 harbor]# 

安装成功之后,查看一下镜像:

[root@lb01 ~]# docker images 
REPOSITORY                      TAG                 IMAGE ID            CREATED             SIZE
centos_nginx                    latest              f3f68e71836d        3 days ago          499MB
goharbor/chartmuseum-photon     v0.7.1-v1.6.0       b67537c8726d        6 days ago          357MB
goharbor/harbor-migrator        v1.6.0              22775c4e4066        6 days ago          803MB
goharbor/redis-photon           v1.6.0              06a776379641        6 days ago          214MB
goharbor/clair-photon           v2.0.5-v1.6.0       3c5c2968147d        6 days ago          309MB
goharbor/notary-server-photon   v0.5.1-v1.6.0       4dd7df4ad4b6        6 days ago          215MB
goharbor/notary-signer-photon   v0.5.1-v1.6.0       78decf4dc4d9        6 days ago          212MB
goharbor/registry-photon        v2.6.2-v1.6.0       98bf341403a5        6 days ago          201MB
goharbor/nginx-photon           v1.6.0              71b4ae38b2e7        6 days ago          138MB
goharbor/harbor-log             v1.6.0              9de414888d83        6 days ago          203MB
goharbor/harbor-jobservice      v1.6.0              273959ce10be        6 days ago          198MB
goharbor/harbor-ui              v1.6.0              dca75f6ec7d4        6 days ago          221MB
goharbor/harbor-adminserver     v1.6.0              08b2d70c45ce        6 days ago          187MB
goharbor/harbor-db              v1.6.0              d241676e2034        6 days ago          225MB
centos                          latest              5182e96772bf        4 weeks ago         200MB
registry                        latest              b2b03e9146e1        2 months ago        33.3MB
[root@lb01 ~]#

有很多goharbor/*的镜像。

查看进程:

[root@lb01 ~]# docker ps
CONTAINER ID        IMAGE                                    COMMAND                  CREATED             STATUS                   PORTS                                                              NAMES
6aa26daeba21        goharbor/harbor-jobservice:v1.6.0        "/harbor/start.sh"       3 minutes ago       Up 3 minutes                                                                                harbor-jobservice
60dc029400f1        goharbor/nginx-photon:v1.6.0             "nginx -g 'daemon of…"   3 minutes ago       Up 3 minutes (healthy)   0.0.0.0:80->80/tcp, 0.0.0.0:443->443/tcp, 0.0.0.0:4443->4443/tcp   nginx
c31d0fbe1adc        goharbor/harbor-ui:v1.6.0                "/harbor/start.sh"       4 minutes ago       Up 3 minutes (healthy)                                                                      harbor-ui
00e35753ddc6        goharbor/harbor-adminserver:v1.6.0       "/harbor/start.sh"       4 minutes ago       Up 3 minutes (healthy)                                                                      harbor-adminserver
6ce1e73b9c9b        goharbor/registry-photon:v2.6.2-v1.6.0   "/entrypoint.sh /etc…"   4 minutes ago       Up 4 minutes (healthy)   5000/tcp                                                           registry
5046c1ffa5dc        goharbor/harbor-db:v1.6.0                "/entrypoint.sh post…"   4 minutes ago       Up 4 minutes (healthy)   5432/tcp                                                           harbor-db
9d2cfbcd9cc8        goharbor/redis-photon:v1.6.0             "docker-entrypoint.s…"   4 minutes ago       Up 4 minutes             6379/tcp                                                           redis
7b2a0fa91f1d        goharbor/harbor-log:v1.6.0               "/bin/sh -c /usr/loc…"   4 minutes ago       Up 4 minutes (healthy)   127.0.0.1:1514->10514/tcp                                          harbor-log
[root@lb01 ~]# 

harbor已经启动。

浏览器打开:192.168.10.101

f10e7df9c2f10ad06be8a07d371761ed4eb.jpg

OK。harbor安装成功。

(2)Harbor使用

登录harbor的账号是:root,密码:Harbor12345,可以在harbor.cfg文件中修改密码。登录成功如下图:

569f9ac2e8a9660184ea0449d636db83b39.jpg

1、新建一个名为test的项目

3eb171b2f87b49a16c0afab83be3f5e262a.jpg

如果选择公开,则任何人都有此项目下镜像的读权限。命令行用户不需要“docker login”就可以拉取此项目下的镜像。

2、本地命令行登录

给镜像打一个标签:

[root@lb01 ~]# docker tag centos_nginx  192.168.10.101/test/centos_nginx:haha

登录:

[root@lb01 ~]# docker login 192.168.10.101
Username: admin
Password: 
WARNING! Your password will be stored unencrypted in /root/.docker/config.json.
Configure a credential helper to remove this warning. See
https://docs.docker.com/engine/reference/commandline/login/#credentials-store

Login Succeeded
[root@lb01 ~]# 

登录成功,就可以推送镜像了。

[root@lb01 ~]# docker push 192.168.10.101/test/centos_nginx
The push refers to repository [192.168.10.101/test/centos_nginx]
58888f1784bf: Pushed 
97d852a5b0f7: Pushed 
f5e93efeb80e: Pushed 
2cd8f00657b1: Pushed 
b39ca80cd9a7: Pushed 
9f7887e07f11: Pushed 
26a22778e17f: Pushed 
9c7851c4a382: Pushed 
081242efb8b5: Pushed 
d9d0e311ea90: Pushed 
501f40271ef9: Pushed 
a7ad7c2b558d: Pushed 
75162b1daa08: Pushed 
9d90c748557d: Pushed 
1d31b5806ba4: Pushed 
haha: digest: sha256:fd7934a4b9043dd90c6bd00f978fa44024b12ef96df0a725a817332931e95db8 size: 3446
[root@lb01 ~]# 

浏览器查看一下:

aa4d7ff22be4391f5402503ceb49793a1ed.jpg

推送成功。

退出登录:

[root@lb01 ~]# docker logout 192.168.10.101
Removing login credentials for 192.168.10.101
[root@lb01 ~]# 

(3)SSL证书

1、修改daemon.json文件为:

{
 "registry-mirrors": ["https://registry.docker-cn.com","https://dhq9bx4f.mirror.aliyuncs.com"]
}

2、使用openssl自建ca,openssl的配置文件默认为/etc/pki/tls/openssl.cnf

在此文件添加一行:subjectAltName=IP:192.168.10.101

进入/etc/pki/CA/目录,生成自签证书

[root@lb01 ~]# cd /etc/pki/CA/
[root@lb01 CA]# (umask 077;openssl  genrsa  -out  private/cakey.pem  2048)
Generating RSA private key, 2048 bit long modulus
........................+++
................+++
e is 65537 (0x10001)
[root@lb01 CA]# 

创建index.txt文件 和serial文件

[root@lb01 CA]# touch index.txt
[root@lb01 CA]# echo 01 > serial
[root@lb01 CA]# 

生成服务证书

[root@lb01 CA]# openssl  req  -new  -x509  -key private/cakey.pem -out  cacert.pem   -days 7300
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:gd
Locality Name (eg, city) [Default City]:gd
Organization Name (eg, company) [Default Company Ltd]:haha
Organizational Unit Name (eg, section) []:haha
Common Name (eg, your name or your server's hostname) []:haha
Email Address []:haha@haha.com
[root@lb01 CA]# 

生成签名请求:

[root@lb01 CA]# (umask  077;openssl  genrsa  -out  httpd.key  1024)
Generating RSA private key, 1024 bit long modulus
....++++++
...++++++
e is 65537 (0x10001)
[root@lb01 CA]# openssl  req  -new  -key  httpd.key  -days  365  -out  httpd.csr
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:gd  
Locality Name (eg, city) [Default City]:gd
Organization Name (eg, company) [Default Company Ltd]:haha
Organizational Unit Name (eg, section) []:haha
Common Name (eg, your name or your server's hostname) []:haha
Email Address []:haha@haha.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:haha
[root@lb01 CA]# 

使用ca证书签署请求

[root@lb01 CA]# ls
cacert.pem  certs  crl  httpd.csr  httpd.key  index.txt  newcerts  private  serial
[root@lb01 CA]# openssl ca -in httpd.csr -out certs/httpd.crt -days 365
Using configuration from /etc/pki/tls/openssl.cnf
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number: 1 (0x1)
        Validity
            Not Before: Sep 10 14:49:28 2018 GMT
            Not After : Sep 10 14:49:28 2019 GMT
        Subject:
            countryName               = CN
            stateOrProvinceName       = gd
            organizationName          = haha
            organizationalUnitName    = haha
            commonName                = haha
            emailAddress              = haha@haha.com
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            Netscape Comment: 
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier: 
                6F:9E:11:75:25:BA:C8:EB:1E:2E:15:70:62:58:96:DD:DC:B2:22:35
            X509v3 Authority Key Identifier: 
                keyid:79:2E:9E:8D:42:1C:54:88:52:7B:8E:7D:53:AB:95:64:8C:DC:71:E6

Certificate is to be certified until Sep 10 14:49:28 2019 GMT (365 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated
[root@lb01 CA]# 

然系统信任自己:

[root@lb01 cert]# cat /etc/pki/CA/cacert.pem >> /etc/pki/tls/certs/ca-bundle.crt

创建一个/data/cert/目录。将/etc/pki/CA/httpd.key、/etc/pki/CA/certs/httpd.crt文件拷贝到/data/cert/,并分别重命名为:server.crt、server.key

[root@lb01 ~]# mkdir /data/cert/ -p
[root@lb01 ~]# 

将公钥和私钥复制到到/data/cert目录

[root@lb01 CA]# pwd
/etc/pki/CA
[root@lb01 CA]# ls
cacert.pem  crl        httpd.key  index.txt.attr  newcerts  serial
certs       httpd.csr  index.txt  index.txt.old   private   serial.old
[root@lb01 CA]# cp httpd.key /data/cert/server.key
[root@lb01 CA]# cp certs/httpd.crt  /data/cert/server.crt
[root@lb01 CA]# 

其中,server.crt为公钥,server.key为私钥。

3、进入harbor的解压目录重新安装harbor

harbor解压在/root目录中

修改harbor.cfg文件:ui_url_protocol = https

[root@lb01 CA]# 
[root@lb01 CA]# cd /root/harbor/
[root@lb01 harbor]# ./install.sh

安装ca-certificates

[root@lb01 nginx]# yum install ca-certificates -y
[root@lb01 nginx]# update-ca-trust force-enable
[root@lb01 nginx]# cp /etc/pki/CA/cacert.pem /etc/pki/ca-trust/source/anchors/
[root@lb01 nginx]# update-ca-trust extract
[root@lb01 nginx]# systemctl restart docker
[root@lb01 nginx]# cp /data/cert/server.crt /etc/pki/ca-trust/source/anchors/

如果出现x509,执行命令:

echo -n openssl s_client -showcerts -connect 域名:443 2>/dev/null sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' >> /etc/ssl/certs/ca-bundle.trust.crt

4、登录测试

 

3f5520359dc4a05372a2a17a90101649c22.jpg

转载于:https://my.oschina.net/logmm/blog/1935471

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值