亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Docker-client for python詳解及簡單示例

 更新時間:2017年04月05日 09:10:57   作者:Andy-xu  
這篇文章主要介紹了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參數(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相關的方法使用
使用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進行區(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管理容器相關

C.containers類,下面有相關的方法:

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ù)設置為'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: 設置設備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的執(zhí)行 (``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參數(shù)選項到容器內部,比如resolv.conf文件
    dns_search (list): 設置dns搜索域
    domainname (str or list): 設置當前dns搜索域名

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

    environment (dict or list): 內部環(huán)境變量["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): 內存限制,允許浮點型數(shù)據(jù)或單位區(qū)分的字符串(``100000b``, ``1000k``, ``128m``, ``1g``). 如果一個字符串沒有指定單位,默認會使用字節(jié)(bytes)
    mem_limit (str or int): 容器可以使用的最大內存數(shù)量(e.g. ``1G``).

    mem_swappiness (int): 調整容器內存的swappiness行為狀態(tài),允許的數(shù)值為0-100 
    memswap_limit (str or int): 最大內存限制,容器可用的內存為(memory+swap)
    networks (list): 設置連接到該容器網(wǎng)絡的名稱
    name (str): 為容器設置名字
    network_disabled (bool): 禁用容器網(wǎng)絡
    network_mode (str): 網(wǎng)絡模式 相當于docker run --net='none'

      - ``bridge`` 默認使用橋接模式
      - ``none`` 無網(wǎng)絡模式
      - ``container:<name|id>`` 重用另外一個容器的網(wǎng)絡
      - ``host`` 使用本機的網(wǎng)絡棧


    oom_kill_disable (bool): 是否啟用OOM
    oom_score_adj (int): 一個整數(shù),以調整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): 以只讀方式掛載容器的根文件系統(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): 設置安全標簽,類似于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): 容器內部設置內核參數(shù)
    tmpfs (dict): 掛載臨時文件系統(tǒng) 
            .. 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參數(shù)被啟用的時候,支持參數(shù)有'host'
      values are: ``host``
    volume_driver (str): 數(shù)據(jù)卷掛載驅動名
    volumes (dict or list): 一個字典配置,將外部數(shù)據(jù)卷掛載到容器內部,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`
    如果是服務返回一個錯誤
    :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')

查看容器相關信息:
容器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   設置tty session信息
c1.restart  重啟容器信息
c1.start   啟動容器信息
c1.stats   容器狀態(tài)

c1.update  動態(tài)調整容器內部信息(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執(zhí)行(0-3, 0,1)
    cpuset_mems (str): 指定cpu內存的執(zhí)行(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動態(tài)調整內存信息:
docker update -m 1024M xuxuebiao-test

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

感謝閱讀 ,希望能幫助到大家,謝謝大家對本站的支持!

您可能感興趣的文章:

相關文章

  • 利用Docker制作Nginx+PHP鏡像的步驟詳解

    利用Docker制作Nginx+PHP鏡像的步驟詳解

    Nginx是一個高性能的Web和反向代理服務器,它具有很多非常優(yōu)越的特性,那么這篇文章小編就分步驟向大家介紹如何利用Docker制作Nginx+PHP的鏡像,文章介紹的很詳細,對大家具有一定的參考借鑒價值,有需要的朋友們下面來一起看看吧。
    2016-10-10
  • 使用Docker快速搭建你的Gitbook

    使用Docker快速搭建你的Gitbook

    這篇文章主要介紹了使用Docker快速搭建你的Gitbook的相關資料,需要的朋友可以參考下
    2023-11-11
  • 使用Docker部署MySQL數(shù)據(jù)庫的兩種方法

    使用Docker部署MySQL數(shù)據(jù)庫的兩種方法

    在現(xiàn)代軟件開發(fā)中,MySQL 是一種流行的關系數(shù)據(jù)庫管理系統(tǒng),因其可靠性和易用性受到廣泛歡迎,通過 Docker,可以快速、便捷地部署和管理 MySQL 數(shù)據(jù)庫實例,本文將介紹兩種通過 Docker 部署 MySQL 的方法,需要的朋友可以參考下
    2024-10-10
  • Docker基礎命令詳解

    Docker基礎命令詳解

    Docker 是一個開源的應用容器引擎,讓開發(fā)者可以打包他們的應用以及依賴包到一個可移植的容器中,然后發(fā)布到任何流行的 Linux 機器上。本文給大家分享docker基礎命令,感興趣的朋友一起看看吧
    2016-10-10
  • Docker安裝RabbitMQ的超詳細步驟

    Docker安裝RabbitMQ的超詳細步驟

    RabbitMQ是一套開源的消息隊列服務軟件,是由LShift提供的一個 Advanced Message Queuing Protocol的開源實現(xiàn),由以高性能、健壯以及可伸縮性出名的 Erlang 寫成,這篇文章主要給大家介紹了關于Docker安裝RabbitMQ的超詳細步驟,需要的朋友可以參考下
    2022-08-08
  • 利用Dockerfile制作個人的鏡像文件詳細講解

    利用Dockerfile制作個人的鏡像文件詳細講解

    Docker是一個開源的應用容器引擎,Dockerfile是用來構建Docker鏡像的構建文件,是由一系列命令和參數(shù)構成的腳本,本文將給大家詳細介紹如何利用Dockerfile制作個人的鏡像文件,感興趣的同學可以借鑒參考
    2023-06-06
  • Docker login和logout的使用

    Docker login和logout的使用

    本文主要介紹了Docker login和logout的使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-02-02
  • docker如何快速搭建幾個常用的第三方服務詳解

    docker如何快速搭建幾個常用的第三方服務詳解

    這篇文章主要給大家介紹了關于利用docker如何快速搭建幾個常用的第三方服務的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2018-07-07
  • 使用 Docker 企業(yè)版搭建自己的私有注冊服務器

    使用 Docker 企業(yè)版搭建自己的私有注冊服務器

    這篇文章主要介紹了使用 Docker 企業(yè)版搭建自己的私有注冊服務器的相關資料,需要的朋友可以參考下
    2018-11-11
  • docker-compose實現(xiàn)容器任務編排的方法步驟

    docker-compose實現(xiàn)容器任務編排的方法步驟

    本文主要介紹了docker-compose實現(xiàn)容器任務編排的方法步驟,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-01-01

最新評論