duong_dajgja
duong_dajgja

Reputation: 4276

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?

Upvotes: 10

Views: 6055

Answers (2)

BilboX
BilboX

Reputation: 11

I know it's late but btw, if you started it using "detach=True", you can poll it anytime with:

container.attrs["State"]

This returns a dict with all sort of usefull information on the state of the container, including running state, status code, start time, etc...

Btw, container.attrs returns even more informations about container, like runnign command, etc...

Upvotes: 0

David Maze
David Maze

Reputation: 160003

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

Upvotes: 14

Related Questions