程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[Python] Python calls docker API

編輯:Python

Introduce

be used for Docker engine API Of Python library . It allows you to perform docker Anything the command does , But it can be in Python In the application —— Run container 、 Manage containers 、 management Swarm etc. .

docker-py git Project address .

install

pip install docker

If you intend to pass TLS Connect to docker host ,docker[tls] Please add your requirements instead , Or use pip install :

pip install docker[tls]

usage

1、 Connect to using the default socket or configuration in the environment Docker:

import docker
client = docker.from_env()

2、 Remote connection Docker

The premise is... On the remote machine docker Turn on remote service , Configuration reference link below :
【docker】 Turn on remote docker Method of service

import docker
client = docker.APIClient(base_url='tcp://ip:2375') # This ip It means that the remote access function is configured in the above operation docker Machine ip

3、run containers Run container

container = client.containers.run(
image="alpine",
command="sh -c 'echo \"hello\" > /insidecontainer/test'",
volumes=["somevolume:/insidecontainer"],
detach=True
)

Common parameters :

  • image Selected image run container , Mandatory
  • command:docker run When the order is executed
  • volumes: Pass in the mount Directory , list , Multiple mount directories can be passed in
    The rule is : [“docker-path:local-path”]
  • detach: Parameter is True when , It will start the container , And immediately return an object
  • environment: Configure the environment variables inside the container , Format [“SOMEVARIABLE=xxx”]

The other parameters , Reference resources git project api Source code :

4、 Enter the started container and execute the command

exec_output = container.exec_run("cat /test")

5、kill And remove the container

container.kill()
container.remove()

6、 Copy files from container to local -get_archive

The obtained file is tar package

 with tempfile.NamedTemporaryFile() as destination:
strm, stat = self.client.get_archive(ctnr, '/vol1/data.txt')
for d in strm:
destination.write(d)
destination.seek(0)

6、 Copy files locally to the container -put_archive

self.client.put_archive(ctnr, '/vol1', test_tar)

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved