本文整理汇总了Python中docker.APIClient.remove_container方法的典型用法代码示例。如果您正苦于以下问题:Python APIClient.remove_container方法的具体用法?Python APIClient.remove_container怎么用?Python APIClient.remove_container使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类docker.APIClient
的用法示例。
在下文中一共展示了APIClient.remove_container方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: modify_random_containers
# 需要导入模块: from docker import APIClient [as 别名]
# 或者: from docker.APIClient import remove_container [as 别名]
def modify_random_containers(client: docker.APIClient, amount: int, action: str = 'stop') -> tp.List[dict]:
server_containers = client.containers()
stopped_containers = []
for _ in range(amount):
container = random.choice(server_containers)
if action == 'delete':
client.remove_container(container, force=True)
elif action == 'stop':
client.stop(container)
stopped_containers.append(container)
server_containers.remove(container)
return stopped_containers
示例2: RmContainer
# 需要导入模块: from docker import APIClient [as 别名]
# 或者: from docker.APIClient import remove_container [as 别名]
def RmContainer():
if GOT_DOCKERPY_API < 2:
cli = Client()
try:
cli.remove_container('suri-buildbot')
except:
print "Unable to remove suri-buildbot container"
pass
try:
cli.remove_image('regit/suri-buildbot:latest')
except:
print "Unable to remove suri-buildbot images"
pass
else:
cli = DockerClient()
cli.containers.get('suri-buildbot').remove()
cli.images.remove('regit/suri-buildbot:latest')
sys.exit(0)
示例3: _clean_project_containers
# 需要导入模块: from docker import APIClient [as 别名]
# 或者: from docker.APIClient import remove_container [as 别名]
def _clean_project_containers(worker_api, name_prefix, timeout=5):
"""
Clean cluster node containers and chaincode containers
All containers with the name prefix will be removed.
:param worker_api: Docker daemon url
:param name_prefix: image name prefix
:param timeout: Time to wait for the response
:return: None
"""
logger.debug("Clean project containers, worker_api={}, prefix={}".format(
worker_api, name_prefix))
client = Client(base_url=worker_api, version="auto", timeout=timeout)
containers = client.containers(all=True)
id_removes = [e['Id'] for e in containers if
e['Names'][0].split("/")[-1].startswith(name_prefix)]
for _ in id_removes:
client.remove_container(_, force=True)
logger.debug("Remove container {}".format(_))
示例4: _clean_exited_containers
# 需要导入模块: from docker import APIClient [as 别名]
# 或者: from docker.APIClient import remove_container [as 别名]
def _clean_exited_containers(worker_api):
""" Clean those containers with exited status
This is dangerous, as it may delete temporary containers.
Only trigger this when no one else uses the system.
:param worker_api: Docker daemon url
:return: None
"""
logger.debug("Clean exited containers")
client = Client(base_url=worker_api, version="auto")
containers = client.containers(quiet=True, all=True,
filters={"status": "exited"})
id_removes = [e['Id'] for e in containers]
for _ in id_removes:
logger.debug("exited container to remove, id={}", _)
try:
client.remove_container(_)
except Exception as e:
logger.error("Exception in clean_exited_containers {}".format(e))
示例5: reset_container_host
# 需要导入模块: from docker import APIClient [as 别名]
# 或者: from docker.APIClient import remove_container [as 别名]
def reset_container_host(host_type, worker_api, timeout=15):
""" Try to detect the daemon type
Only wait for timeout seconds.
:param host_type: Type of host: single or swarm
:param worker_api: Docker daemon url
:param timeout: Time to wait for the response
:return: host type info
"""
try:
client = Client(base_url=worker_api, version="auto", timeout=timeout)
containers = client.containers(quiet=True, all=True)
logger.debug(containers)
for c in containers:
client.remove_container(c['Id'], force=True)
logger.debug("cleaning all containers")
except Exception as e:
logger.error("Exception happens when reset host!")
logger.error(e)
return False
try:
images = client.images(all=True)
logger.debug(images)
for i in images:
if i["RepoTags"][0] == "<none>:<none>":
logger.debug(i)
try:
client.remove_image(i['Id'])
except Exception as e:
logger.error(e)
continue
logger.debug("cleaning <none> images")
except Exception as e:
logger.error("Exception happens when reset host!")
logger.error(e)
return False
return setup_container_host(host_type=host_type, worker_api=worker_api)
示例6: ImageBuildException
# 需要导入模块: from docker import APIClient [as 别名]
# 或者: from docker.APIClient import remove_container [as 别名]
#.........这里部分代码省略.........
image_tag = Constants.DOCKER_IMAGE_PREFIX + "{0}".format(random_string[:])
last_line = ""
try:
for line in self.client.build(fileobj=dockerfile, rm=True, tag=image_tag):
print(DockerProxy._decorate(line))
if "errorDetail" in line:
raise DockerProxy.ImageBuildException()
last_line = line
# Return image ID. It's a hack around the fact that docker-py's build image command doesn't return an image
# id.
image_id = get_docker_image_id_from_string(str(last_line))
logging.info("Image ID: {0}".format(image_id))
return str(DockerImage(image_id, image_tag))
except (DockerProxy.ImageBuildException, IndexError) as e:
raise DockerProxy.ImageBuildException(e)
@staticmethod
def _decorate(some_line):
return some_line[11:-4].rstrip()
def image_exists(self, image_str):
"""Checks if an image with the given ID/tag exists locally."""
docker_image = DockerImage.from_string(image_str)
if docker_image.image_id is Constants.DockerNonExistentTag \
and docker_image.image_tag is Constants.DockerNonExistentTag:
raise InvalidDockerImageException("Neither image_id nor image_tag provided.")
for image in self.client.images():
some_id = image["Id"]
some_tags = image["RepoTags"] or [None]
if docker_image.image_id in \
some_id[:(Constants.DOCKER_PY_IMAGE_ID_PREFIX_LENGTH + Constants.DOKCER_IMAGE_ID_LENGTH)]:
return True
if docker_image.image_tag in some_tags:
return True
return False
def terminate_containers(self, container_ids):
""" Terminates containers with given container ids."""
for container_id in container_ids:
try:
if self.container_status(container_id) == ProviderBase.STATUS_RUNNING:
self.stop_container(container_id)
self.terminate_container(container_id)
except NotFound:
pass
def terminate_container(self, container_id):
self.client.remove_container(container_id)
def get_mapped_ports(self, container_id):
container_ins = self.client.inspect_container(container_id)
mapped_ports = container_ins['HostConfig']['PortBindings']
ret_val = []
if mapped_ports is None:
logging.info("No mapped ports for {0}".format(container_id))
return
for k, v in mapped_ports.iteritems():
host_port = v[0]['HostPort']
ret_val.append(host_port)
return ret_val
def get_working_directory(self, container_id):
return self.client.inspect_container(container_id)["Config"]["WorkingDir"]
def get_home_directory(self, container_id):
env_vars = self.client.inspect_container(container_id)["Config"]["Env"]
home = [i for i in env_vars if i.startswith("HOME")]
return home[0].split("=")[1]
def put_archive(self, container_id, tar_file_bytes, target_path_in_container):
""" Copies and unpacks a given tarfile in the container at specified location.
Location must exist in container."""
if self.start_container(container_id) is False:
raise Exception("Could not start container.")
# Prepend file path with /home/ubuntu/. TODO Should be refined.
if not target_path_in_container.startswith("/home/ubuntu/"):
import os
target_path_in_container = os.path.join("/home/ubuntu/", target_path_in_container)
logging.info("target path in container: {0}".format(target_path_in_container))
if not self.client.put_archive(container_id, target_path_in_container, tar_file_bytes):
logging.error(DockerProxy.LOG_TAG + "Failed to copy.")
def get_container_ip_address(self, container_id):
""" Returns the IP Address of given container."""
self.start_container(container_id)
ins = self.client.inspect_container(container_id)
ip_address = str(ins.get("NetworkSettings").get("IPAddress"))
while True:
ip_address = str(ins.get("NetworkSettings").get("IPAddress"))
if ip_address == "":
time.sleep(3)
if ip_address.startswith("1") is True:
break
return ip_address