Docker-client for python詳解及簡單示例
Docker-client for python使用指南:
客戶端初始化的三種方法
import docker docker.api() docker.APIClient() docker.client() docker.DockerClient() 其實(shí)也是docker.client()的一個(gè)子集 docker.from_env() 其實(shí)就是docker.client()的一個(gè)子集
一、初始化客戶端
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默認(rèn)的api版本是1.24,最低支持1.21,docker1.9+的api是1.21),因此在使用python的docker模塊時(shí)一定要注意docker的api以及docker模塊的api是否兼容。當(dāng)然如果設(shè)置為 ``auto`` 降回去自動(dòng)檢測(cè)server的版本
timeout (int): 使用API調(diào)用的默認(rèn)超時(shí)時(shí)間,默認(rèn)單位為秒
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引擎當(dāng)前版本:
$ 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`初始化一個(gè)docker客戶端實(shí)例代替了`APIClient `實(shí)例 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對(duì)象,會(huì)有以下方法: 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)信息,相當(dāng)于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:返回的錯(cuò)誤日志信息
(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.
示例:
查看默認(rèn)所有的鏡像文件,以image-id進(jìn)行區(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方法:相當(dāng)于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的時(shí)候,會(huì)弱匹配所有的tag標(biāo)簽
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
列出當(dāng)前存活的容器:
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一個(gè)容器:類似于命令行的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',他將立即返回一個(gè)Container對(duì)象,類似于'docker run -d'
實(shí)例:
運(yùn)行一個(gè)容器并獲取輸出。
>>> import docker
>>> client = docker.from_env()
>>> client.containers.run('alpine', 'echo hello world')
b'hello world\n'
后臺(tái)運(yùn)行一個(gè)容器:
>>> container = client.containers.run('bfirsh/reticulate-splines',
detach=True)
獲取該容器的日志信息
>>> container.logs()
'Reticulating spline 1...\nReticulating spline 2...\n'
參數(shù)介紹:
image (str): run一個(gè)容器所需要的鏡像(str類型)
command (str or list): 容器啟動(dòng)默認(rèn)運(yùn)行的命令(字符串或者列表類型).
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): 容器在每一個(gè)cpu的時(shí)間周期內(nèi)可以得到多少的的cpu時(shí)間(ms)
cpu_shares (int): 共享cpu權(quán)重CPU 相對(duì)權(quán)重
cpuset_cpus (str): 綁定cpu的執(zhí)行 (``0-3``,``0,1``).
detach (bool): 后臺(tái)運(yùn)行一個(gè)容器,布爾類型值.相當(dāng)于docker run -d選項(xiàng)
device_read_bps: 從一個(gè)設(shè)備上限制讀速率(bytes/s) `[{"Path": "device_path", "Rate": rate}]`
device_read_iops: 從一個(gè)設(shè)備中限制讀取速率(IO/s)
device_write_bps: 從一個(gè)設(shè)備上限制寫速率(bytes/s)
device_write_iops: 從一個(gè)設(shè)備中限制讀取速率(IO/s)
devices (list): 映射主機(jī)的設(shè)備到容器中``<path_on_host>:<path_in_container>:<cgroup_permissions>``.
dns (list): 配置當(dāng)前的dns-server
dns_opt (list): 添加額外的dns參數(shù)選項(xiàng)到容器內(nèi)部,比如resolv.conf文件
dns_search (list): 設(shè)置dns搜索域
domainname (str or list): 設(shè)置當(dāng)前dns搜索域名
entrypoint (str or list): 為容器設(shè)置入口,覆蓋鏡像中的entrypoint
environment (dict or list): 內(nèi)部環(huán)境變量["SOMEVARIABLE=xxx"]``
extra_hosts (dict): 在容器內(nèi)部添加額外的主機(jī)名解析(本地hosts文件)
group_add (list): 設(shè)置容器內(nèi)部進(jìn)程運(yùn)行時(shí)額外的組名(gid)
hostname (str): 容器設(shè)置額外的主機(jī)名.相當(dāng)于docker run -h/--hostname 選項(xiàng)
ipc_mode (str): 為容器設(shè)置ipc模式
isolation (str): 隔離技術(shù)的使用Default: `None`.
labels (dict or list): 一個(gè)k/v類型的標(biāo)簽存儲(chǔ)``{"label1": "value1", "label2": "value2"}``)或一個(gè)列表類型的k/v存儲(chǔ)``["label1", "label2"]``
links (dict or list of tuples): 為容器映射一個(gè)別名``(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)存限制,允許浮點(diǎn)型數(shù)據(jù)或單位區(qū)分的字符串(``100000b``, ``1000k``, ``128m``, ``1g``). 如果一個(gè)字符串沒有指定單位,默認(rèn)會(huì)使用字節(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ò)模式 相當(dāng)于docker run --net='none'
- ``bridge`` 默認(rèn)使用橋接模式
- ``none`` 無網(wǎng)絡(luò)模式
- ``container:<name|id>`` 重用另外一個(gè)容器的網(wǎng)絡(luò)
- ``host`` 使用本機(jī)的網(wǎng)絡(luò)棧
oom_kill_disable (bool): 是否啟用OOM
oom_score_adj (int): 一個(gè)整數(shù),以調(diào)整OOM的整體性能.
pid_mode (str): pid模式,如果設(shè)置為'host',在容器內(nèi)部將會(huì)使用宿主機(jī)的host pid
pids_limit (int): 調(diào)整容器的pid的限制。'-1'表示不限制
ports (dict): 為容器內(nèi)部綁定端口 相當(dāng)于docker run -p
實(shí)例:
``{'2222/tcp': 3333}`` 暴露容器內(nèi)部的2222端口到本機(jī)的3333端
``{'2222/tcp': None}`` 將容器內(nèi)部的2222隨機(jī)映射到本機(jī)
``{'1111/tcp': ('127.0.0.1', 1111)}``.
``{'1111/tcp': [1234, 4567]}`` 綁定多個(gè)端口
privileged (bool): 給容器額外的特權(quán)
publish_all_ports (bool): 開放所有的端口到本機(jī)上 相當(dāng)于docker run -P
read_only (bool): 以只讀方式掛載容器的根文件系統(tǒng)
remove (bool): 當(dāng)容器退出的時(shí)候刪除,默認(rèn)是'False'
restart_policy (dict): 當(dāng)容器退出時(shí)重啟容器
配置參數(shù)如下:
- ``Name`` One of ``on-failure``, or ``always``.
- ``MaximumRetryCount`` 容器失敗多少次后進(jìn)行重啟
實(shí)例:
``{"Name": "on-failure", "MaximumRetryCount": 5}``
security_opt (list): 設(shè)置安全標(biāo)簽,類似于selinux
shm_size (str or int): /dev/shm 的大小(e.g. ``1G``).
stdin_open (bool): 保持 ``STDIN`` 打開即使沒有attach到容器內(nèi)部相當(dāng)于docker run -i
stdout (bool): 當(dāng)detach=False的時(shí)候,從'STDOUT'返回日志。默認(rèn)為True
stdout (bool): 當(dāng)detach=False的時(shí)候,從'STDERR'返回日志,默認(rèn)為False
stop_signal (str): 設(shè)置用于停止容器的信號(hào)。(e.g. ``SIGINT``).
sysctls (dict): 容器內(nèi)部設(shè)置內(nèi)核參數(shù)
tmpfs (dict): 掛載臨時(shí)文件系統(tǒng)
.. code-block:: python
{
'/mnt/vol2': '',
'/mnt/vol1': 'size=3G,uid=1000'
}
tty (bool): 分配一個(gè)tty 相當(dāng)于docker run -t
ulimits (list): 在容器內(nèi)部設(shè)置ulimits值,一個(gè)字典類型的列表
user (str or int): 設(shè)置容器啟動(dòng)的用戶名以及id
userns_mode (str): 為容器設(shè)置用戶的命名空間模式,當(dāng)用戶的namespace的remapping參數(shù)被啟用的時(shí)候,支持參數(shù)有'host'
values are: ``host``
volume_driver (str): 數(shù)據(jù)卷掛載驅(qū)動(dòng)名
volumes (dict or list): 一個(gè)字典配置,將外部數(shù)據(jù)卷掛載到容器內(nèi)部,key是主機(jī)或者數(shù)據(jù)卷的名字,value是帶有key的字典:
實(shí)例:
{'/home/user1/': {'bind': '/mnt/vol2', 'mode': 'rw'},
'/var/www': {'bind': '/mnt/vol1', 'mode': 'ro'}}
volumes_from (list): 獲取容器名或者id標(biāo)識(shí)。
working_dir (str): 容器默認(rèn)的工作目錄
返回參數(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ù)返回一個(gè)錯(cuò)誤
:py:class:`docker.errors.APIError`
If the server returns an error.
示例: 一個(gè)完成的創(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 刪除容器信息,相當(dāng)于docker rm 參數(shù):c1.remove(v=True,link=True,force=True)
c2.rename 重命名容器名,相當(dāng)于docker renmame oldname newname
c1.resize 設(shè)置tty session信息
c1.restart 重啟容器信息
c1.start 啟動(dòng)容器信息
c1.stats 容器狀態(tài)
c1.update 動(dòng)態(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目錄下面查看到每個(gè)容器的相關(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 顯示當(dāng)前綁定的cpu信息 0-1 使用docker update動(dòng)態(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
感謝閱讀 ,希望能幫助到大家,謝謝大家對(duì)本站的支持!
相關(guān)文章
使用Docker部署MySQL數(shù)據(jù)庫的兩種方法
在現(xiàn)代軟件開發(fā)中,MySQL 是一種流行的關(guān)系數(shù)據(jù)庫管理系統(tǒng),因其可靠性和易用性受到廣泛歡迎,通過 Docker,可以快速、便捷地部署和管理 MySQL 數(shù)據(jù)庫實(shí)例,本文將介紹兩種通過 Docker 部署 MySQL 的方法,需要的朋友可以參考下2024-10-10
利用Dockerfile制作個(gè)人的鏡像文件詳細(xì)講解
Docker是一個(gè)開源的應(yīng)用容器引擎,Dockerfile是用來構(gòu)建Docker鏡像的構(gòu)建文件,是由一系列命令和參數(shù)構(gòu)成的腳本,本文將給大家詳細(xì)介紹如何利用Dockerfile制作個(gè)人的鏡像文件,感興趣的同學(xué)可以借鑒參考2023-06-06
docker如何快速搭建幾個(gè)常用的第三方服務(wù)詳解
這篇文章主要給大家介紹了關(guān)于利用docker如何快速搭建幾個(gè)常用的第三方服務(wù)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-07-07
使用 Docker 企業(yè)版搭建自己的私有注冊(cè)服務(wù)器
這篇文章主要介紹了使用 Docker 企業(yè)版搭建自己的私有注冊(cè)服務(wù)器的相關(guān)資料,需要的朋友可以參考下2018-11-11
docker-compose實(shí)現(xiàn)容器任務(wù)編排的方法步驟
本文主要介紹了docker-compose實(shí)現(xiàn)容器任務(wù)編排的方法步驟,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-01-01

