溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Docker-client for python是怎么使用的

發(fā)布時間:2021-10-12 09:41:51 來源:億速云 閱讀:139 作者:柒染 欄目:云計算

本篇文章為大家展示了Docker-client for python是怎么使用的,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。

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是否兼容。當然如果設(shè)置為 ``auto`` 降回去自動檢測server的版本
      timeout (int): 使用API調(diào)用的默認超時時間,默認單位為秒
      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參數(shù)
6.開始由之前的docker-py模塊變?yōu)閐ocker
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相關(guān)的方法使用
使用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的相關(guān)信息,相當于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進行區(qū)分
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管理容器相關(guān)

C.containers類,下面有相關(guān)的方法:

client,create,get,list,model,run

列出當前存活的容器:

C.containers.list()

列出指定容器:

C.containers.get('')

創(chuàng)建容器:

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'參數(shù)設(shè)置為'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'

   參數(shù)介紹:
        image (str): run一個容器所需要的鏡像(str類型)
        command (str or list): 容器啟動默認運行的命令(字符串或者列表類型).

        blkio_weight_device: 設(shè)置設(shè)備Block IO 權(quán)重:``[{"Path": "device_path", "Weight": weight}]``.
        blkio_weight: 設(shè)置block IO 的權(quán)重 范圍10-1000.
        cap_add (list of str): 增加內(nèi)核特性 比如:``["SYS_ADMIN", "MKNOD"]``.
        cap_drop (list of str): 刪除內(nèi)核特性
        cpu_group (int): 每顆cpu的長度
        cpu_period (int): 容器在每一個cpu的時間周期內(nèi)可以得到多少的的cpu時間(ms)
        cpu_shares (int): 共享cpu權(quán)重CPU 相對權(quán)重
        cpuset_cpus (str): 綁定cpu的執(zhí)行 (``0-3``,``0,1``).

        detach (bool): 后臺運行一個容器,布爾類型值.相當于docker run -d選項

        device_read_bps: 從一個設(shè)備上限制讀速率(bytes/s) `[{"Path": "device_path", "Rate": rate}]`
        device_read_iops: 從一個設(shè)備中限制讀取速率(IO/s)
        device_write_bps: 從一個設(shè)備上限制寫速率(bytes/s)
        device_write_iops: 從一個設(shè)備中限制讀取速率(IO/s)
        devices (list): 映射主機的設(shè)備到容器中``<path_on_host>:<path_in_container>:<cgroup_permissions>``.
        dns (list): 配置當前的dns-server
        dns_opt (list): 添加額外的dns參數(shù)選項到容器內(nèi)部,比如resolv.conf文件
        dns_search (list): 設(shè)置dns搜索域
        domainname (str or list): 設(shè)置當前dns搜索域名

        entrypoint (str or list): 為容器設(shè)置入口,覆蓋鏡像中的entrypoint

        environment (dict or list): 內(nèi)部環(huán)境變量["SOMEVARIABLE=xxx"]``
        extra_hosts (dict): 在容器內(nèi)部添加額外的主機名解析(本地hosts文件)
        group_add (list): 設(shè)置容器內(nèi)部進程運行時額外的組名(gid)

        hostname (str): 容器設(shè)置額外的主機名.相當于docker run -h/--hostname 選項

        ipc_mode (str): 為容器設(shè)置ipc模式
        isolation (str): 隔離技術(shù)的使用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): 內(nèi)存限制,允許浮點型數(shù)據(jù)或單位區(qū)分的字符串(``100000b``, ``1000k``, ``128m``, ``1g``). 如果一個字符串沒有指定單位,默認會使用字節(jié)(bytes)
        mem_limit (str or int): 容器可以使用的最大內(nèi)存數(shù)量(e.g. ``1G``).

        mem_swappiness (int): 調(diào)整容器內(nèi)存的swappiness行為狀態(tài),允許的數(shù)值為0-100 
        memswap_limit (str or int): 最大內(nèi)存限制,容器可用的內(nèi)存為(memory+swap)
        networks (list): 設(shè)置連接到該容器網(wǎng)絡(luò)的名稱
        name (str): 為容器設(shè)置名字
        network_disabled (bool): 禁用容器網(wǎng)絡(luò)
        network_mode (str): 網(wǎng)絡(luò)模式 相當于docker run --net='none'
    
            - ``bridge`` 默認使用橋接模式
            - ``none`` 無網(wǎng)絡(luò)模式
            - ``container:<name|id>`` 重用另外一個容器的網(wǎng)絡(luò)
            - ``host`` 使用本機的網(wǎng)絡(luò)棧


        oom_kill_disable (bool): 是否啟用OOM
        oom_score_adj (int): 一個整數(shù),以調(diào)整OOM的整體性能.
        pid_mode (str): pid模式,如果設(shè)置為'host',在容器內(nèi)部將會使用宿主機的host pid
        pids_limit (int): 調(diào)整容器的pid的限制。'-1'表示不限制

        ports (dict): 為容器內(nèi)部綁定端口 相當于docker run -p 
    		實例:
              ``{'2222/tcp': 3333}`` 暴露容器內(nèi)部的2222端口到本機的3333端
              ``{'2222/tcp': None}`` 將容器內(nèi)部的2222隨機映射到本機
              ``{'1111/tcp': ('127.0.0.1', 1111)}``.
              ``{'1111/tcp': [1234, 4567]}`` 綁定多個端口


		privileged (bool): 給容器額外的特權(quán)

        publish_all_ports (bool): 開放所有的端口到本機上 相當于docker run -P 

        read_only (bool): 以只讀方式掛載容器的根文件系統(tǒng)
        remove (bool): 當容器退出的時候刪除,默認是'False'
        restart_policy (dict): 當容器退出時重啟容器
            配置參數(shù)如下:
            - ``Name`` One of ``on-failure``, or ``always``.
            - ``MaximumRetryCount`` 容器失敗多少次后進行重啟
            實例:
            ``{"Name": "on-failure", "MaximumRetryCount": 5}``
    
        security_opt (list): 設(shè)置安全標簽,類似于selinux
        shm_size (str or int): /dev/shm 的大小(e.g. ``1G``).

        stdin_open (bool): 保持 ``STDIN`` 打開即使沒有attach到容器內(nèi)部相當于docker run -i

        stdout (bool): 當detach=False的時候,從'STDOUT'返回日志。默認為True
        stdout (bool): 當detach=False的時候,從'STDERR'返回日志,默認為False
        stop_signal (str): 設(shè)置用于停止容器的信號。(e.g. ``SIGINT``).
        sysctls (dict): 容器內(nèi)部設(shè)置內(nèi)核參數(shù)
        tmpfs (dict): 掛載臨時文件系統(tǒng) 
                        .. code-block:: python
    
                {
                    '/mnt/vol2': '',
                    '/mnt/vol1': 'size=3G,uid=1000'
                }
    
        tty (bool): 分配一個tty 相當于docker run -t

        ulimits (list): 在容器內(nèi)部設(shè)置ulimits值,一個字典類型的列表
        user (str or int): 設(shè)置容器啟動的用戶名以及id

        userns_mode (str): 為容器設(shè)置用戶的命名空間模式,當用戶的namespace的remapping參數(shù)被啟用的時候,支持參數(shù)有'host'
            values are: ``host``
        volume_driver (str): 數(shù)據(jù)卷掛載驅(qū)動名
        volumes (dict or list): 一個字典配置,將外部數(shù)據(jù)卷掛載到容器內(nèi)部,key是主機或者數(shù)據(jù)卷的名字,value是帶有key的字典:
        		實例:
                {'/home/user1/': {'bind': '/mnt/vol2', 'mode': 'rw'},
                 '/var/www': {'bind': '/mnt/vol1', 'mode': 'ro'}}
    
        volumes_from (list): 獲取容器名或者id標識。
        working_dir (str): 容器默認的工作目錄
    
    返回參數(shù):
        容器的日志,包含 ``STDOUT``, ``STDERR``
        If ``detach`` is ``True``, a :py:class:`Container` object is
        returned instead.
    
    異常信息:
    	如果容器以非0狀態(tài)退出,或者`detach`參數(shù)為`False`
        :py:class:`docker.errors.ContainerError`
        如果指定的鏡像不存在
        :py:class:`docker.errors.ImageNotFound`
        如果是服務(wù)返回一個錯誤
        :py:class:`docker.errors.APIError`
            If the server returns an error.

示例: 一個完成的創(chuàng)建容器的基本粒子:

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')

查看容器相關(guān)信息:
容器id,64位的字符
In [20]: c1.id
Out[20]: '499db0824206d61d09db2f36c70aa84bdb1a4b6d508b001a618d2010a23fea7e'


c1.logs 
c1.name      獲取容器名信息
c1.reload
c1.remove    刪除容器信息,相當于docker rm 參數(shù):c1.remove(v=True,link=True,force=True)
c2.rename	 重命名容器名,相當于docker renmame oldname newname
c1.resize	 設(shè)置tty session信息
c1.restart   重啟容器信息
c1.start     啟動容器信息
c1.stats     容器狀態(tài)

c1.update    動態(tài)調(diào)整容器內(nèi)部信息(blkio_weight,cpu_period,cpu_quota,cpu_shares,cpuset_cpus,cpuset_mems,mem_limit,mem_reservation)
    Args:
        blkio_weight (int): 塊IO權(quán)重比例(10-100)
        cpu_period (int): 限制cpu公平調(diào)度周期
        cpu_quota (int): 限制cpu公平調(diào)度配額
        cpu_shares (int): 設(shè)置cpu共享權(quán)重
        cpuset_cpus (str): 指定cpu執(zhí)行(0-3, 0,1)
        cpuset_mems (str): 指定cpu內(nèi)存的執(zhí)行(0-3, 0,1)
        mem_limit (int or str): 內(nèi)存限制
        mem_reservation (int or str): 內(nèi)存軟限制
        memswap_limit (int or str): swap限制總的可使用內(nèi)存限制(memory + swap),-1表示關(guān)閉swap
        kernel_memory (int or str): 內(nèi)核內(nèi)存限制
        restart_policy (dict): 重啟策略

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

查看容器相關(guān)信息:
容器id,64位的字符
In [20]: c1.id
Out[20]: '499db0824206d61d09db2f36c70aa84bdb1a4b6d508b001a618d2010a23fea7e'

可以在/sys/fs/cgroup/memory/docker目錄下面查看到每個容器的相關(guān)cgroup配置信息。
查看內(nèi)存信息:
# grep hierarchical memory.stat     分別顯示容器的內(nèi)存限制和swap限制
hierarchical_memory_limit 536870912
hierarchical_memsw_limit 1073741824

#cat memory.limit_in_bytes
536870912

可以在/sys/fs/cgroup/cpuset/docker目錄下面查看到容器cpu的相關(guān)配置
# cat cpuset.cpus       顯示當前綁定的cpu信息
0-1
使用docker update動態(tài)調(diào)整內(nèi)存信息:
docker update -m 1024M xuxuebiao-test

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

上述內(nèi)容就是Docker-client for python是怎么使用的,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI