本文主要包含Docker,client,for,python详解,Docker,client,for,python实例,Docker,client,for,python应用等服务器相关知识,Andy-xu 希望可以进行参考
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 star

