设为首页 收藏本站
查看: 1535|回复: 0

[经验分享] Docker Python API 与 Docker Command

[复制链接]

尚未签到

发表于 2015-4-17 10:12:38 | 显示全部楼层 |阅读模式
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 ")
-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: , 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:': 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)
五.端口绑定


  • 创建busybox的container实例

c.create_container('busybox', 'ls', ports=[1111, 2222])

  • 启动容器时指定端口映射

c.start(container_id, port_bindings={1111: 4567, 2222: None})

  • 指定目标地址和端口

c.start(container_id, port_bindings={1111: ('127.0.0.1', 4567)})

  • 使用随机端口

c.start(container_id, port_bindings={1111: ('127.0.0.1',)})

  • 绑定udp端口

container_id = c.create_container('busybox', 'ls', ports=[(1111, 'udp'), 2222])
c.start(container_id, port_bindings={'1111/udp': 4567, 2222: None})
六.使用外挂存储


  • 创建容器时挂载存储

c.create_container('busybox', 'ls', volumes=['/mnt/vol1', '/mnt/vol2'])

  • 启动容器时挂载存储

c.start(container_id, binds={
'/home/user1/':
{
'bind': '/mnt/vol2',
'ro': False
},
'/var/www':
{
'bind': '/mnt/vol1',
'ro': True
}
})

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-58055-1-1.html 上篇帖子: docker的分层 下篇帖子: Docker web管理界面——Shipyard
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表