Pages

Sunday, 16 February 2014

Docker及其安装(also can be installed on 内核版本:2.6.32-431.el6 centos vps)


We try to make using Docker easy.

Interactive commandline tutorial

The best way to learn how Docker works is to use it!
This hands-on tutorial is 100% online, so you don't need to install a thing. In about 10-15 minutes you'll be familiar with the basic Docker commands.

from https://www.docker.io/gettingstarted/
https://www.docker.io/gettingstarted/#1

  1. Get the latest Docker package.
    $ wget -qO- https://get.docker.com/ | sh(用此法在我的vps上安装docker失败。强烈建议不要使用此法。如果你的vps是debian7/ubuntu14.0.4系统,请看下文)
    
    The system prompts you for your sudo password. Then, it downloads and installs Docker and its dependencies.
    Note: If your company is behind a filtering proxy, you may find that the apt-key command fails for the Docker repo during installation. To work around this, add the key directly using the following:
      $ wget -qO- https://get.docker.com/gpg | sudo apt-key add -
    
  2. Verify docker is installed correctly.
    $ docker run hello-world
from  http://docs.docker.com/linux/step_one/
(https://docs.docker.com/engine/installation/,
https://docs.docker.com/engine/installation/debian/
----------------------
在debian7/8下,安装docker

apt-get install apt-transport-https (我在某台debian vps上运行此命令成功,但在另一台debian vps上运行此命令却失败了。但在2台ubuntu vps上分别运行此命令都成功了。可见ubuntu比debian更好/更方便,而debian则比centos更方便。因此就vps而言,ubuntu是最好的操作系统!
apt-get install aufs-tools

apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D
nano /etc/apt/sources.list
在文件末尾加上
deb https://apt.dockerproject.org/repo debian-wheezy main
deb http://ftp.de.debian.org/debian wheezy-backports main
(如果是debian8,则把上面的2个wheezy都改成jessie)
apt-get update -y

apt-get install docker-engine
这样即可成功安装docker-engine.


root@shc:~# docker -v
Docker version 1.12.1, build 23cf638
root@shc:~# 
参考:
https://docs.docker.com/engine/installation/debian/
https://github.com/docker/docker/issues/15692中的deshka的评论。
---------------------
在ubuntu14.0.4下,安装docker

apt-get install apt-transport-https
apt-get install aufs-tools

apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D

echo 'deb https://apt.dockerproject.org/repo ubuntu-trusty main' >> '/etc/apt/sources.list'

apt-get update
apt-get install docker-engine (在ubuntu14.0.4下,此步会自动启动
docker.因此无需再运行service docker start)

参考自:https://docs.docker.com/engine/installation/ubuntulinux/
-----------------------------------------
在centos6.x下,安装docker

centos/fedora系统一贯比debian/ubuntu系统繁琐和复杂。 

如果你一定要在centos下安装docker,请先按此文用Elrepo包升级centos7/6的内核(不要用“从源码编译”的方式。“从源码编译”的方式非常难... 升级centos7/6的内核到3.10.0或更高版本。然后,
yum update
nano /etc/yum.repos.d/docker.repo
其内容为:
[dockerrepo] name=Docker Repository baseurl=https://yum.dockerproject.org/repo/main/centos/$releasever/ enabled=1 gpgcheck=1 gpgkey=https://yum.dockerproject.org/gpg

yum install docker-engine -y
service docker start即可。
参考自https://docs.docker.com/engine/installation/centos/
-------------------------------------------
在centos7.x下,安装docker

centos/fedora系统一贯比debian/ubuntu系统繁琐和复杂。 

如果你一定要在centos下安装docker,请先按此文用Elrepo包升级centos7/6的内核(不要用“从源码编译”的方式。“从源码编译”的方式非常难... 升级centos7/6的内核到3.10.0或更高版本。然后,
yum update
nano /etc/yum.repos.d/docker.repo
其内容为:
[dockerrepo] name=Docker Repository baseurl=https://yum.dockerproject.org/repo/main/centos/$releasever/ enabled=1
gpgcheck=1 gpgkey=https://yum.dockerproject.org/gpg

关闭SELinux
1
2
3
4
# nano /etc/selinux/config 
SELINUX=disabled
# reboot

3、关闭firewalld(以免和docker创建iptables规则冲突
改用传统的iptables-service 来管理iptables规则
1
2
3
4
5
# systemctl stop firewalld
# systemctl disable firewalld
# systemctl disable iptables.service  //不需要启用这个服务,docker会自动启动iptables

安装docker:
yum install docker-engine -y(现在,暂时还启动不了docker,需做如下操作才行)
# vi /usr/lib/systemd/system/docker.service 
  
[Service]
EnvironmentFile=-/etc/sysconfig/docker  (加入这一行)
Type=notify
ExecStart=/usr/bin/docker daemon -H fd:// $OPTIONS  (加入$OPTIONS)
  
# vi /etc/sysconfig/docker 
OPTIONS="--storage-driver=overlay"
  
# systemctl daemon-reload
  

systemctl start docker (现在终于成功启动docker)
-------------------------------
https://philipzheng.gitbooks.io/docker_practice/content/index.html
(Docker —— 從入門到實踐)
--------------------------------

针对 Linux on Power Systems 的 Docker


Docker 是一个部署、执行和管理容器的工具。本文将提供 Linux on Power Systems Docker 二进制文件的链接,并介绍安装它们的步骤。

简介

Docker 是一个用于部署、执行和管理容器的工具。自 Vivid (15.04) 版本起,Docker 就开始包含在 Ubuntu 中,自 23 版起,就开始包含在 Fedora 中。
已有针对 Ubuntu Trusty (14.04) LE 和 Red Hat Enterprise Linux Version 7.1 LE 的试验性 Linux on Power Systems 二进制文件。
请注意,这是用于获取早期用户反馈的试验性代码。可能有一些限制。
此试验性代码随时可能更新或停止提供!此外,没有针对此试验性代码的官方支持声明。
如有疑问、评论和反馈,请加入 Linux on Power 社区

Docker 二进制文件的存储库位置

发行版存储库链接
Ubuntu Trusty (14.04)http://ftp.unicamp.br/pub/ppc64el/ubuntu/14_04/docker-ppc64el/
RHEL 7.1 LEhttp://ftp.unicamp.br/pub/ppc64el/rhel/7_1/docker-ppc64el/

安装

安装在 Ubuntu Trusty 上

使用根用户特权执行以下步骤
  • 安装 Docker 存储库:
# echo deb http://ftp.unicamp.br/pub/ppc64el/ubuntu/14_04/docker-ppc64el/ trusty 
main > /etc/apt/sources.list.d/trusty-docker.list
  • 更新归档索引
 # apt-get update
  • 安装 Docker 包
 # apt-get install docker.io

安装在 RHEL 7.1 LE 上

使用根用户特权执行以下步骤
  • 安装 Docker 存储库:
#cat > /etc/yum.repos.d/docker.repo <<EOF 
[docker]
name=Docker
baseurl=http://ftp.unicamp.br/pub/ppc64el/rhel/7_1/docker-ppc64el/
enabled=1
gpgcheck=0
EOF
  • 安装 Docker 包
# yum install docker-io
  • 启动 Docker 引擎
# service docker start

参考资料

from http://www.ibm.com/developerworks/cn/linux/l-docker/index.html
------------------------------------------------------------------------------------------------------------------------

在 CentOS6.x上,安装 docker

需要注意的是CentOS 6.5与7.0的安装是有一点点不同的,CentOS-6上docker的安装包叫docker-io,并且来源于Fedora epel库,这个仓库维护了大量的没有包含在发行版中的软件,所以先要安装EPEL,而CentOS-7的docker直接包含在官方镜像源的Extras仓库(CentOS-Base.repo下的[extras]节enable=1启用)。前提是都需要联网,具体安装过程如下。
###1. 禁用selinux###
1
2
3
4
5
6
7
# getenforce
enforcing
# setenforce 0
permissive
# vi /etc/selinux/config
SELINUX=disabled
...
###2. 安装 Fedora EPEL###
epel-release-6-8.noarch.rpm包在发行版的介质里面已经自带了,可以从rpm安装。
1
2
3
# yum install epel-release-6-8.noarch.rpm
//或
yum -y install http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
如果出现GPG key retrieval failed: [Errno 14] Could not open/read file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6问题,请在线安装epel,下载RPM-GPG-KEY-EPEL-6文件。
这一步执行之后,会在/etc/yum.repos.d/下生成epel.repo、epel-testing.repo两个文件,用于从Fedora官网下载rpm包。
###3. 检查内核版本###
1
2
3
4
# uname -r
2.6.32-431.el6.x86_64
# cat /etc/redhat-release 
CentOS release 6.5 (Final)
看到这个最低的内核版本:2.6.32-431.el6,事实运行起来是没太大问题的,你也可以升级到3.10.x版本。
另外你也可以运行脚本check-config.sh,来检查内核模块符不符合(下面有些missing的,我的docker还是可以正常启动):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
[root@sean ~]# ./check-config 
warning: /proc/config.gz does not exist, searching other paths for kernel config...
info: reading kernel config from /boot/config-2.6.32-431.el6.x86_64 ...

Generally Necessary:
- cgroup hierarchy: properly mounted [/cgroup]
- CONFIG_NAMESPACES: enabled
- CONFIG_NET_NS: enabled
- CONFIG_PID_NS: enabled
- CONFIG_IPC_NS: enabled
- CONFIG_UTS_NS: enabled
- CONFIG_DEVPTS_MULTIPLE_INSTANCES: enabled
- CONFIG_CGROUPS: enabled
- CONFIG_CGROUP_CPUACCT: enabled
- CONFIG_CGROUP_DEVICE: enabled
- CONFIG_CGROUP_FREEZER: enabled
- CONFIG_CGROUP_SCHED: enabled
- CONFIG_MACVLAN: enabled
- CONFIG_VETH: enabled
- CONFIG_BRIDGE: enabled
- CONFIG_NF_NAT_IPV4: missing
- CONFIG_IP_NF_TARGET_MASQUERADE: enabled
- CONFIG_NETFILTER_XT_MATCH_ADDRTYPE: missing
- CONFIG_NETFILTER_XT_MATCH_CONNTRACK: enabled
- CONFIG_NF_NAT: enabled
- CONFIG_NF_NAT_NEEDED: enabled

Optional Features:
- CONFIG_MEMCG_SWAP: missing
- CONFIG_RESOURCE_COUNTERS: enabled
- CONFIG_CGROUP_PERF: enabled
- Storage Drivers:
  - "aufs":
    - CONFIG_AUFS_FS: missing
    - CONFIG_EXT4_FS_POSIX_ACL: enabled
    - CONFIG_EXT4_FS_SECURITY: enabled
  - "btrfs":
    - CONFIG_BTRFS_FS: enabled
  - "devicemapper":
    - CONFIG_BLK_DEV_DM: enabled
    - CONFIG_DM_THIN_PROVISIONING: enabled
    - CONFIG_EXT4_FS: enabled
    - CONFIG_EXT4_FS_POSIX_ACL: enabled
    - CONFIG_EXT4_FS_SECURITY: enabled
假如你是自己编译内核,请特别留意几个绝对不能缺少的:DM_THIN_PROVISIONING、IP_NF_TARGET_MASQUERADE、NF_NAT。(AUFS_FS没有对应选项,还不清楚怎么回事,但不是必须)
###4. 安装 docker-io###
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# yum install docker-io
Dependencies Resolved

===========================================================================================
 Package                        Arch               Version          Repository     Size
===========================================================================================
Installing:
 docker-io                      x86_64         1.1.2-1.el6          epel          4.5 M
Installing for dependencies:
 lua-alt-getopt                 noarch         0.7.0-1.el6          epel          6.9 k
 lua-filesystem                 x86_64         1.4.2-1.el6          epel           24 k
 lua-lxc                        x86_64         1.0.6-1.el6          epel           15 k
 lxc                            x86_64         1.0.6-1.el6          epel          120 k
 lxc-libs                       x86_64         1.0.6-1.el6          epel          248 k

Transaction Summary
===========================================================================================
Install       6 Package(s)
许多文档介绍到这里,下一步为挂载/cgroup文件系统,我的docker版本为1.1.2,没有修改/etc/fstab的步骤。
###5. 启动试运行###
1
2
3
# service docker start
//或
# docker -d
##6. 异常##
在我的一次安装过程中,很不幸遇到下面的问题:
docker -d启动,或tail -f /var/log/docker查看日志
1
2
3
4
5
6
7
8
[f32e7d9f] +job initserver()
[f32e7d9f.initserver()] Creating server
[f32e7d9f] +job serveapi(unix:///var/run/docker.sock)
2014/10/22 13:02:45 Listening for HTTP on unix (/var/run/docker.sock)
Error running DeviceCreate (createPool) dm_task_run failed
[f32e7d9f] -job initserver() = ERR (1)
2014/10/22 13:02:45 Error running DeviceCreate (createPool) dm_task_run failed
\nWed Oct 22 14:35:54 CST 2014\n
再或者是service docker restart
1
2
3
4
5
6
Stopping docker:                                             [  OK  ]
Starting cgconfig service: Error: cannot mount cpuset to /cgroup/cpuset: Device or resource busy
/sbin/cgconfigparser; error loading /etc/cgconfig.conf: Cgroup mounting failed
Failed to parse /etc/cgconfig.conf                           [FAILED]

Starting docker:                                              [  OK  ]
1
2
Unable to enable network bridge NAT: iptables failed: iptables -I POSTROUTING -t nat -s 172.17.42.1/16 ! -d 172.17.42.1/16 -j MASQUERADE: iptables v1.4.7: can't initialize iptables table `nat': Table does not exist (do you need to insmod?)
Perhaps iptables or your kernel needs to be upgraded.
上面的三个异常都是由于内核模块的缺失导致的,这也是自己编译内核来升级带来的风险,于是就有了sciurus的kernel-ml-aufs的rpm包(见参考的第一个链接)。
##7. 参考##

---------------------------------------------------------------------------------------------------

Distribution

The Docker toolset to pack, ship, store, and deliver content.
This repository's main product is the Docker Registry 2.0 implementation for storing and distributing Docker images. It supersedes the docker/docker-registry project with a new API design, focused around security and performance.
Circle CI GoDoc
This repository contains the following components:
ComponentDescription
registryAn implementation of the Docker Registry HTTP API V2 for use with docker 1.6+.
librariesA rich set of libraries for interacting with,distribution components. Please see godoc for details. Note: These libraries are unstable.
specificationsDistribution related specifications are available in docs/spec
documentationDocker's full documentation set is available at docs.docker.com. This repository contains the subset related just to the registry.

How does this integrate with Docker engine?

This project should provide an implementation to a V2 API for use in the Docker core project. The API should be embeddable and simplify the process of securely pulling and pushing content from docker daemons.

What are the long term goals of the Distribution project?

The Distribution project has the further long term goal of providing a secure tool chain for distributing content. The specifications, APIs and tools should be as useful with Docker as they are without.
Our goal is to design a professional grade and extensible content distribution system that allow users to:
  • Enjoy an efficient, secured and reliable way to store, manage, package and exchange content
  • Hack/roll their own on top of healthy open-source components
  • Implement their own home made solution through good specs, and solid extensions mechanism.

More about Registry 2.0

The new registry implementation provides the following benefits:
  • faster push and pull
  • new, more efficient implementation
  • simplified deployment
  • pluggable storage backend
  • webhook notifications
For information on upcoming functionality, please see ROADMAP.md.

Who needs to deploy a registry?

By default, Docker users pull images from Docker's public registry instance. Installing Dockergives users this ability. Users can also push images to a repository on Docker's public registry, if they have a Docker Hub account. 
For some users and even companies, this default behavior is sufficient. For others, it is not. 
For example, users with their own software products may want to maintain a registry for private, company images. Also, you may wish to deploy your own image repository for images used to test or in continuous integration. For these use cases and others, deploying your own registry instance may be the better choice.

Migration to Registry 2.0

For those who have previously deployed their own registry based on the Registry 1.0 implementation and wish to deploy a Registry 2.0 while retaining images, data migration is required. A tool to assist with migration efforts has been created. For more information see docker/migrator.

Contribute

Please see CONTRIBUTING.md for details on how to contribute issues, fixes, and patches to this project. If you are contributing code, see the instructions for building a development environment.

Support

If any issues are encountered while using the Distribution project, several avenues are available for support:
IRC#docker-distribution on FreeNode
Issue Trackergithub.com/docker/distribution/issues
Google Groupshttps://groups.google.com/a/dockerproject.org/forum/#!forum/distribution
Mailing Listdocker@dockerproject.org

from https://github.com/docker/distribution
https://github.com/docker/docker-registry
-------------------------

docker基础

前言

Docker 是目前最为火热的开源技术之一,它在应用层面(用户空间)将相关依赖进行了打包,构建出一个个轻量而完备的功能模块(镜像),能够跨平台运行,低开销地创建传递销毁和重建,实在是开发运维居家旅行必备良品
Docker allows you to package an application with all of its dependencies into a standardized unit for software development.
目前通用的应用场景中,Docker 可以明显提升开发和运维效率
Docker containers wrap up a piece of software in a complete filesystem that contains everything it needs to run: code, runtime, system tools, system libraries – anything you can install on a server. This guarantees that it will always run the same, regardless of the environment it is running in.
它的隔离性确保了应用的模块化,轻量性使得系资源被更为有效的使用,只是安全性还在持续的提升过程中
以下是容器和虚拟机的区别
每一个虚拟机除了必要的应用和它依赖的库还包含了一整个操作系统
每一个容器只包含必要的应用和其依赖的库,操作系统的内核是共享的(其它实例并不拥有独享内核)
这里分享一下 Docker 的相关基础,详细可以参阅 官方文档
Tip: 当前的最新版本为 Docker 1.10 Released on January 15, 2016

概要


依赖

Docker需要运行在 CentOS 7.X 上 (这是以CentOS为演示平台)
  • 64位 操作系统
  • 内核版本至少为 3.10
检查方法
[root@h103 ~]# hostnamectl 
   Static hostname: h103
         Icon name: computer-vm
           Chassis: vm
        Machine ID: 12a02f8ee88d4b8e91d54d1390b0b275
           Boot ID: 3232f3779bf34f68959ac017c214f268
    Virtualization: vmware
  Operating System: CentOS Linux 7 (Core)
       CPE OS Name: cpe:/o:centos:centos:7
            Kernel: Linux 3.10.0-327.4.4.el7.x86_64
      Architecture: x86-64
[root@h103 ~]# 
符合要求
Tip: CentOS 7 开始使用使用 hostnamectl 管理主机名,更为简洁方便
另外最好将系统进行升级,打上所有最新的补丁
[root@h103 ~]# yum update 
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
 * base: mirrors.163.com
 * extras: mirrors.pubyun.com
 * updates: mirrors.163.com
No packages marked for update
[root@h103 ~]# 
准备工作完成

使用yum安装Docker

添加yum仓库

[root@h103 ~]# ll /etc/yum.repos.d/
total 28
drwxr-xr-x 2 root root   24 Jan 19 15:18 bak
-rw-r--r-- 1 root root 1664 Dec  9 17:59 CentOS-Base.repo
-rw-r--r-- 1 root root 1309 Dec  9 17:59 CentOS-CR.repo
-rw-r--r-- 1 root root  649 Dec  9 17:59 CentOS-Debuginfo.repo
-rw-r--r-- 1 root root  290 Dec  9 17:59 CentOS-fasttrack.repo
-rw-r--r-- 1 root root  630 Dec  9 17:59 CentOS-Media.repo
-rw-r--r-- 1 root root 1331 Dec  9 17:59 CentOS-Sources.repo
-rw-r--r-- 1 root root 1952 Dec  9 17:59 CentOS-Vault.repo
[root@h103 ~]# tee /etc/yum.repos.d/docker.repo <<-'EOF'
> [dockerrepo]
> name=Docker Repository
> baseurl=https://yum.dockerproject.org/repo/main/centos/$releasever/
> enabled=1
> gpgcheck=1
> gpgkey=https://yum.dockerproject.org/gpg
> EOF
[dockerrepo]
name=Docker Repository
baseurl=https://yum.dockerproject.org/repo/main/centos/$releasever/
enabled=1
gpgcheck=1
gpgkey=https://yum.dockerproject.org/gpg
[root@h103 ~]# ll /etc/yum.repos.d/
total 32
drwxr-xr-x 2 root root   24 Jan 19 15:18 bak
-rw-r--r-- 1 root root 1664 Dec  9 17:59 CentOS-Base.repo
-rw-r--r-- 1 root root 1309 Dec  9 17:59 CentOS-CR.repo
-rw-r--r-- 1 root root  649 Dec  9 17:59 CentOS-Debuginfo.repo
-rw-r--r-- 1 root root  290 Dec  9 17:59 CentOS-fasttrack.repo
-rw-r--r-- 1 root root  630 Dec  9 17:59 CentOS-Media.repo
-rw-r--r-- 1 root root 1331 Dec  9 17:59 CentOS-Sources.repo
-rw-r--r-- 1 root root 1952 Dec  9 17:59 CentOS-Vault.repo
-rw-r--r-- 1 root root  166 Jan 19 17:12 docker.repo
[root@h103 ~]# cat /etc/yum.repos.d/docker.repo 
[dockerrepo]
name=Docker Repository
baseurl=https://yum.dockerproject.org/repo/main/centos/$releasever/
enabled=1
gpgcheck=1
gpgkey=https://yum.dockerproject.org/gpg
[root@h103 ~]# 

安装Docker

[root@h103 ~]# yum install docker-engine
Loaded plugins: fastestmirror, langpacks
dockerrepo                                                                                                     | 2.9 kB  00:00:00     
dockerrepo/7/primary_db                                                                                        | 8.2 kB  00:00:00     
Loading mirror speeds from cached hostfile
 * base: mirrors.163.com
 * extras: mirrors.pubyun.com
 * updates: mirrors.163.com
Resolving Dependencies
--> Running transaction check
---> Package docker-engine.x86_64 0:1.9.1-1.el7.centos will be installed
--> Processing Dependency: docker-engine-selinux >= 1.9.1-1.el7.centos for package: docker-engine-1.9.1-1.el7.centos.x86_64
--> Running transaction check
---> Package docker-engine-selinux.noarch 0:1.9.1-1.el7.centos will be installed
--> Processing Dependency: policycoreutils-python for package: docker-engine-selinux-1.9.1-1.el7.centos.noarch
--> Running transaction check
---> Package policycoreutils-python.x86_64 0:2.2.5-20.el7 will be installed
--> Processing Dependency: libsemanage-python >= 2.1.10-1 for package: policycoreutils-python-2.2.5-20.el7.x86_64
--> Processing Dependency: audit-libs-python >= 2.1.3-4 for package: policycoreutils-python-2.2.5-20.el7.x86_64
--> Processing Dependency: python-IPy for package: policycoreutils-python-2.2.5-20.el7.x86_64
--> Processing Dependency: libqpol.so.1(VERS_1.4)(64bit) for package: policycoreutils-python-2.2.5-20.el7.x86_64
--> Processing Dependency: libqpol.so.1(VERS_1.2)(64bit) for package: policycoreutils-python-2.2.5-20.el7.x86_64
--> Processing Dependency: libapol.so.4(VERS_4.0)(64bit) for package: policycoreutils-python-2.2.5-20.el7.x86_64
--> Processing Dependency: checkpolicy for package: policycoreutils-python-2.2.5-20.el7.x86_64
--> Processing Dependency: libqpol.so.1()(64bit) for package: policycoreutils-python-2.2.5-20.el7.x86_64
--> Processing Dependency: libapol.so.4()(64bit) for package: policycoreutils-python-2.2.5-20.el7.x86_64
--> Running transaction check
---> Package audit-libs-python.x86_64 0:2.4.1-5.el7 will be installed
---> Package checkpolicy.x86_64 0:2.1.12-6.el7 will be installed
---> Package libsemanage-python.x86_64 0:2.1.10-18.el7 will be installed
---> Package python-IPy.noarch 0:0.75-6.el7 will be installed
---> Package setools-libs.x86_64 0:3.3.7-46.el7 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

======================================================================================================================================
 Package                                Arch                   Version                               Repository                  Size
======================================================================================================================================
Installing:
 docker-engine                          x86_64                 1.9.1-1.el7.centos                    dockerrepo                 8.2 M
Installing for dependencies:
 audit-libs-python                      x86_64                 2.4.1-5.el7                           base                        69 k
 checkpolicy                            x86_64                 2.1.12-6.el7                          base                       247 k
 docker-engine-selinux                  noarch                 1.9.1-1.el7.centos                    dockerrepo                  21 k
 libsemanage-python                     x86_64                 2.1.10-18.el7                         base                        94 k
 policycoreutils-python                 x86_64                 2.2.5-20.el7                          base                       435 k
 python-IPy                             noarch                 0.75-6.el7                            base                        32 k
 setools-libs                           x86_64                 3.3.7-46.el7                          base                       485 k

Transaction Summary
======================================================================================================================================
Install  1 Package (+7 Dependent packages)

Total download size: 9.5 M
Installed size: 40 M
Is this ok [y/d/N]: y
Downloading packages:
(1/8): audit-libs-python-2.4.1-5.el7.x86_64.rpm                                                                |  69 kB  00:00:00     
(2/8): libsemanage-python-2.1.10-18.el7.x86_64.rpm                                                             |  94 kB  00:00:00     
(3/8): python-IPy-0.75-6.el7.noarch.rpm                                                                        |  32 kB  00:00:00     
(4/8): policycoreutils-python-2.2.5-20.el7.x86_64.rpm                                                          | 435 kB  00:00:00     
(5/8): docker-engine-selinux-1.9.1-1.el7.centos.noarch.rpm                                                     |  21 kB  00:00:01     
(6/8): setools-libs-3.3.7-46.el7.x86_64.rpm                                                                    | 485 kB  00:00:00     
(7/8): checkpolicy-2.1.12-6.el7.x86_64.rpm                                                                     | 247 kB  00:00:02     
(8/8): docker-engine-1.9.1-1.el7.centos.x86_64.rpm                                                             | 8.2 MB  00:01:06     
--------------------------------------------------------------------------------------------------------------------------------------
Total                                                                                                 147 kB/s | 9.5 MB  00:01:06     
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : audit-libs-python-2.4.1-5.el7.x86_64                                                                               1/8 
  Installing : libsemanage-python-2.1.10-18.el7.x86_64                                                                            2/8 
  Installing : checkpolicy-2.1.12-6.el7.x86_64                                                                                    3/8 
  Installing : python-IPy-0.75-6.el7.noarch                                                                                       4/8 
  Installing : setools-libs-3.3.7-46.el7.x86_64                                                                                   5/8 
  Installing : policycoreutils-python-2.2.5-20.el7.x86_64                                                                         6/8 
  Installing : docker-engine-selinux-1.9.1-1.el7.centos.noarch                                                                    7/8 
setsebool:  SELinux is disabled.
  Installing : docker-engine-1.9.1-1.el7.centos.x86_64                                                                            8/8 
  Verifying  : setools-libs-3.3.7-46.el7.x86_64                                                                                   1/8 
  Verifying  : python-IPy-0.75-6.el7.noarch                                                                                       2/8 
  Verifying  : checkpolicy-2.1.12-6.el7.x86_64                                                                                    3/8 
  Verifying  : docker-engine-selinux-1.9.1-1.el7.centos.noarch                                                                    4/8 
  Verifying  : docker-engine-1.9.1-1.el7.centos.x86_64                                                                            5/8 
  Verifying  : libsemanage-python-2.1.10-18.el7.x86_64                                                                            6/8 
  Verifying  : policycoreutils-python-2.2.5-20.el7.x86_64                                                                         7/8 
  Verifying  : audit-libs-python-2.4.1-5.el7.x86_64                                                                               8/8 

Installed:
  docker-engine.x86_64 0:1.9.1-1.el7.centos                                                                                           

Dependency Installed:
  audit-libs-python.x86_64 0:2.4.1-5.el7                                checkpolicy.x86_64 0:2.1.12-6.el7                            
  docker-engine-selinux.noarch 0:1.9.1-1.el7.centos                     libsemanage-python.x86_64 0:2.1.10-18.el7                    
  policycoreutils-python.x86_64 0:2.2.5-20.el7                          python-IPy.noarch 0:0.75-6.el7                               
  setools-libs.x86_64 0:3.3.7-46.el7                                   

Complete!
[root@h103 ~]# 

启动Docker

[root@h103 ~]# service docker start
Redirecting to /bin/systemctl start  docker.service
[root@h103 ~]# ps faux | grep docker
root      3315  0.0  0.0 112644   960 pts/1    S+   17:20   0:00  |       \_ grep --color=auto docker
root      3200  1.5  0.5 395368 22640 ?        Ssl  17:20   0:00 /usr/bin/docker daemon -H fd://
[root@h103 ~]# ps -Lf 3200
UID        PID  PPID   LWP  C NLWP STIME TTY      STAT   TIME CMD
root      3200     1  3200  0    7 17:20 ?        Ssl    0:00 /usr/bin/docker daemon -H fd://
root      3200     1  3201  0    7 17:20 ?        Ssl    0:00 /usr/bin/docker daemon -H fd://
root      3200     1  3202  0    7 17:20 ?        Ssl    0:00 /usr/bin/docker daemon -H fd://
root      3200     1  3203  0    7 17:20 ?        Ssl    0:00 /usr/bin/docker daemon -H fd://
root      3200     1  3205  0    7 17:20 ?        Ssl    0:00 /usr/bin/docker daemon -H fd://
root      3200     1  3206  0    7 17:20 ?        Ssl    0:00 /usr/bin/docker daemon -H fd://
root      3200     1  3242  0    7 17:20 ?        Ssl    0:00 /usr/bin/docker daemon -H fd://
[root@h103 ~]# 
[root@h103 ~]# systemctl status docker.service
● docker.service - Docker Application Container Engine
   Loaded: loaded (/usr/lib/systemd/system/docker.service; disabled; vendor preset: disabled)
   Active: active (running) since Tue 2016-01-19 17:20:10 CST; 10min ago
     Docs: https://docs.docker.com
 Main PID: 3200 (docker)
   CGroup: /system.slice/docker.service
           └─3200 /usr/bin/docker daemon -H fd://

Jan 19 17:20:05 h103 systemd[1]: Starting Docker Application Container Engine...
Jan 19 17:20:05 h103 docker[3200]: time="2016-01-19T17:20:05.746819485+08:00" level=info msg="API listen on /var/run/docker.sock"
Jan 19 17:20:05 h103 docker[3200]: time="2016-01-19T17:20:05.917640473+08:00" level=warning msg="Usage of loopback devices i...ction."
Jan 19 17:20:09 h103 docker[3200]: time="2016-01-19T17:20:09.967104253+08:00" level=info msg="Firewalld running: true"
Jan 19 17:20:10 h103 docker[3200]: time="2016-01-19T17:20:10.147349577+08:00" level=info msg="Default bridge (docker0) is as...ddress"
Jan 19 17:20:10 h103 docker[3200]: time="2016-01-19T17:20:10.461970275+08:00" level=info msg="Loading containers: start."
Jan 19 17:20:10 h103 docker[3200]: time="2016-01-19T17:20:10.462289951+08:00" level=info msg="Loading containers: done."
Jan 19 17:20:10 h103 docker[3200]: time="2016-01-19T17:20:10.462313472+08:00" level=info msg="Daemon has completed initialization"
Jan 19 17:20:10 h103 docker[3200]: time="2016-01-19T17:20:10.462336163+08:00" level=info msg="Docker daemon" commit=a34a1d5 ...n=1.9.1
Jan 19 17:20:10 h103 systemd[1]: Started Docker Application Container Engine.
Hint: Some lines were ellipsized, use -l to show in full.
[root@h103 ~]#
Tip: CentOS 7 开始使用 systemd 来管理服务
[root@h103 ~]# which systemctl 
/usr/bin/systemctl
[root@h103 ~]# rpm -qf /usr/bin/systemctl
systemd-219-19.el7.x86_64
[root@h103 ~]# 
[root@h103 ~]# rpm -qi systemd
Name        : systemd
Version     : 219
Release     : 19.el7
Architecture: x86_64
Install Date: Tue 19 Jan 2016 04:31:19 PM CST
Group       : Unspecified
Size        : 22289573
License     : LGPLv2+ and MIT and GPLv2+
Signature   : RSA/SHA256, Wed 25 Nov 2015 11:42:22 PM CST, Key ID 24c6a8a7f4a80eb5
Source RPM  : systemd-219-19.el7.src.rpm
Build Date  : Fri 20 Nov 2015 12:49:31 PM CST
Build Host  : worker1.bsys.centos.org
Relocations : (not relocatable)
Packager    : CentOS BuildSystem <http://bugs.centos.org>
Vendor      : CentOS
URL         : http://www.freedesktop.org/wiki/Software/systemd
Summary     : A System and Service Manager
Description :
systemd is a system and service manager for Linux, compatible with
SysV and LSB init scripts. systemd provides aggressive parallelization
capabilities, uses socket and D-Bus activation for starting services,
offers on-demand starting of daemons, keeps track of processes using
Linux cgroups, supports snapshotting and restoring of the system
state, maintains mount and automount points and implements an
elaborate transactional dependency-based service control logic. It can
work as a drop-in replacement for sysvinit.
[root@h103 ~]# 

检查Docker

[root@h103 ~]# docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
b901d36b6f2f: Pull complete 
0a6ba66e537a: Pull complete 
Digest: sha256:8be990ef2aeb16dbcb9271ddfe2610fa6658d13f6dfb8bc72074cc1ca36966a7
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.
 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 Hub account:
 https://hub.docker.com

For more examples and ideas, visit:
 https://docs.docker.com/userguide/

[root@h103 ~]# 

使用脚本安装Docker

确保Docker已经删除的情况下,执行如下命令
[root@h103 ~]#  curl -sSL https://get.docker.com/ | sh
+ sh -c 'sleep 3; yum -y -q install docker-engine'

If you would like to use Docker as a non-root user, you should now consider
adding your user to the "docker" group with something like:

  sudo usermod -aG docker your-user

Remember that you will have to log out and back in for this to take effect!

[root@h103 ~]#
启动Docker
[root@h103 ~]# service docker start
Redirecting to /bin/systemctl start  docker.service
[root@h103 ~]# service docker status
Redirecting to /bin/systemctl status  docker.service
● docker.service - Docker Application Container Engine
   Loaded: loaded (/usr/lib/systemd/system/docker.service; disabled; vendor preset: disabled)
   Active: active (running) since Tue 2016-01-19 17:49:51 CST; 5s ago
     Docs: https://docs.docker.com
 Main PID: 4514 (docker)
   CGroup: /system.slice/docker.service
           └─4514 /usr/bin/docker daemon -H fd://

Jan 19 17:49:48 h103 systemd[1]: Starting Docker Application Container Engine...
Jan 19 17:49:48 h103 docker[4514]: time="2016-01-19T17:49:48.493901017+08:00" level=info msg="API listen on /var/run/docker.sock"
Jan 19 17:49:48 h103 docker[4514]: time="2016-01-19T17:49:48.523287426+08:00" level=warning msg="Usage of loopback devices i...ction."
Jan 19 17:49:51 h103 docker[4514]: time="2016-01-19T17:49:51.065772044+08:00" level=info msg="Firewalld running: true"
Jan 19 17:49:51 h103 docker[4514]: time="2016-01-19T17:49:51.152288274+08:00" level=info msg="Default bridge (docker0) is as...ddress"
Jan 19 17:49:51 h103 docker[4514]: time="2016-01-19T17:49:51.279193343+08:00" level=info msg="Loading containers: start."
Jan 19 17:49:51 h103 docker[4514]: time="2016-01-19T17:49:51.279523520+08:00" level=info msg="Loading containers: done."
Jan 19 17:49:51 h103 docker[4514]: time="2016-01-19T17:49:51.279547046+08:00" level=info msg="Daemon has completed initialization"
Jan 19 17:49:51 h103 docker[4514]: time="2016-01-19T17:49:51.279578666+08:00" level=info msg="Docker daemon" commit=a34a1d5 ...n=1.9.1
Jan 19 17:49:51 h103 systemd[1]: Started Docker Application Container Engine.
Hint: Some lines were ellipsized, use -l to show in full.
[root@h103 ~]# ps faux | grep docker 
root      4586  0.0  0.0 112644   956 pts/1    S+   17:50   0:00  |       \_ grep --color=auto docker
root      4514  1.2  0.5 387160 22600 ?        Ssl  17:49   0:00 /usr/bin/docker daemon -H fd://
[root@h103 ~]# ps -Lf 4514
UID        PID  PPID   LWP  C NLWP STIME TTY      STAT   TIME CMD
root      4514     1  4514  0    6 17:49 ?        Ssl    0:00 /usr/bin/docker daemon -H fd://
root      4514     1  4515  0    6 17:49 ?        Ssl    0:00 /usr/bin/docker daemon -H fd://
root      4514     1  4516  0    6 17:49 ?        Ssl    0:00 /usr/bin/docker daemon -H fd://
root      4514     1  4517  0    6 17:49 ?        Ssl    0:00 /usr/bin/docker daemon -H fd://
root      4514     1  4521  0    6 17:49 ?        Ssl    0:00 /usr/bin/docker daemon -H fd://
root      4514     1  4526  0    6 17:49 ?        Ssl    0:00 /usr/bin/docker daemon -H fd://
[root@h103 ~]# 
使用相同的方式检验Docker
[root@h103 ~]# docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
b901d36b6f2f: Pull complete 
0a6ba66e537a: Pull complete 
Digest: sha256:8be990ef2aeb16dbcb9271ddfe2610fa6658d13f6dfb8bc72074cc1ca36966a7
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.
 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 Hub account:
 https://hub.docker.com

For more examples and ideas, visit:
 https://docs.docker.com/userguide/

[root@h103 ~]# 
Tip: 脚本自动创建了一个docker的软件仓库,所以其实是将上面的手动过程使用脚本自动完成了
[root@h103 ~]# ll /etc/yum.repos.d/docker-main.repo 
-rw-r--r-- 1 root root 166 Jan 19 17:46 /etc/yum.repos.d/docker-main.repo
[root@h103 ~]# cat /etc/yum.repos.d/docker-main.repo 
[docker-main-repo]
name=Docker main Repository
baseurl=https://yum.dockerproject.org/repo/main/centos/7
enabled=1
gpgcheck=1
gpgkey=https://yum.dockerproject.org/gpg
[root@h103 ~]# 

创建docker组

  • Docker不是使用的TCP端口,而是使用的Unix Socket来监听请求
  • 默认情况下Docker Socket的拥有者是root
  • Docker的进程一般也是以root的身份运行
  • 用户如果想调用得使用sudo
为了避免只能使用sudo来调用Docker,在软件安装过程中自动创建了docker组,并且在docker进程启动时赋权给了这个组的用户以docker socket的读写权限,所以只用将管理用户加入到docker组,就可以对docker进行使用了
Note: 使用docker group的方式解决了不用sudo的问题,但仍然有很大的安全隐患,因为它的操作依然相当于root,对运行在容器中的其它镜像实例有破坏潜力,相关详情可以参考 Docker Daemon Attack Surface
普通用户没有docker操作权限
[root@h103 ~]# id cc
uid=1000(cc) gid=1000(cc) groups=1000(cc)
[root@h103 ~]# su - cc
Last login: Tue Jan 19 23:00:16 CST 2016 on pts/1
[cc@h103 ~]$ docker run hello-world
Cannot connect to the Docker daemon. Is the docker daemon running on this host?
[cc@h103 ~]$ 
将普通用户添加到docker组
[root@h103 ~]# usermod -aG docker cc
[root@h103 ~]# id cc
uid=1000(cc) gid=1000(cc) groups=1000(cc),993(docker)
[root@h103 ~]#
再次尝试使用普通用户的身份执行docker命令
[root@h103 ~]# su - cc
Last login: Tue Jan 19 23:23:04 CST 2016 on pts/1
[cc@h103 ~]$ docker run hello-world

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 Hub account:
 https://hub.docker.com

For more examples and ideas, visit:
 https://docs.docker.com/userguide/

[cc@h103 ~]$ 

设定开机启动

[root@h103 ~]# systemctl list-unit-files| grep docker
docker.service                              disabled
docker.socket                               disabled
[root@h103 ~]# systemctl enable docker.service
Created symlink from /etc/systemd/system/multi-user.target.wants/docker.service to /usr/lib/systemd/system/docker.service.
[root@h103 ~]# systemctl list-unit-files | grep docker
docker.service                              enabled 
docker.socket                               disabled
[root@h103 ~]# 
Tip: CentOS 7 里服务的开机启动也是由 systemctl 来进行管理了
我们看到还有一个 docker.socket 不是开机启动的,它和 docker.socket 的关系如下
[root@h103 ~]# systemctl list-dependencies docker.service
docker.service
● ├─docker.socket
● ├─system.slice
● └─basic.target
●   ├─firewalld.service
●   ├─microcode.service
●   ├─rhel-autorelabel-mark.service
●   ├─rhel-autorelabel.service
●   ├─rhel-configure.service
●   ├─rhel-dmesg.service
●   ├─rhel-loadmodules.service
●   ├─paths.target
●   ├─slices.target
●   │ ├─-.slice
●   │ └─system.slice
●   ├─sockets.target
●   │ ├─dbus.socket
●   │ ├─dm-event.socket
●   │ ├─iscsid.socket
●   │ ├─iscsiuio.socket
●   │ ├─rpcbind.socket
●   │ ├─systemd-initctl.socket
●   │ ├─systemd-journald.socket
●   │ ├─systemd-shutdownd.socket
●   │ ├─systemd-udevd-control.socket
●   │ └─systemd-udevd-kernel.socket
[root@h103 ~]# 
[root@h103 ~]# cat /usr/lib/systemd/system/docker.service
[Unit]
Description=Docker Application Container Engine
Documentation=https://docs.docker.com
After=network.target docker.socket
Requires=docker.socket

[Service]
Type=notify
ExecStart=/usr/bin/docker daemon -H fd://
MountFlags=slave
LimitNOFILE=1048576
LimitNPROC=1048576
LimitCORE=infinity

[Install]
WantedBy=multi-user.target
[root@h103 ~]# cat /usr/lib/systemd/system/docker.socket
[Unit]
Description=Docker Socket for the API
PartOf=docker.service

[Socket]
ListenStream=/var/run/docker.sock
SocketMode=0660
SocketUser=root
SocketGroup=docker

[Install]
WantedBy=sockets.target
[root@h103 ~]# ll /var/run/docker.sock
srw-rw---- 1 root docker 0 Jan 20 11:21 /var/run/docker.sock
[root@h103 ~]# 
可见 docker.service 是依赖于 docker.socket 的,但是并不必要开启
Tip: 其实上面的步骤完成,就已经能保证docker会开机启动,原因是它依赖的 docker.socket 虽然本身设定为不要开机启动,但开机时会被systemctl检查然后触发启动以支持 docker.service 的运行
可以用上面方法也将 docker.socket 设为开机启动(但这一步不是非常必要)
[root@h103 ~]# systemctl list-unit-files| grep docker
docker.service                              enabled 
docker.socket                               disabled
[root@h103 ~]# systemctl enable docker.socket
Created symlink from /etc/systemd/system/sockets.target.wants/docker.socket to /usr/lib/systemd/system/docker.socket.
[root@h103 ~]# systemctl list-unit-files| grep docker
docker.service                              enabled 
docker.socket                               enabled 
[root@h103 ~]# 

卸载Docker

列出安装包

[root@h103 ~]# yum list installed | grep docker
docker-engine.x86_64                  1.9.1-1.el7.centos             @dockerrepo
docker-engine-selinux.noarch          1.9.1-1.el7.centos             @dockerrepo
[root@h103 ~]# 

删除软件包

[root@h103 ~]# yum -y remove docker-engine.x86_64
Loaded plugins: fastestmirror, langpacks
Resolving Dependencies
--> Running transaction check
---> Package docker-engine.x86_64 0:1.9.1-1.el7.centos will be erased
--> Finished Dependency Resolution

Dependencies Resolved

======================================================================================================================================
 Package                         Arch                     Version                                 Repository                     Size
======================================================================================================================================
Removing:
 docker-engine                   x86_64                   1.9.1-1.el7.centos                      @dockerrepo                    36 M

Transaction Summary
======================================================================================================================================
Remove  1 Package

Installed size: 36 M
Downloading packages:
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Erasing    : docker-engine-1.9.1-1.el7.centos.x86_64                                                                            1/1 
  Verifying  : docker-engine-1.9.1-1.el7.centos.x86_64                                                                            1/1 

Removed:
  docker-engine.x86_64 0:1.9.1-1.el7.centos                                                                                           

Complete!
[root@h103 ~]# 
这种情况下,只删除了软件包,但是没有删除镜像,容器,卷和自己创建的本地配置

删除数据

[root@h103 ~]# ll /var/lib/docker
total 16
drwx------ 3 root root   77 Jan 19 17:37 containers
drwx------ 5 root root   50 Jan 19 17:37 devicemapper
drwx------ 5 root root 4096 Jan 19 17:37 graph
-rw-r--r-- 1 root root 5120 Jan 19 17:37 linkgraph.db
drwxr-x--- 3 root root   18 Jan 19 17:20 network
-rw------- 1 root root  110 Jan 19 17:37 repositories-devicemapper
drwx------ 2 root root    6 Jan 19 17:37 tmp
drwx------ 2 root root    6 Jan 19 17:20 trust
drwx------ 2 root root    6 Jan 19 17:20 volumes
[root@h103 ~]# du -sh /var/lib/docker
61M /var/lib/docker
[root@h103 ~]# rm -rf /var/lib/docker
[root@h103 ~]# du -sh /var/lib/docker
du: cannot access ‘/var/lib/docker’: No such file or directory
[root@h103 ~]# 
其它配置文件可以根据具体项目进行定位和清理

命令汇总

  • hostnamectl
  • yum update
  • tee /etc/yum.repos.d/docker.repo <<-'EOF'
  • cat /etc/yum.repos.d/docker.repo
  • yum install docker-engine
  • service docker start
  • systemctl status docker.service
  • rpm -qi systemd
  • docker run hello-world
  • curl -sSL https://get.docker.com/ | sh
  • cat /etc/yum.repos.d/docker-main.repo
  • usermod -aG docker cc
  • id cc
  • su - cc
  • docker run hello-world
  • systemctl enable docker.service
  • systemctl list-unit-files | grep docker
  • systemctl list-dependencies docker.service
  • cat /usr/lib/systemd/system/docker.service
  • cat /usr/lib/systemd/system/docker.socket
  • ll /var/run/docker.sock
  • systemctl enable docker.socket
  • yum list installed | grep docker
  • yum -y remove docker-engine.x86_64
  • rm -rf /var/lib/docker

systemctl用法小结

CLI COMMENT
systemctl is-enabled *.service 查询服务是否开机启动
systemctl enable *.service 开机运行服务
systemctl disable *.service 取消开机运行
systemctl start *.service 启动服务
systemctl stop *.service 停止服务
systemctl restart *.service 重启服务
systemctl reload *.service 重新加载服务配置文件
systemctl status *.service 查询服务运行状态
systemctl –failed 显示启动失败的服务
systemctl list-unit-files 查看所有服务及开机启动状态
systemctl list-dependencies *.service 查看服务依赖
--------------------------------------

docker registry

本地Registry服务的部署与销毁,远程Registry服务的部署与销毁,Docker卷,DockerTLS加密,基本认证与访问控制, 使用Compose构建容器,docker-compose.yml的编辑与注意事项,Registry部署过程中的常见问题处理.

前言

Docker 是围绕 Images 进行管理的:


构建一个私有的镜像仓库可以更高效地管理镜像
Docker 中,镜像仓库叫 Registry
A registry is a storage and content delivery system, holding named Docker images, available in different tagged versions.
Registry 是开源的,高弹性的,可以更为容易地对生产测试环境里的镜像进行定制化管理
The Registry is a stateless, highly scalable server side application that stores and lets you distribute Docker images. The Registry is open-source, under the permissive Apache license.
这里分享一下 Docker Registry 的相关基础,详细可以参阅 官方文档
Tip: 当前的最新版本为 Docker 1.10 Released on January 15, 2016

概要


依赖

Registry 要求构建在不小于 1.6.0 版本的 Docker 引擎上
The Registry is compatible with Docker engine version 1.6.0 or higher

Registry的创建与销毁

创建运行Registry

[root@h103 ~]# docker run -d -p 5000:5000 --name registry registry:2
Unable to find image 'registry:2' locally
2: Pulling from library/registry
fcee8bcfe180: Pull complete 
4cdc0cbc1936: Pull complete 
d9e545b90db8: Pull complete 
c4bea91afef3: Pull complete 
d03a562198ae: Pull complete 
d2e8bfe6f2bc: Pull complete 
51d207c7259b: Pull complete 
7148a81f93cb: Pull complete 
b239a09153bd: Pull complete 
8f1214c20b01: Pull complete 
683f9cd9cf88: Pull complete 
Digest: sha256:a842b52833778977f7b4466b90cc829e0f9aae725aebe3e32a5a6c407acd2a03
Status: Downloaded newer image for registry:2
7716d7899161a529780b55a51b541953275f0d63bb97f9630b2edab26e1d556f
[root@h103 ~]# echo $?
0
[root@h103 ~]# 

从Docker Hub拉取镜像

[root@h103 ~]# docker pull ubuntu
Using default tag: latest
latest: Pulling from library/ubuntu
92ec6d044cb3: Verifying Checksum 
2ef91804894a: Download complete 
f80999a1f330: Download complete 
6cc0fc2a5ee3: Download complete 
Pulling repository docker.io/library/ubuntu
8693db7e8a00: Download complete 
f15ce52fc004: Download complete 
c4fae638e7ce: Download complete 
a4c5be5b6e59: Download complete 
Status: Downloaded newer image for ubuntu:latest
docker.io/library/ubuntu: this image was pulled from a legacy registry.  Important: This registry version will not be supported in future versions of docker.
[root@h103 ~]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
ubuntu              latest              8693db7e8a00        9 hours ago         187.9 MB
registry            2                   683f9cd9cf88        2 weeks ago         224.5 MB
hello-world         latest              0a6ba66e537a        3 months ago        960 B
[root@h103 ~]# 

镜像打标

[root@h103 ~]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
ubuntu              latest              8693db7e8a00        9 hours ago         187.9 MB
registry            2                   683f9cd9cf88        2 weeks ago         224.5 MB
hello-world         latest              0a6ba66e537a        3 months ago        960 B 
[root@h103 ~]# docker tag ubuntu localhost:5000/myfirstimage 
[root@h103 ~]# docker images
REPOSITORY                    TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
ubuntu                        latest              8693db7e8a00        9 hours ago         187.9 MB
localhost:5000/myfirstimage   latest              8693db7e8a00        9 hours ago         187.9 MB
registry                      2                   683f9cd9cf88        2 weeks ago         224.5 MB
hello-world                   latest              0a6ba66e537a        3 months ago        960 B
[root@h103 ~]#

推送镜像到Registry

[root@h103 ~]# docker push localhost:5000/myfirstimage 
The push refers to a repository [localhost:5000/myfirstimage] (len: 1)
8693db7e8a00: Pushed 
a4c5be5b6e59: Pushed 
c4fae638e7ce: Pushed 
f15ce52fc004: Pushed 
latest: digest: sha256:a27637294694a32300c5a9b94c9078709ec75216dd875fbdbc89acb0eb803401 size: 6806
[root@h103 ~]# 

从Registry拉取镜像

[root@h103 ~]# docker pull localhost:5000/myfirstimage
Using default tag: latest
latest: Pulling from myfirstimage
Digest: sha256:a27637294694a32300c5a9b94c9078709ec75216dd875fbdbc89acb0eb803401
Status: Image is up to date for localhost:5000/myfirstimage:latest
[root@h103 ~]# echo $?
0
[root@h103 ~]# 

销毁Registry

registry和其它实例没有任何区别,使用stop然后rm就可以便捷地进行销毁
[root@h103 ~]# docker  ps -a 
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                    NAME
7716d7899161        registry:2          "/bin/registry /etc/d"   22 hours ago        Up 2 minutes        0.0.0.0:5000->5000/tcp   regi
[root@h103 ~]# docker stop 7716d7899161
7716d7899161
[root@h103 ~]# docker  ps -a 
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                     PORTS               NA
7716d7899161        registry:2          "/bin/registry /etc/d"   22 hours ago        Exited (2) 1 seconds ago                       re
[root@h103 ~]# docker rm 7716d7899161
7716d7899161
[root@h103 ~]# docker  ps -a 
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
[root@h103 ~]# 

部署本地Registry服务

[root@h103 ~]# docker run -d -p 5000:5000 --restart=always --name registry registry:2
4352b16f2582ed0478f3380be5ab4a65487d7adf1698c66f365881e3aefdab68
[root@h103 ~]# docker ps -a 
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                    NAMES
4352b16f2582        registry:2          "/bin/registry /etc/d"   7 seconds ago       Up 5 seconds        0.0.0.0:5000->5000/tcp   registry
[root@h103 ~]# docker pull ubuntu &&  docker tag ubuntu localhost:5000/ubuntu
Using default tag: latest
Pulling repository docker.io/library/ubuntu
8693db7e8a00: Download complete 
8693db7e8a00: Pulling image (latest) from docker.io/library/ubuntu 
f15ce52fc004: Download complete 
c4fae638e7ce: Download complete 
Status: Image is up to date for ubuntu:latest
docker.io/library/ubuntu: this image was pulled from a legacy registry.  Important: This registry version will not be supported in future versions of docker.
[root@h103 ~]# echo $?
0
[root@h103 ~]# docker images
REPOSITORY                    TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
localhost:5000/myfirstimage   latest              8693db7e8a00        30 hours ago        187.9 MB
ubuntu                        latest              8693db7e8a00        30 hours ago        187.9 MB
localhost:5000/ubuntu         latest              8693db7e8a00        30 hours ago        187.9 MB
jenkins                       latest              fc39417bd5fb        12 days ago         708.1 MB
registry                      2                   683f9cd9cf88        2 weeks ago         224.5 MB
hello-world                   latest              0a6ba66e537a        3 months ago        960 B
[root@h103 ~]# docker push localhost:5000/ubuntu 
The push refers to a repository [localhost:5000/ubuntu] (len: 1)
8693db7e8a00: Pushed 
a4c5be5b6e59: Pushed 
c4fae638e7ce: Pushed 
f15ce52fc004: Pushed 
latest: digest: sha256:45d78ef16a9e6199ffbbc78f71c2c6ef6647f3be6b9721fe3f1b08d6e3fcf6b3 size: 6800
[root@h103 ~]# 
[root@h103 ~]# docker pull localhost:5000/ubuntu
Using default tag: latest
latest: Pulling from ubuntu
Digest: sha256:45d78ef16a9e6199ffbbc78f71c2c6ef6647f3be6b9721fe3f1b08d6e3fcf6b3
Status: Image is up to date for localhost:5000/ubuntu:latest
[root@h103 ~]# docker images
REPOSITORY                    TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
localhost:5000/myfirstimage   latest              8693db7e8a00        31 hours ago        187.9 MB
ubuntu                        latest              8693db7e8a00        31 hours ago        187.9 MB
localhost:5000/ubuntu         latest              8693db7e8a00        31 hours ago        187.9 MB
jenkins                       latest              fc39417bd5fb        12 days ago         708.1 MB
registry                      2                   683f9cd9cf88        2 weeks ago         224.5 MB
hello-world                   latest              0a6ba66e537a        3 months ago        960 B
[root@h103 ~]# docker ps -a 
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                    NAMES
4352b16f2582        registry:2          "/bin/registry /etc/d"   28 minutes ago      Up 28 minutes       0.0.0.0:5000->5000/tcp   registry
[root@h103 ~]# docker stop registry && docker rm -v registry
registry
registry
[root@h103 ~]# 

存储

默认情况下,registry 中的数据是以docker卷的形式存在于本地文件系统
可以使用 -v 的参数来指定一个卷的位置,从而实现对数据存储的控制
[root@h103 ~]# ls
anaconda-ks.cfg  dockerfile
[root@h103 ~]# docker ps -a 
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
[root@h103 ~]# echo `pwd`
/root
[root@h103 ~]# docker  run -d -p 5000:5000 --restart=always --name registry -v `pwd`/data:/var/lib/registry registry:2
f0e1c155d7ad1e0607e33f9f0b9ff23f1d7e4761b88070486425f3137b513540
[root@h103 ~]# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                    NAMES
f0e1c155d7ad        registry:2          "/bin/registry /etc/d"   9 seconds ago       Up 6 seconds        0.0.0.0:5000->5000/tcp   registry
[root@h103 ~]# ls
anaconda-ks.cfg  data  dockerfile
[root@h103 ~]# cd data/
[root@h103 data]# ls
[root@h103 data]# cd ..
[root@h103 ~]# docker push localhost:5000/ubuntu
The push refers to a repository [localhost:5000/ubuntu] (len: 1)
8693db7e8a00: Pushed 
a4c5be5b6e59: Pushed 
c4fae638e7ce: Pushed 
f15ce52fc004: Pushed 
latest: digest: sha256:45d78ef16a9e6199ffbbc78f71c2c6ef6647f3be6b9721fe3f1b08d6e3fcf6b3 size: 6800
[root@h103 ~]# 
[root@h103 ~]# tree data/
data/
└── docker
    └── registry
        └── v2
            ├── blobs
            │   └── sha256
            │       ├── 27
            │       │   └── 2796840645a7bf9739e3859ba390d8adfbfa9bf8ddbce09feb875a1840df7f38
            │       │       └── data
            │       ├── 3b
            │       │   └── 3b52deaaf0edb8a0282a08dd9c9e25da2050a75739b832ecc6e29941394933a6
            │       │       └── data
            │       ├── 45
            │       │   └── 45d78ef16a9e6199ffbbc78f71c2c6ef6647f3be6b9721fe3f1b08d6e3fcf6b3
            │       │       └── data
            │       ├── 4b
            │       │   └── 4bd501fad6defc3af5638b82f7d760f0dc2f2c5f1bcd2cbfd59607b1631bc679
            │       │       └── data
            │       ├── 83
            │       │   └── 8387d9ff0016d004777e511a55e21672e4b6de49e32db2544b8ac0e2ee01d5ed
            │       │       └── data
            │       └── a3
            │           └── a3ed95caeb02ffe68cdd9fd84406680ae93d633cb16422d00e8a7c22955b46d4
            │               └── data
            └── repositories
                └── ubuntu
                    ├── _layers
                    │   └── sha256
                    │       ├── 3b52deaaf0edb8a0282a08dd9c9e25da2050a75739b832ecc6e29941394933a6
                    │       │   └── link
                    │       ├── 4bd501fad6defc3af5638b82f7d760f0dc2f2c5f1bcd2cbfd59607b1631bc679
                    │       │   └── link
                    │       ├── 8387d9ff0016d004777e511a55e21672e4b6de49e32db2544b8ac0e2ee01d5ed
                    │       │   └── link
                    │       └── a3ed95caeb02ffe68cdd9fd84406680ae93d633cb16422d00e8a7c22955b46d4
                    │           └── link
                    ├── _manifests
                    │   ├── revisions
                    │   │   └── sha256
                    │   │       └── 45d78ef16a9e6199ffbbc78f71c2c6ef6647f3be6b9721fe3f1b08d6e3fcf6b3
                    │   │           ├── link
                    │   │           └── signatures
                    │   │               └── sha256
                    │   │                   └── 2796840645a7bf9739e3859ba390d8adfbfa9bf8ddbce09feb875a1840df7f38
                    │   │                       └── link
                    │   └── tags
                    │       └── latest
                    │           ├── current
                    │           │   └── link
                    │           └── index
                    │               └── sha256
                    │                   └── 45d78ef16a9e6199ffbbc78f71c2c6ef6647f3be6b9721fe3f1b08d6e3fcf6b3
                    │                       └── link
                    └── _uploads

39 directories, 14 files
[root@h103 ~]# 

部署远程Registry服务

创建自签名证书

[root@h104 ~]# cd certs/
[root@h104 certs]# openssl genrsa -out docker.key 2048
Generating RSA private key, 2048 bit long modulus
..............................................................................+++
................................................................................................+++
e is 65537 (0x10001)
[root@h104 certs]# openssl req -new -key docker.key -out docker.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) []:Shanghai
Locality Name (eg, city) [Default City]:Shanghai
Organization Name (eg, company) [Default Company Ltd]:docker
Organizational Unit Name (eg, section) []:docker         
Common Name (eg, your name or your server's hostname) []:docker-registry
Email Address []:ok@docker.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
[root@h104 certs]# openssl x509 -req -days 365 -in docker.csr -signkey docker.key -out docker.crt
Signature ok
subject=/C=CN/ST=Shanghai/L=Shanghai/O=docker/OU=docker/CN=docker-registry/emailAddress=ok@docker.com
Getting Private key
[root@h104 certs]# ll
total 12
-rw-r--r-- 1 root root 1306 Jan 21 22:04 docker.crt
-rw-r--r-- 1 root root 1058 Jan 21 22:04 docker.csr
-rw-r--r-- 1 root root 1675 Jan 21 22:02 docker.key
[root@h104 certs]# chmod 600 * 
[root@h104 certs]# ll
total 12
-rw------- 1 root root 1306 Jan 21 22:04 docker.crt
-rw------- 1 root root 1058 Jan 21 22:04 docker.csr
-rw------- 1 root root 1675 Jan 21 22:02 docker.key
[root@h104 certs]# cd ..
[root@h104 ~]# 

运行Registry

[root@h104 ~]# docker ps -a 
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
[root@h104 ~]# ls
anaconda-ks.cfg  certs  dockerfile
[root@h104 ~]# docker run -d -p 5000:5000 --restart=always --name registry  -v `pwd`/data:/var/lib/registry  -v `pwd`/certs:/certs -e REGISTRY_HTTP_TLS_CERTIFICATE=/certs/docker.crt -e REGISTRY_HTTP_TLS_KEY=/certs/docker.key registry:2
b578e321f33f6f2a0c34340b35239d1ce724c4523f3b2266bc01239658fc3f46
[root@h104 ~]# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                    NAMES
b578e321f33f        registry:2          "/bin/registry /etc/d"   6 seconds ago       Up 5 seconds        0.0.0.0:5000->5000/tcp   registry
[root@h104 ~]#

尝试push一个镜像

先tag一些镜像出来
其实就是将本地的镜像作一些别名(链接)
[root@h103 ~]# docker tag ubuntu 192.168.100.104:5000/ubuntu
[root@h103 ~]# docker tag ubuntu h104:5000/ubuntu
[root@h103 ~]# docker tag ubuntu docker-registry:5000/ubuntu 
[root@h103 ~]# docker images
REPOSITORY                    TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
192.168.100.104:5000/ubuntu   latest              8693db7e8a00        39 hours ago        187.9 MB
h104:5000/ubuntu              latest              8693db7e8a00        39 hours ago        187.9 MB
localhost:5000/myfirstimage   latest              8693db7e8a00        39 hours ago        187.9 MB
localhost:5000/ubuntu         latest              8693db7e8a00        39 hours ago        187.9 MB
docker:5000/ubuntu            latest              8693db7e8a00        39 hours ago        187.9 MB
h103:5000/ubuntu              latest              8693db7e8a00        39 hours ago        187.9 MB
ubuntu                        latest              8693db7e8a00        39 hours ago        187.9 MB
docker-registry:5000/ubuntu   latest              8693db7e8a00        39 hours ago        187.9 MB
jenkins                       latest              fc39417bd5fb        12 days ago         708.1 MB
registry                      2                   683f9cd9cf88        2 weeks ago         224.5 MB
hello-world                   latest              0a6ba66e537a        3 months ago        960 B
[root@h103 ~]#
再次尝试push

报错1

[root@h103 ~]# docker push h104:5000/ubuntu
The push refers to a repository [h104:5000/ubuntu] (len: 1)
unable to ping registry endpoint https://h104:5000/v0/
v2 ping attempt failed with error: Get https://h104:5000/v2/: tls: oversized record received with length 20527
 v1 ping attempt failed with error: Get https://h104:5000/v1/_ping: tls: oversized record received with length 20527
[root@h103 ~]# 
根据官网的解释和方法,我没有成功处理
官网的解释如下:
原因是没有加入证书或证书不被信任,解决办法是从证书入手
有三种方式可以解决:
  • 1.买一个SSL证书
  • 2.配置docker忽视指定registry的安全
DOCKER_OPTS="--insecure-registry myregistrydomain.com:5000" ,然后重启客户端
  • 3.导入自签名证书,让docker客户端单向相信这个registry,然后重启客户端
  • 解决办法:
最后的解决办法是将registry删除重建,问题就没再出现了
  • 可能原因:
所以,我猜测可能是(当时)我构建这个registry的过程中环境变量配置错误了

报错234

[root@h103 ~]# docker push 192.168.100.104:5000/ubuntu
The push refers to a repository [192.168.100.104:5000/ubuntu] (len: 1)
unable to ping registry endpoint https://192.168.100.104:5000/v0/
v2 ping attempt failed with error: Get https://192.168.100.104:5000/v2/: x509: cannot validate certificate for 192.168.100.104 because it doesn't contain any IP SANs
 v1 ping attempt failed with error: Get https://192.168.100.104:5000/v1/_ping: x509: cannot validate certificate for 192.168.100.104 because it doesn't contain any IP SANs
[root@h103 ~]#
原因是证书中没有指定IP
[root@h103 ~]# docker push h104:5000/ubuntu
The push refers to a repository [h104:5000/ubuntu] (len: 1)
unable to ping registry endpoint https://h104:5000/v0/
v2 ping attempt failed with error: Get https://h104:5000/v2/: x509: certificate is valid for docker-registry, not h104
 v1 ping attempt failed with error: Get https://h104:5000/v1/_ping: x509: certificate is valid for docker-registry, not h104
[root@h103 ~]#
原因是证书中指定的主机名为 docker-registry 而不是 h104
[root@h103 ~]# vim /etc/hosts
[root@h103 ~]# grep docker-registry  /etc/hosts
192.168.100.104  h104 docker-registry
[root@h103 ~]# docker push docker-registry:5000/ubuntu
The push refers to a repository [docker-registry:5000/ubuntu] (len: 1)
unable to ping registry endpoint https://docker-registry:5000/v0/
v2 ping attempt failed with error: Get https://docker-registry:5000/v2/: x509: certificate signed by unknown authority
 v1 ping attempt failed with error: Get https://docker-registry:5000/v1/_ping: x509: certificate signed by unknown authority
[root@h103 ~]# 
原因是证书不被信任(自签名证书)
  • 解决办法一:
将证书内容导入受信列表,重启docker客户端
[root@h103 ~]# ll /etc/pki/tls/certs/ca-bundle.crt
lrwxrwxrwx 1 root root 49 Jan 19 16:30 /etc/pki/tls/certs/ca-bundle.crt -> /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem
[root@h103 ~]# ll /etc/pki/ca-trust/extracted/pem/
total 692
-r--r--r-- 1 root root 217510 Jan 19 16:30 email-ca-bundle.pem
-r--r--r-- 1 root root 211626 Jan 19 16:30 objsign-ca-bundle.pem
-rw-r--r-- 1 root root    897 Apr 23  2015 README
-r--r--r-- 1 root root 267983 Jan 21 21:21 tls-ca-bundle.pem
[root@h103 ~]# scp root@h104:/root/certs/docker.crt /etc/pki/ca-trust/extracted/pem/
root@h104's password: 
docker.crt                                                                                          100% 1306     1.3KB/s   00:00    
[root@h103 ~]# ll /etc/pki/ca-trust/extracted/pem/
total 696
-rw------- 1 root root   1306 Jan 21 23:24 docker.crt
-r--r--r-- 1 root root 217510 Jan 19 16:30 email-ca-bundle.pem
-r--r--r-- 1 root root 211626 Jan 19 16:30 objsign-ca-bundle.pem
-rw-r--r-- 1 root root    897 Apr 23  2015 README
-r--r--r-- 1 root root 267983 Jan 21 21:21 tls-ca-bundle.pem
[root@h103 ~]# cat /etc/pki/ca-trust/extracted/pem/docker.crt >> /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem
[root@h103 ~]# docker push docker-registry:5000/ubuntu
The push refers to a repository [docker-registry:5000/ubuntu] (len: 1)
unable to ping registry endpoint https://docker-registry:5000/v0/
v2 ping attempt failed with error: Get https://docker-registry:5000/v2/: x509: certificate signed by unknown authority
 v1 ping attempt failed with error: Get https://docker-registry:5000/v1/_ping: x509: certificate signed by unknown authority
[root@h103 ~]# systemctl stop docker && systemctl start docker
[root@h103 ~]# docker push docker-registry:5000/ubuntu
The push refers to a repository [docker-registry:5000/ubuntu] (len: 1)
8693db7e8a00: Pushed 
a4c5be5b6e59: Pushed 
c4fae638e7ce: Pushed 
f15ce52fc004: Pushed 
latest: digest: sha256:45d78ef16a9e6199ffbbc78f71c2c6ef6647f3be6b9721fe3f1b08d6e3fcf6b3 size: 6800
[root@h103 ~]# docker pull  docker-registry:5000/ubuntu
Using default tag: latest
latest: Pulling from ubuntu
Digest: sha256:45d78ef16a9e6199ffbbc78f71c2c6ef6647f3be6b9721fe3f1b08d6e3fcf6b3
Status: Image is up to date for docker-registry:5000/ubuntu:latest
[root@h103 ~]# 
Note: 一定要重启客户端,否则无效
  • 解决办法二:
[root@h103 ~]# ll /etc/pki/ca-trust/source/anchors/
total 0
[root@h103 ~]# scp root@h104:/root/certs/docker.crt  /etc/pki/ca-trust/source/anchors/
root@h104's password: 
docker.crt                                                                                                            100% 1306     1.3KB/s   00:00    
[root@h103 ~]# ll /etc/pki/ca-trust/source/anchors/
total 4
-rw------- 1 root root 1306 Jan 21 23:49 docker.crt
[root@h103 ~]# docker push docker-registry:5000/ubuntu
The push refers to a repository [docker-registry:5000/ubuntu] (len: 1)
unable to ping registry endpoint https://docker-registry:5000/v0/
v2 ping attempt failed with error: Get https://docker-registry:5000/v2/: x509: certificate signed by unknown authority
 v1 ping attempt failed with error: Get https://docker-registry:5000/v1/_ping: x509: certificate signed by unknown authority
[root@h103 ~]# systemctl stop docker && systemctl start docker 
[root@h103 ~]# docker push docker-registry:5000/ubuntu
The push refers to a repository [docker-registry:5000/ubuntu] (len: 1)
unable to ping registry endpoint https://docker-registry:5000/v0/
v2 ping attempt failed with error: Get https://docker-registry:5000/v2/: x509: certificate signed by unknown authority
 v1 ping attempt failed with error: Get https://docker-registry:5000/v1/_ping: x509: certificate signed by unknown authority
[root@h103 ~]# 
[root@h103 ~]# update-ca-trust 
[root@h103 ~]# docker push docker-registry:5000/ubuntu
The push refers to a repository [docker-registry:5000/ubuntu] (len: 1)
unable to ping registry endpoint https://docker-registry:5000/v0/
v2 ping attempt failed with error: Get https://docker-registry:5000/v2/: x509: certificate signed by unknown authority
 v1 ping attempt failed with error: Get https://docker-registry:5000/v1/_ping: x509: certificate signed by unknown authority
[root@h103 ~]# systemctl stop docker && systemctl start docker 
[root@h103 ~]# docker push docker-registry:5000/ubuntu
The push refers to a repository [docker-registry:5000/ubuntu] (len: 1)
8693db7e8a00: Pushed 
a4c5be5b6e59: Pushed 
c4fae638e7ce: Pushed 
f15ce52fc004: Pushed 
latest: digest: sha256:45d78ef16a9e6199ffbbc78f71c2c6ef6647f3be6b9721fe3f1b08d6e3fcf6b3 size: 6800
[root@h103 ~]# docker pull docker-registry:5000/ubuntu
Using default tag: latest
latest: Pulling from ubuntu
Digest: sha256:45d78ef16a9e6199ffbbc78f71c2c6ef6647f3be6b9721fe3f1b08d6e3fcf6b3
Status: Image is up to date for docker-registry:5000/ubuntu:latest
[root@h103 ~]# 
为什么这么啰嗦地反复测试,是为了说明以下三步必须且只能按照以下步骤完成,否则无法生效
  • 拷贝自签证书到 /etc/pki/ca-trust/source/anchors/ 中(只能是这个目录,其它不行)
  • 执行 update-ca-trust 刷新受信列表
  • 重启docker客户端
Note: Common Name 要设置得和库(访问域名)的名字一样否则检查证书时会报错,客户端配置完证书要重启才能生效

其它报错

类似于下面两种
[root@h104 ~]# docker push docker:5000/ubuntu 
The push refers to a repository [docker:5000/ubuntu] (len: 1)
unable to ping registry endpoint https://docker:5000/v0/
v2 ping attempt failed with error: Get https://docker:5000/v2/: dial tcp 192.168.100.103:5000: no route to host
 v1 ping attempt failed with error: Get https://docker:5000/v1/_ping: dial tcp 192.168.100.103:5000: no route to host
[root@h104 ~]# 
[root@h104 ~]# docker push docker:5000/ubuntu 
The push refers to a repository [docker:5000/ubuntu] (len: 1)
unable to ping registry endpoint https://docker:5000/v0/
v2 ping attempt failed with error: Get https://docker:5000/v2/: dial tcp 192.168.100.103:5000: i/o timeout
 v1 ping attempt failed with error: Get https://docker:5000/v1/_ping: dial tcp 192.168.100.103:5000: i/o timeout
[root@h104 ~]# 
  • 故障原因
一般而言,防火墙会在docker服务之前打开,docker服务启动后会在iptables中应用一些策略
[root@docker ~]# systemctl list-dependencies docker.service | head -n 10
docker.service
● ├─docker.socket
● ├─system.slice
● └─basic.target
●   ├─firewalld.service
●   ├─microcode.service
●   ├─rhel-autorelabel-mark.service
●   ├─rhel-autorelabel.service
●   ├─rhel-configure.service
●   ├─rhel-dmesg.service
[root@docker ~]# 
[root@docker ~]# iptables -L -nv | grep -i docker
  288 46767 DOCKER     all  --  *      docker0  0.0.0.0/0            0.0.0.0/0           
    0     0 ACCEPT     all  --  *      docker0  0.0.0.0/0            0.0.0.0/0            ctstate RELATED,ESTABLISHED
  224 45545 ACCEPT     all  --  docker0 !docker0  0.0.0.0/0            0.0.0.0/0           
    0     0 ACCEPT     all  --  docker0 docker0  0.0.0.0/0            0.0.0.0/0           
Chain DOCKER (1 references)
  288 46767 ACCEPT     tcp  --  !docker0 docker0  0.0.0.0/0            172.17.0.2           tcp dpt:5000
[root@docker ~]# 
如果单独重载iptables服务,docker这边的配置会丢失
[root@docker ~]# firewall-cmd --reload
success
[root@docker ~]# iptables -L -nv | grep -i docker
    0     0 ACCEPT     all  --  *      docker0  0.0.0.0/0            0.0.0.0/0            ctstate RELATED,ESTABLISHED
    0     0 ACCEPT     all  --  docker0 !docker0  0.0.0.0/0            0.0.0.0/0           
    0     0 ACCEPT     all  --  docker0 docker0  0.0.0.0/0            0.0.0.0/0           
[root@docker ~]# 
从而导致网络不可达或相关信息的报错
[root@h104 ~]# docker push docker:5000/ubuntu 
The push refers to a repository [docker:5000/ubuntu] (len: 1)
unable to ping registry endpoint https://docker:5000/v0/
v2 ping attempt failed with error: Get https://docker:5000/v2/: dial tcp 192.168.100.103:5000: no route to host
 v1 ping attempt failed with error: Get https://docker:5000/v1/_ping: dial tcp 192.168.100.103:5000: no route to host
[root@h104 ~]# 
  • 解决办法
就是确保在iptables服务重启后,docker服务也重启一下,以应用docker里的网络策略(最主要的是加载那条 Chain DOCKER)
[root@docker ~]# systemctl stop docker && systemctl  start docker 
[root@docker ~]# iptables -L -nv | grep -i docker 
    0     0 DOCKER     all  --  *      docker0  0.0.0.0/0            0.0.0.0/0           
    0     0 ACCEPT     all  --  *      docker0  0.0.0.0/0            0.0.0.0/0            ctstate RELATED,ESTABLISHED
    0     0 ACCEPT     all  --  docker0 !docker0  0.0.0.0/0            0.0.0.0/0           
    0     0 ACCEPT     all  --  docker0 docker0  0.0.0.0/0            0.0.0.0/0           
Chain DOCKER (1 references)
    0     0 ACCEPT     tcp  --  !docker0 docker0  0.0.0.0/0            172.17.0.2           tcp dpt:5000
[root@docker ~]# 
----------
[root@h104 ~]# docker push docker:5000/ubuntu 
The push refers to a repository [docker:5000/ubuntu] (len: 1)

8693db7e8a00: Image already exists 
a4c5be5b6e59: Image already exists 
c4fae638e7ce: Image already exists 
latest: digest: sha256:45d78ef16a9e6199ffbbc78f71c2c6ef6647f3be6b9721fe3f1b08d6e3fcf6b3 size: 6800
[root@h104 ~]# 
Tip: 由docker export出来的端口不必在主机的防火墙filter表中另外打开,因为它的数据进入了forward链中

Registry负载均衡

目前可以使用多个容器共享存储的方式来实现负载均衡
下面的三点要一样:
  • 存储空间
  • HTTP Secret 证书
  • Redis 缓存(如果有的话)

访问控制

可以使用本地基础认证在TLS加密的基础上进行更细粒度的访问控制
这个机制和http的基础认证是一样的,由于是简单密码,明文传送,所以只有ssl加密的环境中才有安全保障

创建密码文件

首先创建一个密码文件
用户名密码:testuser/testpassword
[root@docker ~]# ls
anaconda-ks.cfg  certs  dockerfile
[root@docker ~]# mkdir auth
[root@docker ~]# docker run --entrypoint htpasswd registry:2 -Bbn testuser testpassword > auth/htpasswd
[root@docker ~]# ll auth/
total 4
-rw-r--r-- 1 root root 71 Jan 22 15:46 htpasswd
[root@docker ~]# cat auth/htpasswd 
testuser:$2y$05$.NF64Yoz4W/VCfM1RrkBw.CT7ji3TbzdgBWjIH6X60MMgNFC.vIy.

[root@docker ~]#

创建一个registry

这个registry
  • 指定了卷
  • TLS加密
  • 基础认证
先清掉docker中同名的registry,然后再创建,否则会报冲突,也可以给这个registry改为其它名字
[root@docker ~]# docker run -d -p 5000:5000 --restart=always --name registry \
> -v `pwd`/data:/data \
> -v `pwd`/certs:/certs \
> -v `pwd`/auth:/auth \
> -e "REGISTRY_AUTH=htpasswd" \
> -e "REGISTRY_AUTH_HTPASSWD_REALM=Registry Realm" \
> -e "REGISTRY_AUTH_HTPASSWD_PATH=/auth/htpasswd" \
> -e "REGISTRY_HTTP_TLS_CERTIFICATE=/certs/docker.crt" \
> -e "REGISTRY_HTTP_TLS_KEY=/certs/docker.key" \
> registry:2
71de3ba937945006578d495ed09ec36ca141130e1e22b3083018b9d43a251767
[root@docker ~]# docker ps -a 
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                     PORTS                    NAMES
71de3ba93794        registry:2          "/bin/registry /etc/d"   4 seconds ago       Up 3 seconds               0.0.0.0:5000->5000/tcp   registry
3d9f0915226f        registry:2          "htpasswd -Bbn testus"   5 minutes ago       Exited (0) 5 minutes ago                            prickly_jang
27995af3fa59        registry:2          "htpasswd -Bbn testus"   2 hours ago         Exited (0) 2 hours ago                              gloomy_goldberg
[root@docker ~]#

尝试push一个镜像

[root@h104 ~]# docker push docker:5000/ubuntu 
The push refers to a repository [docker:5000/ubuntu] (len: 1)

Head https://docker:5000/v2/ubuntu/blobs/sha256:a3ed95caeb02ffe68cdd9fd84406680ae93d633cb16422d00e8a7c22955b46d4: no basic auth credentials
[root@h104 ~]#
报错是因为没有进行认证

进行认证

[root@h104 ~]# docker login docker:5000
Username: testuser
Password: 
Email: yyghdfz@163.com
WARNING: login credentials saved in /root/.docker/config.json
Login Succeeded
[root@h104 ~]# docker push docker:5000/ubuntu 
The push refers to a repository [docker:5000/ubuntu] (len: 1)
8693db7e8a00: Pushed 
a4c5be5b6e59: Pushed 
c4fae638e7ce: Pushed 
f15ce52fc004: Pushed 
latest: digest: sha256:45d78ef16a9e6199ffbbc78f71c2c6ef6647f3be6b9721fe3f1b08d6e3fcf6b3 size: 6800
[root@h104 ~]#

使用Compose构建容器

Docker Compose 是一个docker容器编排工具,可以有效完成多容器对接和组合等工作
如果命令行中输入太多参数变得不方便时,也可以使用它来进行单个容器的配置
相关详情可以参考 Docker Compose 官方说明
Overview of Docker Compose
以后有机会再进行深入研究

下载安装Compose

可以使用下面两种方法进行安装
[root@h104 ~]# curl -L https://github.com/docker/compose/releases/download/1.5.2/docker-compose-`uname -s`-`uname -m` > docker-compose
...
...
[root@h104 ~]# wget https://github.com/docker/compose/releases/download/1.5.2/docker-compose-`uname -s`-`uname -m`
...
...
[root@h104 ~]# 
下载可以参考 Install Docker Compose
Tip: 如果不翻墙,这个不到10M的文件,可以让人崩溃
4% [===>                                                                                                           ] 321,090      423B/s  eta 7h 17m 

Compose软件基础信息

[root@docker ~]# ls
anaconda-ks.cfg  auth  certs  data  docker-compose-Linux-x86_64  dockerfile
[root@docker ~]# du -sh docker-compose-Linux-x86_64 
7.6M docker-compose-Linux-x86_64
[root@docker ~]# file docker-compose-Linux-x86_64 
docker-compose-Linux-x86_64: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.32, BuildID[sha1]=853203ebc6482b8f7e218413e2d0ee3d7d39e234, stripped
[root@docker ~]# chmod +x docker-compose-Linux-x86_64 
[root@docker ~]# ./docker-compose-Linux-x86_64 version
docker-compose version 1.5.2, build 7240ff3
docker-py version: 1.5.0
CPython version: 2.7.9
OpenSSL version: OpenSSL 1.0.1e 11 Feb 2013
[root@docker ~]# ./docker-compose-Linux-x86_64 --help
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)
  --x-networking            (EXPERIMENTAL) Use new Docker networking functionality.
                            Requires Docker 1.9 or later.
  --x-network-driver DRIVER (EXPERIMENTAL) Specify a network driver (default: "bridge").
                            Requires Docker 1.9 or later.
  --verbose                 Show more output
  -v, --version             Print version and exit

Commands:
  build              Build or rebuild services
  help               Get help on a command
  kill               Kill containers
  logs               View output from containers
  pause              Pause services
  port               Print the public port for a port binding
  ps                 List containers
  pull               Pulls 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
  unpause            Unpause services
  up                 Create and start containers
  migrate-to-labels  Recreate containers to add labels
  version            Show the Docker-Compose version information
[root@docker ~]# 

编辑docker-compose.yml

[root@docker ~]# ls
anaconda-ks.cfg  auth  certs  data  docker-compose-Linux-x86_64  docker-compose.yml  dockerfile
[root@docker ~]# vim docker-compose.yml 
[root@docker ~]# cat docker-compose.yml 
registry2:
  restart:always
  image:registry:2
  ports: 
    - 5002:5002
  environment:
    REGISTRY_AUTH:htpasswd
    REGISTRY_AUTH_HTPASSWD_REALM:Registry Realm
    REGISTRY_AUTH_HTPASSWD_PATH:/auth/htpasswd
    REGISTRY_HTTP_TLS_CERTIFICATE:/certs/docker.crt
    REGISTRY_HTTP_TLS_KEY:/certs/docker.key
  volumes:
    - /root/data:/var/lib/registry
    - /root/certs:/certs
    - /root/auth:/auth
[root@docker ~]# ./docker-compose-Linux-x86_64 up -d 
ERROR: yaml.scanner.ScannerError: mapping values are not allowed here
  in "./docker-compose.yml", line 4, column 8
[root@docker ~]# 

报错1

  • 原因是 docker-compose.yml 中格式不对
  • 解决办法调整格式,加上空格
Tip: 属性后面的值与 : 之间要有空格
restart:always 是错的
restart: always 是对的

[root@docker ~]# vim docker-compose.yml 
[root@docker ~]# cat docker-compose.yml 
registry2:
  restart: always
  image: registry:2
  ports: 
    - 5002:5002
  environment:
    REGISTRY_AUTH:htpasswd
    REGISTRY_AUTH_HTPASSWD_REALM:Registry Realm
    REGISTRY_AUTH_HTPASSWD_PATH:/auth/htpasswd
    REGISTRY_HTTP_TLS_CERTIFICATE:/certs/docker.crt
    REGISTRY_HTTP_TLS_KEY:/certs/docker.key
  volumes:
    - /root/data:/var/lib/registry
    - /root/certs:/certs
    - /root/auth:/auth
[root@docker ~]# ./docker-compose-Linux-x86_64 up -d 
ERROR: Validation failed in file './docker-compose.yml', reason(s):
Service 'registry2' configuration key 'environment' contains an invalid type, it should be an object, or an array
[root@docker ~]# 

报错2

  • 原因是 docker-compose.yml 中environment部分格式不对
  • 解决办法:调整格式,加上空格
Tip: environment属性后面的值与 : 之间要有空格
REGISTRY_AUTH:htpasswd 是错的
REGISTRY_AUTH: htpasswd 是对的

[root@docker ~]# vim docker-compose.yml 
[root@docker ~]# cat docker-compose.yml 
registry2:
  restart: always
  image: registry:2
  ports: 
    - 5002:5002
  environment:
    REGISTRY_AUTH: htpasswd
    REGISTRY_AUTH_HTPASSWD_REALM: Registry Realm
    REGISTRY_AUTH_HTPASSWD_PATH: /auth/htpasswd
    REGISTRY_HTTP_TLS_CERTIFICATE: /certs/docker.crt
    REGISTRY_HTTP_TLS_KEY: /certs/docker.key
  volumes:
    - /root/data:/var/lib/registry
    - /root/certs:/certs
    - /root/auth:/auth
[root@docker ~]# ./docker-compose-Linux-x86_64 up -d 
Creating root_registry2_1
[root@docker ~]# docker ps -a 
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                   PORTS                              NAMES
e870d0a4b904        registry:2          "/bin/registry /etc/d"   7 seconds ago       Up 6 seconds             5000/tcp, 0.0.0.0:5002->5002/tcp   root_registry2_1
71de3ba93794        registry:2          "/bin/registry /etc/d"   4 hours ago         Up 4 hours               0.0.0.0:5000->5000/tcp             registry
3d9f0915226f        registry:2          "htpasswd -Bbn testus"   4 hours ago         Exited (0) 4 hours ago                                      prickly_jang
27995af3fa59        registry:2          "htpasswd -Bbn testus"   7 hours ago         Exited (0) 7 hours ago                                      gloomy_goldberg
[root@docker ~]# 
----------
[root@h104 ~]# docker push docker:5002/ubuntu
The push refers to a repository [docker:5002/ubuntu] (len: 1)
unable to ping registry endpoint https://docker:5002/v0/
v2 ping attempt failed with error: Get https://docker:5002/v2/: dial tcp 192.168.100.103:5002: connection refused
 v1 ping attempt failed with error: Get https://docker:5002/v1/_ping: dial tcp 192.168.100.103:5002: connection refused
[root@h104 ~]# nmap docker

Starting Nmap 6.40 ( http://nmap.org ) at 2016-01-22 20:13 CST
Nmap scan report for docker (192.168.100.103)
Host is up (0.00079s latency).
rDNS record for 192.168.100.103: h103
Not shown: 994 filtered ports
PORT     STATE  SERVICE
22/tcp   open   ssh
80/tcp   closed http
3306/tcp closed mysql
5000/tcp open   upnp
5002/tcp closed rfe
8080/tcp closed http-proxy
MAC Address: 00:0C:29:B6:CC:BA (VMware)

Nmap done: 1 IP address (1 host up) scanned in 5.00 seconds
[root@h104 ~]# 

报错3

  • 原因是配置中端口映射不对
  • 解决办法:调整port map 为 5002:5000
Tip: 5000/tcp, 0.0.0.0:5002->5002/tcp 意味着容器里监听了5000端口,但是主机与容器的端口映射为5002外->5002内
产生问题的根本原因就是容器里并没有监听在5002,所以无法提供服务
只要进行正确映射就可以解决问题
WRONG
        "Ports": {
            "5000/tcp": null,
            "5002/tcp": [
                {
                    "HostIp": "0.0.0.0",
                    "HostPort": "5002"
                }
            ]
        }
----------
RIGHT
        "Ports": {
            "5000/tcp": [
                {
                    "HostIp": "0.0.0.0",
                    "HostPort": "5002"
                }
            ]
        }

[root@docker ~]# docker stop e870d0a4b904 && docker rm -v e870d0a4b904
e870d0a4b904
e870d0a4b904
[root@docker ~]# vim docker-compose.yml
[root@docker ~]# cat docker-compose.yml 
registry2:
  restart: always
  image: registry:2
  ports: 
    - 5002:5000
  environment:
    REGISTRY_AUTH: htpasswd
    REGISTRY_AUTH_HTPASSWD_REALM: Registry Realm
    REGISTRY_AUTH_HTPASSWD_PATH: /auth/htpasswd
    REGISTRY_HTTP_TLS_CERTIFICATE: /certs/docker.crt
    REGISTRY_HTTP_TLS_KEY: /certs/docker.key
  volumes:
    - /root/data:/var/lib/registry
    - /root/certs:/certs
    - /root/auth:/auth
[root@docker ~]# docker ps -a 
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                   PORTS                    NAMES
71de3ba93794        registry:2          "/bin/registry /etc/d"   4 hours ago         Up 4 hours               0.0.0.0:5000->5000/tcp   registry
3d9f0915226f        registry:2          "htpasswd -Bbn testus"   4 hours ago         Exited (0) 4 hours ago                            prickly_jang
27995af3fa59        registry:2          "htpasswd -Bbn testus"   7 hours ago         Exited (0) 7 hours ago                            gloomy_goldberg
[root@docker ~]# 
[root@docker ~]# ./docker-compose-Linux-x86_64 up -d 
Creating root_registry2_1
[root@docker ~]# docker ps -a 
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                   PORTS                    NAMES
b9ef0f189068        registry:2          "/bin/registry /etc/d"   6 seconds ago       Up 4 seconds             0.0.0.0:5002->5000/tcp   root_registry2_1
71de3ba93794        registry:2          "/bin/registry /etc/d"   4 hours ago         Up 4 hours               0.0.0.0:5000->5000/tcp   registry
3d9f0915226f        registry:2          "htpasswd -Bbn testus"   4 hours ago         Exited (0) 4 hours ago                            prickly_jang
27995af3fa59        registry:2          "htpasswd -Bbn testus"   7 hours ago         Exited (0) 7 hours ago                            gloomy_goldberg
[root@docker ~]#
----------
[root@h104 ~]# docker push docker:5002/ubuntu
The push refers to a repository [docker:5002/ubuntu] (len: 1)

Head https://docker:5002/v2/ubuntu/blobs/sha256:a3ed95caeb02ffe68cdd9fd84406680ae93d633cb16422d00e8a7c22955b46d4: no basic auth creden
[root@h104 ~]# docker login docker:5002
Username: testuser
Password: 
Email: yyghdfz@163.com
WARNING: login credentials saved in /root/.docker/config.json
Login Succeeded
[root@h104 ~]# docker push docker:5002/ubuntu
The push refers to a repository [docker:5002/ubuntu] (len: 1)
8693db7e8a00: Pushed 
a4c5be5b6e59: Pushed 
c4fae638e7ce: Pushed 
f15ce52fc004: Pushed 
latest: digest: sha256:45d78ef16a9e6199ffbbc78f71c2c6ef6647f3be6b9721fe3f1b08d6e3fcf6b3 size: 6800
[root@h104 ~]# 
现在一切正常
Tip: 直接使用 docker-compose-Linux-x86_64 up -d 时并未指定配置文件, 但其实它在隐性调用当前目录中的 docker-compose.yml 文件,这个和 Dockerfile 有相似之处,但是可以使用 -f, --file FILE 参数来覆盖

命令汇总

docker run -d -p 5000:5000 --name registry registry:2
docker pull ubuntu
docker tag ubuntu localhost:5000/myfirstimage
docker images
docker push localhost:5000/myfirstimage
docker pull localhost:5000/myfirstimage
docker  ps -a
docker stop 7716d7899161
docker rm 7716d7899161
docker run -d -p 5000:5000 --restart=always --name registry registry:2
docker pull ubuntu &&  docker tag ubuntu localhost:5000/ubuntu
docker push localhost:5000/ubuntu
docker pull localhost:5000/ubuntu
docker stop registry && docker rm -v registry
echo `pwd`
docker  run -d -p 5000:5000 --restart=always --name registry -v `pwd`/data:/var/lib/registry registry:2
tree data/
openssl genrsa -out docker.key 2048
openssl req -new -key docker.key -out docker.csr
openssl x509 -req -days 365 -in docker.csr -signkey docker.key -out docker.crt
chmod 600 *
docker run -d -p 5000:5000 --restart=always --name registry  -v `pwd`/data:/var/lib/registry  -v `pwd`/certs:/certs -e REGISTRY_HTTP_TLS_CERTIFICATE=/certs/docker.crt -e REGISTRY_HTTP_TLS_KEY=/certs/docker.key registry:2
docker tag ubuntu 192.168.100.104:5000/ubuntu
docker tag ubuntu h104:5000/ubuntu
docker tag ubuntu docker-registry:5000/ubuntu
docker push h104:5000/ubuntu
docker push 192.168.100.104:5000/ubuntu
docker push h104:5000/ubuntu
vim /etc/hosts
grep docker-registry  /etc/hosts
docker push docker-registry:5000/ubuntu
ll /etc/pki/tls/certs/ca-bundle.crt
ll /etc/pki/ca-trust/extracted/pem/
scp root@h104:/root/certs/docker.crt /etc/pki/ca-trust/extracted/pem/
cat /etc/pki/ca-trust/extracted/pem/docker.crt >> /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem
systemctl stop docker && systemctl start docker
docker push docker-registry:5000/ubuntu
docker pull  docker-registry:5000/ubuntu
scp root@h104:/root/certs/docker.crt  /etc/pki/ca-trust/source/anchors/
ll /etc/pki/ca-trust/source/anchors/
update-ca-trust
systemctl stop docker && systemctl start docker
docker push docker-registry:5000/ubuntu
docker pull docker-registry:5000/ubuntu
systemctl list-dependencies docker.service | head -n 10
firewall-cmd --reload
docker push docker:5000/ubuntu
systemctl stop docker && systemctl  start docker
iptables -L -nv | grep -i docker
docker push docker:5000/ubuntu
mkdir auth
docker run --entrypoint htpasswd registry:2 -Bbn testuser testpassword > auth/htpasswd
cat auth/htpasswd
docker run -d -p 5000:5000 --restart=always --name registry \
docker push docker:5000/ubuntu
docker login docker:5000
docker push docker:5000/ubuntu
curl -L https://github.com/docker/compose/releases/download/1.5.2/docker-compose-`uname -s`-`uname -m` > docker-compose
wget https://github.com/docker/compose/releases/download/1.5.2/docker-compose-`uname -s`-`uname -m`
file docker-compose-Linux-x86_64
chmod +x docker-compose-Linux-x86_64
./docker-compose-Linux-x86_64 version
./docker-compose-Linux-x86_64 --help
vim docker-compose.yml
cat docker-compose.yml
./docker-compose-Linux-x86_64 up -d
nmap docker
docker login docker:5002
docker push docker:5002/ubuntu 
---------------------
 
docker的学习之路

Docker是什么?

Docker 是一个开源项目,Go 语言实现,遵从了 Apache 2.0 协议,项目代码在 GitHub 上进行维护。Docker 项目的目标是实现轻量级的操作系统虚拟化解决方案。Docker 的基础是 Linux 容器(LXC)等技术。
下面的图片比较了 Docker 和传统虚拟化方式的不同之处,可见容器是在操作系统层面上实现虚拟化,直接复用本地主机的操作系统,而传统方式则是在硬件层面实现。

为什么要使用 Docker?

首先,Docker 容器的启动可以在秒级实现,这相比传统的虚拟机方式要快得多。 其次,Docker 对系统资源的利用率很高,一台主机上可以同时运行数千个 Docker 容器。
容器除了运行其中应用外,基本不消耗额外的系统资源,使得应用的性能很高,同时系统的开销尽量小。传统虚拟机方式运行 10 个不同的应用就要起 10 个虚拟机,而Docker 只需要启动 10 个隔离的应用即可。
更快速的交付和部署
开发者可以使用一个标准的镜像来构建一套开发容器,开发完成之后,运维人员可以直接使用这个容器来部署代码。 Docker 可以快速创建容器,快速迭代应用程序,并让整个过程全程可见,使团队中的其他成员更容易理解应用程序是如何创建和工作的。 Docker 容器很轻很快!容器的启动时间是秒级的,大量地节约开发、测试、部署的时间。
更高效的虚拟化
Docker 容器的运行不需要额外的 hypervisor 支持,它是内核级的虚拟化,因此可以实现更高的性能和效率。
更轻松的迁移和扩展
Docker 容器几乎可以在任意的平台上运行,包括物理机、虚拟机、公有云、私有云、个人电脑、服务器等。 这种兼容性可以让用户把一个应用程序从一个平台直接迁移到另外一个。
更简单的管理
使用 Docker,只需要小小的修改,就可以替代以往大量的更新工作。所有的修改都以增量的方式被分发和更新,从而实现自动化并且高效的管理。
对比传统虚拟机总结
特性容器虚拟机
启动秒级分钟级
硬盘使用一般为 MB一般为 GB
性能接近原生弱于
系统支持量单机支持上千个容器一般几十个

Docker能做什么?

Docker可以解决虚拟机能够解决的问题,同时也能够解决虚拟机由于资源要求过高而无法解决的问题。Docker能处理的事情包括:
隔离应用依赖
创建应用镜像并进行复制
创建容易分发的即启即用的应用
允许实例简单、快速地扩展
测试应用并随后销毁它们
Docker背后的想法是创建软件程序可移植的轻量容器,让其可以在任何安装了Docker的机器上运行,而不用关心底层操作系统
基本概念

Docker 镜像 (Image)

镜像原理:Docker的镜像类似虚拟机的快照,但更轻量,非常非常轻量。Docker 使用 Union FS 将这些不同的层结合到一个镜像中去。
通常 Union FS 有两个用途, 一方面可以实现不借助 LVM、RAID 将多个 disk 挂到同一个目录下,另一个更常用的就是将一个只读的分支和一个可写的分支联合在一起,Live CD 正是基于此方法可以允许在镜像不变的基础上允许用户在其上进行一些写操作;
创建Docker镜像有几种方式,多数是在一个现有镜像基础上创建新镜像,因为几乎你需要的任何东西都有了公共镜像,包括所有主流Linux发行版,你应该不会找不到你需要的镜像。不过,就算你想从头构建一个镜像,也有好几种方法。
要创建一个镜像,你可以拿一个镜像,对它进行修改来创建它的子镜像。实现前述目的的方式有两种:在一个文件中指定一个基础镜像及需要完成的修改;或通过“运行”一个镜像,对其进行修改并提交。不同方式各有优点,不过一般会使用文件来指定所做的变化。
Docker 镜像(Image)就是一个只读的模板,可以用来创建 Docker 容器。
简单命令 (Ubuntu系统)
安装Docker




1
2
$ sudo apt-get update
$ wget -qO- https://get.docker.com/ | sh

注:系统会提示你输入sudo密码,输入完成之后,就会下载脚本并且安装Docker及依赖包。
Docker命令工具需要root权限才能工作。你可以将你的用户放入docker组来避免每次都要使用sudo。




1
$ sudo docker pull ubuntu:latest

列出docker镜像




1
$ sudo docker images

上传镜像




1
$ sudo docker push ouruser/sinatra

保存镜像




1
$ sudo docker save -o ubuntu_14.04.tar ubuntu:14.04

加载镜像




1
$ sudo docker load --input ubuntu_14.04.tar # 或者 sudo docker load < ubuntu_14.04.tar

删除镜像




1
2
sudo docker rmi training/sinatra
注:在删除镜像之前要先用 docker rm 删掉依赖于这个镜像的所有容器.

清理所有未打过标签的本地镜像




1
$ sudo docker rmi $(docker images -q -f "dangling=true") #sudo docker rmi $(docker images --quiet --filter "dangling=true")

Dockerfile创建镜像




1
2
3
4
5
6
7
8
9
10
11
12
13
$ vim Dockerfile
# This is a comment
FROM ubuntu:14.04
MAINTAINER Docker Newbee <newbee@docker.com>
RUN apt-get -qq update
RUN apt-get -qqy install ruby ruby-dev
RUN gem install sinatra
$ sudo docker build -t="ouruser/sinatra:v2" .
注:其中 -t 标记来添加 tag,指定新的镜像的用户信息。 “.” 是 Dockerfile 所在的路径(当前目录),也可以替换为一个具体的 Dockerfile 的路径。
$ sudo docker run -t -i ouruser/sinatra:v2 /bin/bash

从本地文件系统导入




1
$ sudo cat ubuntu-14.04-x86_64-minimal.tar.gz |docker import - ubuntu:14.04

Docker 容器(Container)

Docker 利用容器(Container)来运行应用。
容器是从镜像创建的运行实例。它可以被启动、开始、停止、删除。每个容器都是相互隔离的、保证安全的平台。
可以把容器看做是一个简易版的 Linux 环境(包括root用户权限、进程空间、用户空间和网络空间等)和运行在其中的应用程序。
*注:镜像是只读的,容器在启动的时候创建一层可写层作为最上层。
新建并后台启动容器




1
2
3
4
5
$ sudo docker run -tid ubuntu /bin/bash
注:-t 选项让Docker分配一个伪终端(pseudo-tty)并绑定到容器的标准输入上, -i 则让容器的标准输入保持打开,-d 让容器进入后台运行.
$ sudo docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
b548b2d4a537 ubuntu "/bin/bash" 11 seconds ago Up 10 seconds zen_engelbart

docker run 来创建容器时,Docker 在后台运行的标准操作包括:
检查本地是否存在指定的镜像,不存在就从公有仓库下载
利用镜像创建并启动一个容器
分配一个文件系统,并在只读的镜像层外面挂载一层可读写层
从宿主主机配置的网桥接口中桥接一个虚拟接口到容器中去
从地址池配置一个 ip 地址给容器
执行用户指定的应用程序
执行完毕后容器被终止
查看docker容器




1
sudo docker ps

启动已经停止的容器




1
$ sudo docker start ubuntu:14.04

docker自带命令进入容器




1
2
$ sudo docker attach zen_engelbart #zen_engelbart是容器名当退出容器后,容器会关闭
$ docker exec -it zen_engelbart /bin/bash #进入已经开启的容器,退出后容器能继续运行

第三方工具进入容器




1
2
3
$ cd /tmp; curl https://www.kernel.org/pub/linux/utils/util-linux/v2.24/util-linux-2.24.tar.gz | tar -zxf-; cd util-linux-2.24;
$ ./configure --without-ncurses
$ make nsenter && sudo cp nsenter /usr/local/bin

容器的第一个进程的 PID,可以通过下面的命令获取




1
2
$ PID=$(docker inspect --format "{{ .State.Pid }}" <container>)
$ nsenter --target $PID --mount --uts --ipc --net --pid

实例演示




1
2
3
4
5
6
7
8
9
$ sudo docker run -idt ubuntu
243c32535da7d142fb0e6df616a3c3ada0b8ab417937c853a9e1c251f499f550
$ sudo docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
243c32535da7 ubuntu:latest "/bin/bash" 18 seconds ago Up 17 seconds nostalgic_hypatia
$ PID=$(docker-pid 243c32535da7)
10981
$ sudo nsenter --target 10981 --mount --uts --ipc --net --pid
root@243c32535da7:/#
1
2
3
4
5
6
简单的方法是:下载 .bashrc_docker,并将内容放到 .bashrc 中。
$ wget -P ~ https://github.com/yeasy/docker_practice/raw/master/_local/.bashrc_docker;
$ echo "[ -f ~/.bashrc_docker ] && . ~/.bashrc_docker" >> ~/.bashrc; source ~/.bashrc
$ echo $(docker-pid <container>)
$ docker-enter <container> ls

获取容器日志




1
$ sudo docker logs ubuntu:14.04

导出容器




1
2
3
4
$ sudo docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
9c365aaa875f mysql "docker-entrypoint.sh" 9 days ago Exited 8 minutes ago 0.0.0.0:3308->3306/tcp mysql_3308
$ sudo docker export 9c365aaa875f > mysql.tar

导入容器快照




1
2
$ cat mysql.tar | sudo docker import - test/mysql:5.6
$sudo docker import http://example.com/exampleimage.tgz example/imagerepo

Docker 仓库(Repository)

仓库(Repository)是集中存放镜像文件的场所。有时候会把仓库和仓库注册服务器(Registry)混为一谈,并不严格区分。实际上,仓库注册服务器上往往存放着多个仓库,每个仓库中又包含了多个镜像,每个镜像有不同的标签(tag)。
仓库分为公开仓库(Public)和私有仓库(Private)两种形式。
最大的公开仓库是 Docker Hub,存放了数量庞大的镜像供用户下载。
*注:Docker 仓库的概念跟 Git 类似,注册服务器可以理解为 GitHub 这样的托管服务。

Dockerfile使用

指令
指令的一般格式为 INSTRUCTION arguments,指令包括 FROM、MAINTAINER、RUN 等。
FROM
格式为 FROM 或FROM :。
第一条指令必须为 FROM 指令。并且,如果在同一个Dockerfile中创建多个镜像时,可以使用多个 FROM 指令(每个镜像一次)。
MAINTAINER
格式为 MAINTAINER ,指定维护者信息。
RUN
格式为 RUN 或 RUN [“executable”, “param1”, “param2”]。
前者将在 shell 终端中运行命令,即 /bin/sh -c;后者则使用 exec 执行。指定使用其它终端可以通过第二种方式实现,例如 RUN [“/bin/bash”, “-c”, “echo hello”]。
每条 RUN 指令将在当前镜像基础上执行指定命令,并提交为新的镜像。当命令较长时可以使用 \ 来换行。
CMD
支持三种格式
CMD [“executable”,”param1”,”param2”] 使用 exec 执行,推荐方式;
CMD command param1 param2 在 /bin/sh 中执行,提供给需要交互的应用;
CMD [“param1”,”param2”] 提供给 ENTRYPOINT 的默认参数;
指定启动容器时执行的命令,每个 Dockerfile 只能有一条 CMD 命令。如果指定了多条命令,只有最后一条会被执行。
如果用户启动容器时候指定了运行的命令,则会覆盖掉 CMD 指定的命令。
EXPOSE
格式为 EXPOSE […]。
告诉 Docker 服务端容器暴露的端口号,供互联系统使用。在启动容器时需要通过 -P,Docker 主机会自动分配一个端口转发到指定的端口。
ENV
格式为 ENV 。 指定一个环境变量,会被后续 RUN 指令使用,并在容器运行时保持。
例如
ENV PG_MAJOR 9.3
ENV PG_VERSION 9.3.4
RUN curl -SL http://example.com/postgres-$PG_VERSION.tar.xz | tar -xJC /usr/src/postgress && …
ENV PATH /usr/local/postgres-PGMAJOR/bin:PGMAJOR/bin:PATH
ADD
格式为 ADD 
该命令将复制指定的 到容器中的 。 其中 可以是Dockerfile所在目录的一个相对路径;也可以是一个 URL;还可以是一个 tar 文件(自动解压为目录)。
COPY
格式为 COPY 
复制本地主机的 (为 Dockerfile 所在目录的相对路径)到容器中的 
当使用本地目录为源目录时,推荐使用 COPY。
ENTRYPOINT
两种格式:
ENTRYPOINT [“executable”, “param1”, “param2”]
ENTRYPOINT command param1 param2(shell中执行)。
配置容器启动后执行的命令,并且不可被 docker run 提供的参数覆盖。
每个 Dockerfile 中只能有一个 ENTRYPOINT,当指定多个时,只有最后一个起效。
VOLUME
格式为 VOLUME [“/data”]。
创建一个可以从本地主机或其他容器挂载的挂载点,一般用来存放数据库和需要保持的数据等。
USER
格式为 USER daemon。
指定运行容器时的用户名或 UID,后续的 RUN 也会使用指定用户。
当服务不需要管理员权限时,可以通过该命令指定运行用户。并且可以在之前创建所需要的用户,例如:RUN groupadd -r postgres && useradd -r -g postgres postgres。要临时获取管理员权限可以使用 gosu,而不推荐 sudo。
WORKDIR
格式为 WORKDIR /path/to/workdir。
为后续的 RUN、CMD、ENTRYPOINT 指令配置工作目录。
可以使用多个 WORKDIR 指令,后续命令如果参数是相对路径,则会基于之前命令指定的路径。例如
WORKDIR /a
WORKDIR b
WORKDIR c
RUN pwd
则最终路径为 /a/b/c。
ONBUILD
格式为 ONBUILD [INSTRUCTION]。
配置当所创建的镜像作为其它新创建镜像的基础镜像时,所执行的操作指令。
例如,Dockerfile 使用如下的内容创建了镜像 image-A。
[…]
ONBUILD ADD . /app/src
ONBUILD RUN /usr/local/bin/python-build –dir /app/src
[…]
如果基于 image-A 创建新的镜像时,新的Dockerfile中使用 FROM image-A指定基础镜像时,会自动执行 ONBUILD 指令内容,等价于在后面添加了两条指令。
FROM image-A




1
2
3
4
#Automatically run the following
ADD . /app/src
RUN /usr/local/bin/python-build --dir /app/src
注:使用 ONBUILD 指令的镜像,推荐在标签中注明

实例演示(dockerfile创建镜像,运行Django+uwsgi+nginx+supervisor)

启动mysql容器




1
2
sudo docker run -d -e MYSQL_ROOT_PASSWORD=pinbot@123 --name mysql_3308 -v /data/mysql/data:/var/lib/mysql -p 3308:3306 mysql
注:用mysql镜像后台启动容器,并设置root用户初始密码为谁pinbot123,挂载本地目录/data/mysql/data到容器mysql_3308 的/var/lib/mysql目录,映射本地3308端口到容器的3306端口

用Dockerfile创建镜像




1
2
sudo docker build -t talentbi:1.0 .
注:根据Dockerfile创建镜像,并命名为talentbi:1.0;

后台启动容器




1
2
sudo docker run -d -p 8001:8080 -v /home/bigdata/github/TalentMiner/:/home/bigdata/github/TalentMiner --name talentbi1.0 talentbi:1.0
注:用talentbi:1.0镜像启动容器并后台运行,映射本地端口8001到容器内8080端口,挂载本地目录等

进入容器




1
sudo docker exec -ti talentbi1.1 /bin/bash

端口映射




1
sudo iptables -t nat -A DOCKER -p tcp --dport 8080 -j DNAT --to-destination 172.17.0.3:8080

查看iptables列表




1
sudo iptables -t nat -nL

 -------------------

https://github.com/alexellis/handsondocker/
----------------------

使用国内镜像源

由于国内访问国外的网速不理想,所以我们需要找一个国内的docker源,这里推荐DaoCloud的。
步骤如下: 1、 访问http://www.daocloud.io/注册一个账户。 2、 注册后,进入镜像仓库(https://dashboard.daocloud.io/packages),找到想要的镜像,我这里输入的centos,拉取镜像命令如下:docker pull daocloud.io/library/centos:7.2.1511 3、 到docker命令行窗口输入如下命令: docker login daocloud.io 然后输入用户名、密码、邮箱,登录。 4、 到docker命令行窗口输入刚才获取到的拉取镜像的命令:docker pull daocloud.io/library/centos:7.2.1511 5、 等到拉取完成后,输入docker run daocloud.io/library/centos:7.2.1511 ping www.baidu.com 可以看到运行ping命令成功了。
直接输入docker可以看到docker支持的命令。 这里说明下镜像和容器的关系:容器是镜像的实例化,可以通过一个镜像启动多个容器,在里面运行命令,启动容器的命令为docker run 镜像名:版本,每一次执行这段命令,都会启动一个新的容器,当然,也可以启动一个容器,然后在里面执行很多命令,命令为docker run –it 镜像名:版本。

补充:

1、docker启动的容器做出修改后可以保存到镜像去,命令为docker commit,使用方法可以通过docker commit –help查看。 2、可以通过docker ps –a 查看所有容器,通过docker images –a 查看所有镜像。 3、描述镜像,使用镜像:版本,描述容器使用CONTAINER ID。 4、docker run、docker start、docker attach、docker stop是个常用的东西。 5、没事看看docker --help,docker 命令 --help
-------

相关帖子:https://briteming.blogspot.com/2016/09/docker.html