1. 程式人生 > 其它 >Docker-client for python使用指南

Docker-client for python使用指南

Docker-client for python使用指南:

客戶端初始化的三種方法

import docker
docker.api()
docker.APIClient()
docker.client()
docker.DockerClient() 其實也是docker.client()的一個子集
docker.from_env() 其實就是docker.client()的一個子集

一、初始化客戶端

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

>>> 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'}
   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引擎當前版本:

$ 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.丟棄了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客戶端的具體方法

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方法定義

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 類定義:

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.

示例:

檢視預設所有的映象檔案,以image-id進行區分
In [34]: C.images.list()
Out[34]: 
[<Image: 'busybox:latest'>,
 <Image: '172.24.254.235:5010/rancher-server:latest', 'rancher/server:latest'>,
 <Image: '172.24.254.235:5010/jdsingleuser:latest'>,
 <Image: 'registry:2'>,
 <Image: '172.24.254.235:5010/rancher-agent:latest', 'rancher/agent:v1.0.2'>]
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

列出當前存活的容器:

C.containers.list()

列出指定容器:

C.containers.get('')

建立容器:

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 worldn'
    
        後臺執行一個容器:
        >>> 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.

示例: 一個完成的建立容器的基本粒子:

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之後才增加了改功能

檢視容器相關資訊:
容器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