Skip to content

Commit 8ab1024

Browse files
Merge pull request #208 from mrk-andreev/issue-104
Add ResourceCleaner for stop containers after exit (#104)
2 parents c5b7b1c + d32e089 commit 8ab1024

File tree

1 file changed

+29
-9
lines changed

1 file changed

+29
-9
lines changed

testcontainers/core/docker_client.py

Lines changed: 29 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,29 @@
1010
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
1111
# License for the specific language governing permissions and limitations
1212
# under the License.
13+
import atexit
1314
import os
1415
import urllib
1516
import docker
17+
from docker.errors import NotFound
1618
from docker.models.containers import Container
19+
1720
from testcontainers.core.utils import inside_container
1821
from testcontainers.core.utils import default_gateway_ip
22+
from testcontainers.core.utils import setup_logger
23+
24+
25+
LOGGER = setup_logger(__name__)
26+
27+
28+
def _stop_container(container):
29+
try:
30+
container.stop()
31+
except NotFound:
32+
pass
33+
except Exception as ex:
34+
LOGGER.warning("failed to shut down container %s with image %s: %s", container.id,
35+
container.image, ex)
1936

2037

2138
class DockerClient(object):
@@ -30,15 +47,18 @@ def run(self, image: str,
3047
stdout: bool = True,
3148
stderr: bool = False,
3249
remove: bool = False, **kwargs) -> Container:
33-
return self.client.containers.run(image,
34-
command=command,
35-
stdout=stdout,
36-
stderr=stderr,
37-
remove=remove,
38-
detach=detach,
39-
environment=environment,
40-
ports=ports,
41-
**kwargs)
50+
container = self.client.containers.run(image,
51+
command=command,
52+
stdout=stdout,
53+
stderr=stderr,
54+
remove=remove,
55+
detach=detach,
56+
environment=environment,
57+
ports=ports,
58+
**kwargs)
59+
atexit.register(_stop_container, container)
60+
61+
return container
4262

4363
def port(self, container_id, port):
4464
port_mappings = self.client.api.port(container_id, port)

0 commit comments

Comments
 (0)