使用Docker API for Python来更好的管理容器!

客户端初始化的三种方法

1
2
3
4
5
6
import docker
docker.api()
docker.APIClient()
docker.client()
docker.DockerClient() 其实就是docker.client()的一个子集
docker.from_env() 其实也是docker.client()的一个子集

一、初始化客户端

1.Docker客户端的初始化工作

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
>>> import docker
>>> client = docker.APIClient(base_url='unix://var/run/docker.sock’,version='1.21',timeout=5)
>>> client.version()
{u'ApiVersion': u'1.21’,
 u'Arch': u'amd64',
 u'BuildTime': u'2016-09-27T23:38:15.810178467+00:00',
 u'Experimental': True,
 u'GitCommit': u'45bed2c',
 u'GoVersion': u'go1.6.3',
 u'KernelVersion': u'4.4.22-moby',
 u'Os': u'linux',
 u'Version': u'1.12.2-rc1'}
1
2
3
4
5
6
7
8
9
   Args:
      base_url (str): 指定链接路径,可以通过socket或者tcp方式链接
          ``unix:///var/run/docker.sock`` or ``tcp://127.0.0.1:1234``.
      version (str): 指定API使用的版本(docker=2.0.0默认的api版本是1.24,最低支持1.21,docker1.9+api是1.21),因此在使用python的docker模块时一定要注意docker的api以及docker模块的api是否兼容。当然如果设置为 ``auto`` 降回去自动检测server的版本
      timeout (int): 使用API调用的默认超时时间,默认单位为秒
      tls (bool or :py:class:`~docker.tls.TLSConfig`): Enable TLS. Pass
          ``True`` to enable it with default options, or pass a
          :py:class:`~docker.tls.TLSConfig` object to use custom
          configuration.

查看docker引擎当前版本:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
$ sudo docker version
Client:
 Version:      1.9.1
 API version:  1.21
 Go version:   go1.4.3
 Git commit:   a34a1d5-dirty
 Built:        Tue Mar 28 15:39:19 UTC 2017
 OS/Arch:      linux/amd64

Server:
 Version:      1.9.1
 API version:  1.21
 Go version:   go1.4.3
 Git commit:   a34a1d5-dirty
 Built:        Tue Mar 28 15:39:19 UTC 2017
 OS/Arch:      linux/amd64

The sdk of docker for python–docker==2.0.0:

1
2
3
4
5
6
7
1.丢弃了python2.6的支持
2.最低支持API版本为1.12(Engine version 1.9.0+)
3.`docker.Client`被替换成`docker.APIClient`
4.`docker.from_env`初始化一个docker客户端实例代替了`APIClient `实例 
5.从`APIClient.start`中移除了HostConfig参数
6.开始由之前的docker-py模块变为docker
7.`docker.ssladapter`替换为`docker.transport.ssladapter`

####2.Docker客户端的具体方法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import docker
C  = docker.DockerClient(base_url='unix://var/run/docker.sock',version='auto',timeout=10)

##docker相关的方法使用
使用DockerClient对象,会有以下方法:
C.api,
C.containers,
C.events,
C.from_env,
C.images,
C.info,
C.login,
C.networks,
C.nodes,
C.ping,
C.services,
C.swarm,
C.version,
C.volumes,


#输出docker的相关信息,相当于docker info
C.info()

二、api方法使用示例

1. login方法定义

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
C.login()
login(*args, **kwargs) method of docker.client.DockerClient instance
    Authenticate with a registry. Similar to the ``docker login`` command.
    
    Args:
        username (str): The registry username
        password (str): The plaintext password
        email (str): The email for the registry account
        registry (str): URL to the registry.  E.g.
            ``https://index.docker.io/v1/``
        reauth (bool): Whether refresh existing authentication on the
            Docker server.
        dockercfg_path (str): Use a custom path for the ``.dockercfg`` file
    (default ``$HOME/.dockercfg``)
    
    Returns:返回的错误日志信息
        (dict): The response from the login request

          Raises:
        :py:class:`docker.errors.APIError`
            If the server returns an error.

##使用login方法登录
C.login('xxbandy123','nslalla')

2.images 类定义:

 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
build方法
get方法
get(self, name)
    Gets an image.
    
    Args:
        name (str): The name of the image.
    
    Returns:
        (:py:class:`Image`): The image.
    
    Raises:
        :py:class:`docker.errors.ImageNotFound` If the image does not
        exist.
        :py:class:`docker.errors.APIError`
            If the server returns an error.
list方法
   list(self, name=None, all=False, filters=None)
    List images on the server.
    
    Args:
        name (str): Only show images belonging to the repository ``name``
        all (bool): Show intermediate image layers. By default, these are
            filtered out.
        filters (dict): Filters to be processed on the image list.
            Available filters:
            - ``dangling`` (bool)
            - ``label`` (str): format either ``key`` or ``key=value``
    
    Returns:
        (list of :py:class:`Image`): The images.
    
    Raises:
        :py:class:`docker.errors.APIError`
            If the server returns an error.

示例:

1
2
3
4
5
6
7
8
查看默认所有的镜像文件,以image-id进行区分
In [34]: C.images.list()
Out[34]: 
[<Image: 'busybox:latest'>,
 <Image: 'rancher-server:latest', 'rancher/server:latest'>,
 <Image: 'singleuser:latest'>,
 <Image: 'registry:2'>,
 <Image: 'rancher-agent:latest', 'rancher/agent:v1.0.2'>]
 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
load方法:相当于docker load

pull方法:下载镜像文件
 pull(self, name, **kwargs)
    Pull an image of the given name and return it. Similar to the
    ``docker pull`` command.
    
    If you want to get the raw pull output, use the
    :py:meth:`~docker.api.image.ImageApiMixin.pull` method in the
    low-level API.
    
    Args:
        repository (str): The repository to pull
        tag (str): The tag to pull
        insecure_registry (bool): Use an insecure registry
        auth_config (dict): Override the credentials that
            :py:meth:`~docker.client.DockerClient.login` has set for
            this request. ``auth_config`` should contain the ``username``
            and ``password`` keys to be valid.
    
    Returns:
        (:py:class:`Image`): The image that has been pulled.

需要注意的是:使用pull的时候,会弱匹配所有的tag标签

push方法:上传镜像文件

push(self, repository, tag=None, **kwargs)
    Push an image or a repository to the registry. Similar to the ``docker
    push`` command.
    
    Args:
        repository (str): The repository to push to
        tag (str): An optional tag to push
        stream (bool): Stream the output as a blocking generator
        insecure_registry (bool): Use ``http://`` to connect to the
            registry
        auth_config (dict): Override the credentials that
            :py:meth:`~docker.api.daemon.DaemonApiMixin.login` has set for
            this request. ``auth_config`` should contain the ``username``
            and ``password`` keys to be valid.
    
    Returns:
        (generator or str): The output from the server.
    
    Raises:
        :py:class:`docker.errors.APIError`

remove方法docker rmi 
 remove(self, *args, **kwargs)
    Remove an image. Similar to the ``docker rmi`` command.
    
    Args:
        image (str): The image to remove
        force (bool): Force removal of the image
        noprune (bool): Do not delete untagged parents

search方法
search(self, *args, **kwargs)
    Search for images on Docker Hub. Similar to the ``docker search``
    command.
    
    Args:
        term (str): A term to search for.
    
    Returns:
        (list of dicts): The response of the search.

3.docker管理容器相关

C.containers类,下面有相关的方法:

  • client
  • create
  • get
  • list
  • model
  • run …

列出当前存活的容器:

1
C.containers.list()

列出指定容器:

1
C.containers.get('')

创建容器:

  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
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
C.containers.create
create(image, command=None, **kwargs) method of docker.models.containers.ContainerCollection instance
    Create a container without starting it. Similar to ``docker create``.
    
    Takes the same arguments as :py:meth:`run`, except for ``stdout``,
    ``stderr``, and ``remove``.
    
    Returns:
        A :py:class:`Container` object.
    
    Raises:
        :py:class:`docker.errors.ImageNotFound`
            If the specified image does not exist.
        :py:class:`docker.errors.APIError`
            If the server returns an error.


run一个容器:类似于命令行的docker run方法
run(image, command=None, stdout=True, stderr=False, remove=False, **kwargs) method of docker.models.containers.ContainerCollection instance
    Run a container. By default, it will wait for the container to finish
    and return its logs, similar to ``docker run``.
    
    如果'detach'参数设置为'True',他将立即返回一个Container对象,类似于'docker run -d'    
    实例:
        运行一个容器并获取输出。
    
        >>> import docker
        >>> client = docker.from_env()
        >>> client.containers.run('alpine', 'echo hello world')
        b'hello world\n'
    
        后台运行一个容器:
        >>> container = client.containers.run('bfirsh/reticulate-splines',
                                              detach=True)
        获取该容器的日志信息
        >>> container.logs()
        'Reticulating spline 1...\nReticulating spline 2...\n'

   参数介绍:
        image (str): run一个容器所需要的镜像(str类型)
        command (str or list): 容器启动默认运行的命令(字符串或者列表类型).

        blkio_weight_device: 设置设备Block IO 权重:``[{"Path": "device_path", "Weight": weight}]``.
        blkio_weight: 设置block IO 的权重 范围10-1000.
        cap_add (list of str): 增加内核特性 比如:``["SYS_ADMIN", "MKNOD"]``.
        cap_drop (list of str): 删除内核特性
        cpu_group (int): 每颗cpu的长度
        cpu_period (int): 容器在每一个cpu的时间周期内可以得到多少的的cpu时间(ms)
        cpu_shares (int): 共享cpu权重CPU 相对权重
        cpuset_cpus (str): 绑定cpu的执行 (``0-3``,``0,1``).

        detach (bool): 后台运行一个容器,布尔类型值.相当于docker run -d选项

        device_read_bps: 从一个设备上限制读速率(bytes/s) `[{"Path": "device_path", "Rate": rate}]`
        device_read_iops: 从一个设备中限制读取速率(IO/s)
        device_write_bps: 从一个设备上限制写速率(bytes/s)
        device_write_iops: 从一个设备中限制读取速率(IO/s)
        devices (list): 映射主机的设备到容器中``<path_on_host>:<path_in_container>:<cgroup_permissions>``.
        dns (list): 配置当前的dns-server
        dns_opt (list): 添加额外的dns参数选项到容器内部,比如resolv.conf文件
        dns_search (list): 设置dns搜索域
        domainname (str or list): 设置当前dns搜索域名

        entrypoint (str or list): 为容器设置入口,覆盖镜像中的entrypoint

        environment (dict or list): 内部环境变量["SOMEVARIABLE=xxx"]``
        extra_hosts (dict): 在容器内部添加额外的主机名解析(本地hosts文件)
        group_add (list): 设置容器内部进程运行时额外的组名(gid

        hostname (str): 容器设置额外的主机名.相当于docker run -h/--hostname 选项

        ipc_mode (str): 为容器设置ipc模式
        isolation (str): 隔离技术的使用Default: `None`.
        labels (dict or list): 一个k/v类型的标签存储``{"label1": "value1", "label2": "value2"}``)或一个列表类型的k/v存储``["label1", "label2"]``
        links (dict or list of tuples): 为容器映射一个别名``(name, alias)`` 
        log_config (dict): 容器的日志配置。
            keys:
            - ``type`` The logging driver name.
            - ``config`` A dictionary of configuration for the logging
              driver.
        mac_address (str): 绑定mac地址.

        mem_limit (float or str): 内存限制,允许浮点型数据或单位区分的字符串(``100000b``, ``1000k``, ``128m``, ``1g``). 如果一个字符串没有指定单位,默认会使用字节(bytes)
        mem_limit (str or int): 容器可以使用的最大内存数量(e.g. ``1G``).

        mem_swappiness (int): 调整容器内存的swappiness行为状态,允许的数值为0-100 
        memswap_limit (str or int): 最大内存限制,容器可用的内存为(memory+swap)
        networks (list): 设置连接到该容器网络的名称
        name (str): 为容器设置名字
        network_disabled (bool): 禁用容器网络
        network_mode (str): 网络模式 相当于docker run --net='none'
    
            - ``bridge`` 默认使用桥接模式
            - ``none`` 无网络模式
            - ``container:<name|id>`` 重用另外一个容器的网络
            - ``host`` 使用本机的网络栈


        oom_kill_disable (bool): 是否启用OOM
        oom_score_adj (int): 一个整数,以调整OOM的整体性能.
        pid_mode (str): pid模式,如果设置为'host',在容器内部将会使用宿主机的host pid
        pids_limit (int): 调整容器的pid的限制'-1'表示不限制

        ports (dict): 为容器内部绑定端口 相当于docker run -p 
    		实例:
              ``{'2222/tcp': 3333}`` 暴露容器内部的2222端口到本机的3333
              ``{'2222/tcp': None}`` 将容器内部的2222随机映射到本机
              ``{'1111/tcp': ('127.0.0.1', 1111)}``.
              ``{'1111/tcp': [1234, 4567]}`` 绑定多个端口


		privileged (bool): 给容器额外的特权

        publish_all_ports (bool): 开放所有的端口到本机上 相当于docker run -P 

        read_only (bool): 以只读方式挂载容器的根文件系统
        remove (bool): 当容器退出的时候删除,默认是'False'
        restart_policy (dict): 当容器退出时重启容器
            配置参数如下:
            - ``Name`` One of ``on-failure``, or ``always``.
            - ``MaximumRetryCount`` 容器失败多少次后进行重启
            实例:
            ``{"Name": "on-failure", "MaximumRetryCount": 5}``
    
        security_opt (list): 设置安全标签,类似于selinux
        shm_size (str or int): /dev/shm 的大小(e.g. ``1G``).

        stdin_open (bool): 保持 ``STDIN`` 打开即使没有attach到容器内部相当于docker run -i

        stdout (bool): detach=False的时候,从'STDOUT'返回日志。默认为True
        stdout (bool): detach=False的时候,从'STDERR'返回日志,默认为False
        stop_signal (str): 设置用于停止容器的信号。(e.g. ``SIGINT``).
        sysctls (dict): 容器内部设置内核参数
        tmpfs (dict): 挂载临时文件系统 
                        .. code-block:: python
    
                {
                    '/mnt/vol2': '',
                    '/mnt/vol1': 'size=3G,uid=1000'
                }
    
        tty (bool): 分配一个tty 相当于docker run -t

        ulimits (list): 在容器内部设置ulimits值,一个字典类型的列表
        user (str or int): 设置容器启动的用户名以及id

        userns_mode (str): 为容器设置用户的命名空间模式,当用户的namespace的remapping参数被启用的时候,支持参数有'host'
            values are: ``host``
        volume_driver (str): 数据卷挂载驱动名
        volumes (dict or list): 一个字典配置,将外部数据卷挂载到容器内部,key是主机或者数据卷的名字value是带有key的字典
        		实例:
                {'/home/user1/': {'bind': '/mnt/vol2', 'mode': 'rw'},
                 '/var/www': {'bind': '/mnt/vol1', 'mode': 'ro'}}
    
        volumes_from (list): 获取容器名或者id标识
        working_dir (str): 容器默认的工作目录
    
    返回参数:
        容器的日志,包含 ``STDOUT``, ``STDERR``
        If ``detach`` is ``True``, a :py:class:`Container` object is
        returned instead.
    
    异常信息:
    	如果容器以非0状态退出,或者`detach`参数为`False`
        :py:class:`docker.errors.ContainerError`
        如果指定的镜像不存在
        :py:class:`docker.errors.ImageNotFound`
        如果是服务返回一个错误
        :py:class:`docker.errors.APIError`
            If the server returns an error.

示例: 一个完整的创建容器的例子:

 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
Command line:
$ docker run -itd -P --cpuset_cpus='0,1' --cpu_shares=2 --cpu_period=10000 --hostname=xxbandy --mem_limit=512m --net=none --oom_kill_disable=True -P -u admin busybox /bin/sh

Python API:
c1 = C.containers.run('busybox',command='/bin/sh',name='xxb-test',detach=True,tty=True,stdin_open=True,cpuset_cpus='0,1',cpu_shares=2,cpu_period=10000,hostname='xxbandy',mem_limit='512m',network_mode='none',oom_kill_disable=True,publish_all_ports=True,user='root')

查看容器相关信息:
容器id,64位的字符
In [20]: c1.id
Out[20]: '499db0824206d61d09db2f36c70aa84bdb1a4b6d508b001a618d2010a23fea7e'


c1.logs 
c1.name      获取容器名信息
c1.reload
c1.remove    删除容器信息,相当于docker rm 参数:c1.remove(v=True,link=True,force=True)
c2.rename	 重命名容器名,相当于docker renmame oldname newname
c1.resize	 设置tty session信息
c1.restart   重启容器信息
c1.start     启动容器信息
c1.stats     容器状态

c1.update    动态调整容器内部信息(blkio_weight,cpu_period,cpu_quota,cpu_shares,cpuset_cpus,cpuset_mems,mem_limit,mem_reservation)
    Args:
        blkio_weight (int): 块IO权重比例(10-100)
        cpu_period (int): 限制cpu公平调度周期
        cpu_quota (int): 限制cpu公平调度配额
        cpu_shares (int): 设置cpu共享权重
        cpuset_cpus (str): 指定cpu执行(0-3, 0,1)
        cpuset_mems (str): 指定cpu内存的执行(0-3, 0,1)
        mem_limit (int or str): 内存限制
        mem_reservation (int or str): 内存软限制
        memswap_limit (int or str): swap限制总的可使用内存限制(memory + swap),-1表示关闭swap
        kernel_memory (int or str): 内核内存限制
        restart_policy (dict): 重启策略

注意:update方法在docker1.10之后才增加了改功能

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
查看容器相关信息:
容器id,64位的字符
In [20]: c1.id
Out[20]: '499db0824206d61d09db2f36c70aa84bdb1a4b6d508b001a618d2010a23fea7e'

可以在/sys/fs/cgroup/memory/docker目录下面查看到每个容器的相关cgroup配置信息。
查看内存信息:
# grep hierarchical memory.stat     分别显示容器的内存限制和swap限制
hierarchical_memory_limit 536870912
hierarchical_memsw_limit 1073741824

#cat memory.limit_in_bytes
536870912

可以在/sys/fs/cgroup/cpuset/docker目录下面查看到容器cpu的相关配置
# cat cpuset.cpus       显示当前绑定的cpu信息
0-1
使用docker update动态调整内存信息:
docker update -m 1024M xuxuebiao-test

# cat memory.limit_in_bytes 
1073741824
# grep hierarchical_memory_limit memory.stat 
hierarchical_memory_limit 1073741824

个人博客:https://my.oschina.net/xxbAndy/blog 微信公众号:

wechat.png