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)
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()
c.info()

返回值 - 字典对象

2.3 版本信息
c.version()
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()
c.ping()

返回值 - 字符串:OK

2.5 登录
c.login(username, password=None, email=None, registry=None)
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)
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)
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)
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)
c.insert(image, url, path)

= docker insert

3.5 导入镜像
c.import_image(src, data=None, repository=None, tag=None)
c.import_image(src, data=None, repository=None, tag=None)
3.6 删除镜像
c.remove_image(image)
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)
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)
c.tag(image, repository, tag=None, force=False)
3.9 docker pull
c.pull(repository, tag=None, stream=False)
c.pull(repository, tag=None, stream=False)
3.10 docker push
c.push(repository, stream=False)
c.push(repository, stream=False)
3.11 在公共镜像注册库中搜索镜像
c.search(term)
c.search(term)
3.12 查看历史
c.history(image)
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)
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)
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)
c.containers(quiet=False, all=False, trunc=True, latest=False, since=None,
             before=None, limit=-1)

docker ps命令一样

4.4 从容器中复制资源
c.copy(container, resource)
c.copy(container, resource)

docker cp命令一样

4.5 检查容器的变化
c.diff(container)
c.diff(container)

= docker diff

4.6 导出container
c.export(container)
c.export(container)

= docker export

4.7 查看容器内部
c.inspect_container(container)
c.inspect_container(container)

= docker inspect 只能查看container

4.8 杀死container
c.kill(container, signal=None)
c.kill(container, signal=None)

= docker kill

4.9 查看日志
c.logs(container, stdout=True, stderr=True, stream=False, timestamps=False)
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)
c.attach(container, stdout=True, stderr=True, stream=False, logs=False)
4.11 端口
c.port(container, private_port)
c.port(container, private_port)

= docker port

4.12 删除container
c.remove_container(container, v=False, link=False)
c.remove_container(container, v=False, link=False)
4.13 重启container
c.restart(container, timeout=10)
c.restart(container, timeout=10)
4.14 停止container
c.stop(container, timeout=10)
c.stop(container, timeout=10)
4.15 监控container
c.top(container)
c.top(container)
4.16 等待container
c.wait(container)
c.wait(container)

五.端口绑定

  1. 创建busybox的container实例
c.create_container('busybox', 'ls', ports=[1111, 2222])
c.create_container('busybox', 'ls', ports=[1111, 2222])
  1. 启动容器时指定端口映射
c.start(container_id, port_bindings={1111: 4567, 2222: None})
c.start(container_id, port_bindings={1111: 4567, 2222: None})
  1. 指定目标地址和端口
c.start(container_id, port_bindings={1111: ('127.0.0.1', 4567)})
c.start(container_id, port_bindings={1111: ('127.0.0.1', 4567)})
  1. 使用随机端口
c.start(container_id, port_bindings={1111: ('127.0.0.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})
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'])
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
        }
})
c.start(container_id, binds={
    '/home/user1/':
        {
            'bind': '/mnt/vol2',
            'ro': False
        },
    '/var/www':
        {
            'bind': '/mnt/vol1',
            'ro': True
        }
})