首页 > 解决方案 > 处于分离模式的 docker 容器立即退出

问题描述

我正在使用 docker SDK for python 并尝试创建一个容器。以下是我正在执行的代码:

import docker

client = docker.DockerClient(base_url='tcp://10.41.70.76:2375')
image = client.images.get('siab_user_one')

container = client.containers.run(image.tags[0], detach=True)
container.exec_run("ls") 

但是,上面的代码会抛出以下错误:

Traceback (most recent call last):
  File "/Users/aditya/workspace/term/lib/python3.6/site-packages/docker/api/client.py", line 261, in _raise_for_status
    response.raise_for_status()
  File "/Users/aditya/workspace/term/lib/python3.6/site-packages/requests/models.py", line 940, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 409 Client Error: Conflict for url: http://10.41.70.76:2375/v1.35/containers/ccdb556fb234eeb86b19d37c30e9d64e428bf42a8d2b70784225dcf3c5347859/exec

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "dock.py", line 7, in <module>
    container.exec_run("ls")
  File "/Users/aditya/workspace/term/lib/python3.6/site-packages/docker/models/containers.py", line 196, in exec_run
    workdir=workdir,
  File "/Users/aditya/workspace/term/lib/python3.6/site-packages/docker/utils/decorators.py", line 19, in wrapped
    return f(self, resource_id, *args, **kwargs)
  File "/Users/aditya/workspace/term/lib/python3.6/site-packages/docker/api/exec_api.py", line 80, in exec_create
    return self._result(res, True)
  File "/Users/aditya/workspace/term/lib/python3.6/site-packages/docker/api/client.py", line 267, in _result
    self._raise_for_status(response)
  File "/Users/aditya/workspace/term/lib/python3.6/site-packages/docker/api/client.py", line 263, in _raise_for_status
    raise create_api_error_from_http_exception(e)
  File "/Users/aditya/workspace/term/lib/python3.6/site-packages/docker/errors.py", line 31, in create_api_error_from_http_exception
    raise cls(e, response=response, explanation=explanation)
docker.errors.APIError: 409 Client Error: Conflict ("Container ccdb556fb234eeb86b19d37c30e9d64e428bf42a8d2b70784225dcf3c5347859 is not running")

即使在分离模式下运行容器后,容器也会在创建后立即退出。

PS:docker 镜像在本地,是手动创建的。

它适用于远程图像。

标签: pythondockerdockerpy

解决方案


我认为你需要提供一个命令来防止容器退出,试试这个:

container = client.containers.run(image.tags[0], command=["tail", "-f", "/dev/null"],detach=True)

或使用tty=Truewithdetach=True也会有所帮助


推荐阅读