Make `DockerClient` a Context Manager
See original GitHub issueIt’s not obvious that DockerClient
needs to have its close()
method called to clean up resources, which can lead to unclosed sockets. We noticed this using asyncio and pytest together, which complains about unclosed sockets when tearing down test sessions.
Since DockerClient
is wrapping ApiClient
, and ApiClient
inherits its close()
method from requests.Session
, it’s not even obvious from a brief glance source what close()
is for.
I expect that ApiClient
is already a Context Manager, since it would inherit __enter__
and __exit__
from requests.Session
, so the low-level API already has this behaviour.
To make it easier to avoid mistakes, DockerClient
could have __enter__
and __exit__
methods added, identical to requests.Sessions
, which would allow safer usage patterns such as
with docker.from_env() as docker_client:
# Do stuff with docker_client
when that’s feasible.
Issue Analytics
- State:
- Created 2 years ago
- Reactions:2
- Comments:5 (1 by maintainers)
Top GitHub Comments
When this is implemented, it would be great if the docs could also be updated to show context manager usage as the first example new users find: https://docker-py.readthedocs.io/en/stable/client.html#docker.client.from_env
Also the top level README: https://github.com/docker/docker-py#usage
I too was surprised to find a
close()
method and no context manager support to call this automatically.Hi, @TBBle That makes total sense and I´m going to take a look at your request.
@ulyssessouza could you assign this issue to me?
Thanks and have a good day 😃