span.kw { color: #007020; font-weight: bold; }
code > span.dt { color: #902000; }
code > span.dv { color: #40a070; }
code > span.bn { color: #40a070; }
code > span.fl { color: #40a070; }
code > span.ch { color: #4070a0; }
code > span.st { color: #4070a0; }
code > span.co { color: #60a0b0; font-style: italic; }
code > span.ot { color: #007020; }
code > span.al { color: #ff0000; font-weight: bold; }
code > span.fu { color: #06287e; }
code > span.er { color: #ff0000; font-weight: bold; }
-->
span.dt { color:#0FAA27; }
-->

Docker Python API 与 Docker Command

一.基本概念

image 镜像 - 程序运行的模板,里面集合了操作系统,共享库,运行时环境和程序 代码等. 镜像可以自己定义,也可以使用已经制作好的.每个镜像都有一个唯一 ID,如果在API中看到要参数为image就表示输入镜像唯一ID.

container 容器 - 由某个镜像产生出来的进程,每个进程运行何种程序都由镜像 文件所定义.容器具有进程的完整生命周期,可以被创建,启动,杀死和重启等.每 个container都有一个唯一ID,如果下面函数中看到参数为container就表示输入 此唯一ID.

二.通用命令

2.1 创建客户端

import docker
c = docker.Client(base_url='unix://var/run/docker.sock',
version='1.12',
timeout=10)

参数说明:

  • base_url - 连接参数,支持unix和tcp协议
  • version - 客户端当前使用的API版本号
  • timeout - HTTP超时参数 单位为秒

返回值 - 客户端实例

2.2 查看信息

c.info()

返回值 - 字典对象

2.3 版本信息

c.version()

返回值 - 字典对象,如

{u'KernelVersion': u'3.13.0-24-generic', u'Arch': u'amd64', u'ApiVersion': u'1.13', u'Version': u'1.1.0', u'GitCommit': 79812000, u'Os': u'linux', u'GoVersion': u'go1.2.1'}

2.4 PING

c.ping()

返回值 - 字符串:OK

2.5 登录

c.login(username, password=None, email=None, registry=None)

docker login命令一样

$ docker login --help
Usage: docker login [OPTIONS] [SERVER] Register or log in to a Docker registry server, if no server is specified "https://index.docker.io/v1/" is the default. -e, --email="" Email
-p, --password="" Password
-u, --username="" Username

三.镜像

3.1 创建新镜像

c.build(path=None, tag=None, quiet=False, fileobj=None, nocache=False,
rm=False, stream=False, timeout=None,
custom_context=False, encoding=None)

说明 - 用于创建一个新的镜像

参数说明:

  • path - 远程docker-server上的Dockerfile文件路径,如果此参数不设置则需要设置fileobj参数;
  • tag - 镜像标签名;
  • quiet - 静默安装标记,默认为false;
  • fileobj - 文件对象,使得客户端可以通过远程方式将Dockerfile送给服务器;
  • nocache - 不使用缓存标记;
  • rm - 删除标记;
  • stream - 流标记;
  • timeout - 超时时间;
  • custom_context - 如果有自定义tar文件要上传,该选项设置为true;
  • encoding - 字符编码;

等效命令:

$ docker build --help
Usage: docker build [OPTIONS] PATH | URL | - Build a new image from the source code at PATH --force-rm=false Always remove intermediate containers, even after unsuccessful builds
--no-cache=false Do not use cache when building the image
-q, --quiet=false Suppress the verbose output generated by the containers
--rm=true Remove intermediate containers after a successful build
-t, --tag="" Repository name (and optionally a tag) to be applied to the resulting image in case of success

3.2 将容器变成镜像

c.commit(container, repository=None, tag=None, message=None, author=None,
conf=None)

说明 - 将某个具体容器变为镜像;

等效命令 - docker commit

$ docker commit --help

Usage: docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]

Create a new image from a container's changes

  -a, --author=""     Author (e.g., "John Hannibal Smith <hannibal@a-team.com>")
-m, --message="" Commit message
-p, --pause=true Pause container during commit

3.3 查看镜像列表

c.images(name=None, quiet=False, all=False, viz=False)

等效命令 - docker images

$ docker images --help

Usage: docker images [OPTIONS] [NAME]

List images

  -a, --all=false      Show all images (by default filter out the intermediate image layers)
-f, --filter=[] Provide filter values (i.e. 'dangling=true')
--no-trunc=false Don't truncate output
-q, --quiet=false Only show numeric IDs

返回值:

  • Created - 创建时间
  • VirtualSize - 虚拟大小
  • ParentId - 父节点ID
  • RepoTags - 数组,镜像的tag
  • Id - 镜像Id
  • Size - 实际大小

{u'Created': 1403778147, u'VirtualSize': 590896221, u'ParentId': u'8e440ae693cfced82fc1418ec6f01aa2592fd63f7dc07cd0114c15062fd50423', u'RepoTags': [u':'], u'Id': u'9b93b40c2bc6bc92aa1e0fbadb5cc090f359dd5ecb6a2e0e5f286ad4d7af63cc', u'Size': 0}

3.4 插入(未找到此命令)

c.insert(image, url, path)

= docker insert

3.5 导入镜像

c.import_image(src, data=None, repository=None, tag=None)

3.6 删除镜像

c.remove_image(image)

说明 - 删除镜像,必须是没有容器引用此镜像时才可以删除;

等效命令 - docker rmi

$ docker rmi --help

Usage: docker rmi IMAGE [IMAGE...]

Remove one or more images

  -f, --force=false    Force removal of the image
--no-prune=false Do not delete untagged parents

3.7 查看镜像内部

c.inspect_image(image_id)

说明 - 只能查看images

等效命令 - docker inspect ~{.python} $ docker inspect

Usage: docker inspect CONTAINER|IMAGE [CONTAINER|IMAGE...]

Return low-level information on a container or image

-f, --format="" Format the output using the given go template. ~

3.8 给image打tag

c.tag(image, repository, tag=None, force=False)

3.9 docker pull

c.pull(repository, tag=None, stream=False)

3.10 docker push

c.push(repository, stream=False)

3.11 在公共镜像注册库中搜索镜像

c.search(term)

3.12 查看历史

c.history(image)

= docker history

四.容器

4.1 创建容器

c.create_container(image, command=None, hostname=None, user=None,
detach=False, stdin_open=False, tty=False, mem_limit=0,
ports=None, environment=None, dns=None, volumes=None,
volumes_from=None, network_disabled=False, name=None,
entrypoint=None, cpu_shares=None, working_dir=None,
memswap_limit=0)

说明 - 创建一个容器并启动它.端口绑定和外部存储请查看端口绑定挂 载外部存储.参数与docker run命令相似,不同的地方是此函数不支持attach选项(-a).

等效命令 - docker run命令

$ docker run --help

Usage: docker run [OPTIONS] IMAGE [COMMAND] [ARG...]

Run a command in a new container

  -a, --attach=[]            Attach to stdin, stdout or stderr.
-c, --cpu-shares=0 CPU shares (relative weight)
--cidfile="" Write the container ID to the file
--cpuset="" CPUs in which to allow execution (0-3, 0,1)
-d, --detach=false Detached mode: Run container in the background, print new container id
--dns=[] Set custom dns servers
--dns-search=[] Set custom dns search domains
-e, --env=[] Set environment variables
--entrypoint="" Overwrite the default entrypoint of the image
--env-file=[] Read in a line delimited file of ENV variables
--expose=[] Expose a port from the container without publishing it to your host
-h, --hostname="" Container host name
-i, --interactive=false Keep stdin open even if not attached
--link=[] Add link to another container (name:alias)
--lxc-conf=[] (lxc exec-driver only) Add custom lxc options --lxc-conf="lxc.cgroup.cpuset.cpus = 0,1"
-m, --memory="" Memory limit (format: <number><optional unit>, where unit = b, k, m or g)
--name="" Assign a name to the container
--net="bridge" Set the Network mode for the container
'bridge': creates a new network stack for the container on the docker bridge
'none': no networking for this container
'container:<name|id>': reuses another container network stack
'host': use the host network stack inside the container. Note: the host mode gives the container full access to local system services such as D-bus and is therefore considered insecure.
-P, --publish-all=false Publish all exposed ports to the host interfaces
-p, --publish=[] Publish a container's port to the host
format: ip:hostPort:containerPort | ip::containerPort | hostPort:containerPort
(use 'docker port' to see the actual mapping)
--privileged=false Give extended privileges to this container
--rm=false Automatically remove the container when it exits (incompatible with -d)
--sig-proxy=true Proxify received signals to the process (even in non-tty mode). SIGCHLD is not proxied.
-t, --tty=false Allocate a pseudo-tty
-u, --user="" Username or UID
-v, --volume=[] Bind mount a volume (e.g., from the host: -v /host:/container, from docker: -v /container)
--volumes-from=[] Mount volumes from the specified container(s)
-w, --workdir="" Working directory inside the container

4.2 启动容器

c.start(container, binds=None, port_bindings=None, lxc_conf=None,
publish_all_ports=False, links=None, privileged=False,
dns=None, dns_search=None, volumes_from=None, network_mode=None)

docker start命令类似,但不支持attach选项.使用docker logs来恢复stdout/stderr.

参数说明:

  • container - 容器id
  • binds - 允许绑定一个某个宿主机的文件夹到容器中.
  • port_bindings - 用于指定容器的端口到宿主机.
  • lxc_conf - 允许用文件夹的方式传递LXC配置项
  • privileged - 表示以特权模式启动容器.
  • links - 用于指定 Links can be specified with the links argument. They can either be specified as a dictionary mapping name to alias or as a list of (name, alias) tuples.
  • dns - 此参数只对于v1.10有效;
  • volumes_from - 只有v1.10版本支持;
  • network_mode - 指定Network模式,从v1.11之后可用.
    • 'bridge': creates a new network stack for the container on the docker bridge,
    • 'none': no networking for this container,
    • 'container:[name|id]': reuses another container network stack,
    • 'host': use the host network stack inside the container.

等效命令 - docker start

$ docker start --help

Usage: docker start CONTAINER [CONTAINER...]

Restart a stopped container

  -a, --attach=false         Attach container's STDOUT and STDERR and forward all signals to the process
-i, --interactive=false Attach container's STDIN

4.3 查看容器列表

c.containers(quiet=False, all=False, trunc=True, latest=False, since=None,
before=None, limit=-1)

docker ps命令一样

4.4 从容器中复制资源

c.copy(container, resource)

docker cp命令一样

4.5 检查容器的变化

c.diff(container)

= docker diff

4.6 导出container

c.export(container)

= docker export

4.7 查看容器内部

c.inspect_container(container)

= docker inspect 只能查看container

4.8 杀死container

c.kill(container, signal=None)

= docker kill

4.9 查看日志

c.logs(container, stdout=True, stderr=True, stream=False, timestamps=False)

= docker logs

stream参数使得logs函数返回一个可循环反复提取log数据的阻塞流;

4.10 挂载

c.attach(container, stdout=True, stderr=True, stream=False, logs=False)

4.11 端口

c.port(container, private_port)

= docker port

4.12 删除container

c.remove_container(container, v=False, link=False)

4.13 重启container

c.restart(container, timeout=10)

4.14 停止container

c.stop(container, timeout=10)

4.15 监控container

c.top(container)

4.16 等待container

c.wait(container)

五.端口绑定

  1. 创建busybox的container实例
c.create_container('busybox', 'ls', ports=[1111, 2222])
  1. 启动容器时指定端口映射
c.start(container_id, port_bindings={1111: 4567, 2222: None})
  1. 指定目标地址和端口
c.start(container_id, port_bindings={1111: ('127.0.0.1', 4567)})
  1. 使用随机端口
c.start(container_id, port_bindings={1111: ('127.0.0.1',)})
  1. 绑定udp端口
container_id = c.create_container('busybox', 'ls', ports=[(1111, 'udp'), 2222])
c.start(container_id, port_bindings={'1111/udp': 4567, 2222: None})

六.使用外挂存储

  1. 创建容器时挂载存储
c.create_container('busybox', 'ls', volumes=['/mnt/vol1', '/mnt/vol2'])
  1. 启动容器时挂载存储
c.start(container_id, binds={
'/home/user1/':
{
'bind': '/mnt/vol2',
'ro': False
},
'/var/www':
{
'bind': '/mnt/vol1',
'ro': True
}
})

Docker Python API 与 Docker Command的更多相关文章

  1. Docker SDK api操作Docker

    下载包 go get "github.com/docker/docker/api/types" go get "github.com/docker/docker/clie ...

  2. 【转+自己研究】新姿势之Docker Remote API未授权访问漏洞分析和利用

    0x00 概述 最近提交了一些关于 docker remote api 未授权访问导致代码泄露.获取服务器root权限的漏洞,造成的影响都比较严重,比如 新姿势之获取果壳全站代码和多台机器root权限 ...

  3. Docker入门教程(八)Docker Remote API

    Docker入门教程(八)Docker Remote API [编者的话]DockerOne组织翻译了Flux7的Docker入门教程,本文是系列入门教程的第八篇,重点介绍了Docker Remote ...

  4. Docker remote API简单配置使用

    1.启动docker remote API的方式如下: docker -d -H uninx:///var/run/docker.sock -H tcp://0.0.0.0:5678 2.但是为了伴随 ...

  5. Docker教程:使用docker配置python开发环境

    http://blog.csdn.net/pipisorry/article/details/50808034 Docker的安装和配置 [Docker教程:docker的安装] [Docker教程: ...

  6. Running Web API using Docker and Kubernetes

    Context As companies are continuously seeking ways to become more Agile and embracing DevOps culture ...

  7. docker remote api 的安全隐患

    开启docker的api,首先要知道docker的守护进程daemon,在下认为daemon作为Client和service连接的一个桥梁,负责代替将client的请求传递给service端. 默认情 ...

  8. Docker Rest API使用入门

    Docker Rest API使用入门 系统:Centos7.2, Docker版本信息如下: [python] view plain copy Client: Version:      17.03 ...

  9. 在Mac OSX系统的Docker机上启用Docker远程API功能

    在Mac OSX系统的Docker机上启用Docker远程API功能 作者:chszs,未经博主同意不得转载.经许可的转载需注明作者和博客主页:http://blog.csdn.net/chszs D ...

随机推荐

  1. HDU 4658 Integer Partition (2013多校6 1004题)

    Integer Partition Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others ...

  2. 使用XML向SQL Server 2005批量写入数据——一次有关XML时间格式的折腾经历

    使用XML向SQL Server 2005批量写入数据——一次有关XML时间格式的折腾经历   原文:使用XML向SQL Server 2005批量写入数据——一次有关XML时间格式的折腾经历 常常遇 ...

  3. JS类型判断typeof PK {}.toString.call(obj)

    参考链接:https://www.talkingcoder.com/article/6333557442705696719 先看typeof <!doctype html> <htm ...

  4. 经典相关分析,典型关分析, CCA,Canonical Correlation Analysis,多元变量分析,线性组合,相关系数最大化

    1.从概率论中相关系数推广而来 在概率论中,研究两个变量之间的线性相关情况时,提出了 相关系数 这个概念.做一下推广,如果研究一个变量和多个随机变量之间的线性相关关系时,提出了 全相关系数(或者复相关 ...

  5. 关于push动画中尺寸问题

    由于是在sb中写的VC, 所以在跳转动画时, 就会有一些问题. 这是sb中的约束: 当在push动画时, 在中间界面添加imageView时, 如图: imageView的尺寸是如上图所示, 并不是屏 ...

  6. [Android Memory] 内存分析工具 MAT 的使用

    转载自: http://blog.csdn.net/aaa2832/article/details/19419679 1 内存泄漏的排查方法 Dalvik Debug Monitor Server ( ...

  7. tomcat+mysql在Kubernetes环境

    基于PV作为交换目录将应用最终拷贝入/tomcat/webapps目录 进入Docker后,修改/bin/catalina.sh,加入jdbc的类 \webapps\mytestsql\WEB-INF ...

  8. [java] 模拟QPS

    在WEB服务器端,每日的访问量巨大.在非生产环境需要对服务器进行压力测试,一般使用后台线程和Sleep方式来模拟线上的压力.这里使用ScheduledExecutorService实现一种简单的QPS ...

  9. C# 中的单精度与双精度区别

    单精度浮点数(float)与双精度浮点数(double)的区别: (1)在内存中占有的字节数不同 * 单精度浮点数在机内占4个字节 *双精度浮点数在机内占8个字节 (2)有效数字位数不同 *单精度浮点 ...

  10. 快速实现一个生产者-消费者模型demo

    package jesse.test1; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.Blo ...