Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

docker-py: How to get exit code returned by process running inside container?

My python script uses docker-py to launch a docker container as follows:

client = docker.from_env()
result = client.containers.run(
    image="my-prog-image:latest",
    command=["/etc/my-prog/configs.ini"],
    auto_remove=True,
    network_mode="host",
)

As documented docker-py: containers, the client.containers.run(...) method returns container. How can I retrieve exit code returned by my-prog running inside container?

like image 709
duong_dajgja Avatar asked Jan 02 '19 03:01

duong_dajgja


1 Answers

result.wait() should wait for the container to run to completion, then return its exit code.

However, you'll probably hit some trouble with this since you specify auto_remove=True but do not specify detach=True. run() without detach=True will run the container to completion, then the auto_remove=True option will delete the container, and at that point the status code doesn't exist any more. You might split these steps up explicitly:

client = docker.from_env()
container = client.containers.run(
    image="my-prog-image:latest",
    command=["/etc/my-prog/configs.ini"],
    detach=True,
)
result = container.wait()
container.remove()

(In Docker CLI terms, you've done docker run --rm ... and then are trying to find the container's result with docker ps -a, but the container is gone; I suggest changing it to docker run -d ... without --rm, checking the docker ps output, and then manually docker rm the container. Actually, there's even a docker wait CLI command but it's rarely used.)

like image 85
David Maze Avatar answered Nov 15 '22 05:11

David Maze