国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 服務器 > Web服務器 > 正文

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

2024-09-01 13:51:19
字體:
來源:轉載
供稿:網友

Docker-client for python使用指南:

客戶端初始化的三種方法

import dockerdocker.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 versionClient: 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/amd64Server: 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模塊變?yōu)閐ocker7.`docker.ssladapter`替換為`docker.transport.ssladapter`

2.Docker客戶端的具體方法

import dockerC = 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 infoC.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 loadpull方法:下載鏡像文件 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 parentssearch方法: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.createcreate(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的執(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參數選項到容器內部,比如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): 內存限制,允許浮點型數據或單位區(qū)分的字符串(``100000b``, ``1000k``, ``128m``, ``1g``). 如果一個字符串沒有指定單位,默認會使用字節(jié)(bytes)    mem_limit (str or int): 容器可以使用的最大內存數量(e.g. ``1G``).    mem_swappiness (int): 調整容器內存的swappiness行為狀態(tài),允許的數值為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): 以只讀方式掛載容器的根文件系統(tǒng)    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): 掛載臨時文件系統(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參數被啟用的時候,支持參數有'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狀態(tài)退出,或者`detach`參數為`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/shPython 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.idOut[20]: '499db0824206d61d09db2f36c70aa84bdb1a4b6d508b001a618d2010a23fea7e'c1.logs c1.name   獲取容器名信息c1.reloadc1.remove  刪除容器信息,相當于docker rm 參數:c1.remove(v=True,link=True,force=True)c2.rename   重命名容器名,相當于docker renmame oldname newnamec1.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.idOut[20]: '499db0824206d61d09db2f36c70aa84bdb1a4b6d508b001a618d2010a23fea7e'可以在/sys/fs/cgroup/memory/docker目錄下面查看到每個容器的相關cgroup配置信息。查看內存信息:# grep hierarchical memory.stat   分別顯示容器的內存限制和swap限制hierarchical_memory_limit 536870912hierarchical_memsw_limit 1073741824#cat memory.limit_in_bytes536870912可以在/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

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


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 仁怀市| 常州市| 元氏县| 扎囊县| 东丰县| 鹿泉市| 平阴县| 安平县| 盐城市| 谢通门县| 南宁市| 太仆寺旗| 云霄县| 广元市| 瑞丽市| 永善县| 井研县| 长垣县| 会昌县| 准格尔旗| 五常市| 红桥区| 佛山市| 新干县| 通海县| 金阳县| 清流县| 彭阳县| 长汀县| 盈江县| 大荔县| 磐石市| 兴文县| 大英县| 普格县| 民权县| 杭州市| 武汉市| 饶河县| 正安县| 邮箱|