From 9c878a2f74b9f1b086c934a9d22967713cb189b5 Mon Sep 17 00:00:00 2001 From: hugues de keyzer Date: Fri, 7 Mar 2025 18:24:14 +0100 Subject: [PATCH] fix waiting for auto_remove container use the same logic as the cli to wait for the exit of a container when running one: ensure that a container run with auto_remove set to True has been removed when the function returns. this prevents a race condition when trying to run another container with the same name directly afterwards. signed-off-by: hugues de keyzer --- docker/models/containers.py | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/docker/models/containers.py b/docker/models/containers.py index 9c9e92c90..e22c0930e 100644 --- a/docker/models/containers.py +++ b/docker/models/containers.py @@ -894,7 +894,24 @@ def run(self, image, command=None, stdout=True, stderr=False, stdout=stdout, stderr=stderr, stream=True, follow=True ) - exit_status = container.wait()['StatusCode'] + if kwargs.get('auto_remove'): + wait_condition = 'removed' + else: + # the wait condition should theoretically be 'next-exit' (as is + # used by the cli), but it may have exited already if its run time + # was very short, which would cause the wait to hang. + # 'not-running' works in both cases. + wait_condition = 'not-running' + try: + exit_status = container.wait(condition=wait_condition)['StatusCode'] + except NotFound: + if wait_condition == 'removed': + # it has been already removed, which is why it was not found, + # so everything fine here. unfortunately, there is no way to + # have its real exit status, so assume success. + exit_status = 0 + else: + raise if exit_status != 0: out = None if not kwargs.get('auto_remove'):