pythondockerdockerpy

docker container in detach mode exits instantly


I am using docker SDK for python and trying to create a container. Following is the code I am executing:

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") 

But, the above code throws the following error:

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")

Even after running the container in detached mode, container exits soon after creation.

PS: The docker image is present locally and was created manually.

It works fine with remote images.


Solution

  • I think you need to supply a command to prevent the container from exiting, try this:

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

    or using tty=True with detach=True will help also