需要本机或可访问的 Docker 守护进程在运行;使用后需调用 await docker.close() 释放连接;示例依赖本地已有 alpine:latest 镜像,否则需先拉取。
pip install aiodockerREADME 未说明;需能访问 Docker 守护进程,本身为纯 Python 客户端,不涉及 GPU 或显存。
基于 asyncio 和 aiohttp 的 Docker HTTP API 异步 Python 客户端,让异步程序直接管理容器与镜像
基于 asyncio 和 aiohttp 的异步 Docker API 客户端,让 Python 应用以非阻塞方式管理容器、镜像和网络。
核心能力
- 用 asyncio 协程调用 Docker HTTP API
- 封装 images 与 containers 的列表、创建、启动、删除
- 提供 create_or_replace 按名称创建或替换容器
- 支持异步读取容器日志(container.log)
- 基于 aiohttp 实现异步 HTTP 通信
容易踩的坑
- v0.27.00.27.0最新正式版2026-05-27 · 2026-05-27 07:06 UTC
Breaking Changes
images.push(),images.pull(),images.build(), andimages.import_image()now raiseDockerStreamErrorwhen the Docker Engine reports an error in the progress stream, instead of silently returning the error chunk as part of the response. Existingexcept DockerErrorblocks continue to catch these failures becauseDockerStreamErroris a subclass. Callers that intentionally inspected the returned list for anerrorkey must update their code to catch the exception instead. (#445)images.pull()(and itsDocker.pullalias) no longer triggers the Docker Engine's "pull all tags" behavior whentagis omitted andfrom_imagehas no embedded tag or digest; it now pulls"latest"instead. Callers that relied on the previous all-tags behavior must passtag=""explicitly to opt back in. (#974)- Raise the minimum required
aiohttpto>=3.11.13. Earlier releases contain abreakinside afinallyblock inaiohttp/web_protocol.pywhich Python 3.14 turns into aSyntaxWarningunder PEP 765; the offending code was fixed in aiohttp 3.11.13 (aio-libs/aiohttp#10434, backported in #10476). The 3.10 series is end-of-life. The CI test matrix now exercisesaiohttp~=3.11.0andaiohttp~=3.13.0instead of 3.10 and 3.13. (#1038)
Bug Fixes
- Fix
DockerSwarm.join()so the request body is JSON-encoded. The endpoint previously sent a form-encoded body with aContent-Type: application/jsonheader, causing the daemon to reject the request with a JSON decode error. (#288) - Raise
DockerStreamError(aDockerErrorsubclass) when the Docker Engine reports an error inside the JSON progress stream returned byimages.push(),images.pull(),images.build(), andimages.import_image(). Previously these calls returnedHTTP 200from the Engine even when the upstream registry rejected the operation (e.g.403 Forbiddenfrom Nexus or Docker Hub), and the error chunk was silently included in the returned list, giving callers no way to detect the failure. (#445) - Vendor
FlowControlDataQueuefrom aiohttp since it is deprecated and will be removed in aiohttp 4.0, and pinaiohttp<4.0until the dependency is migrated off the class. (#919) - Fix container membership check by renaming the misspelled
__hasitem__to__contains__so theinoperator works onDockerContainerinstances. (#967) - Default
images.pull()to the"latest"tag when neither atagargument nor an embedded tag/digest infrom_imageis provided, matching the behavior of thedocker pullCLI. (#974) - Fix the inverted condition in
Stream.__del__so aResourceWarningis emitted when a stream is garbage-collected while still holding a live, unclosed response. (#1033) - Stop closing caller-supplied
sessionandconnectorfrom :meth:Docker.close; only resources created internally are torn down, and :meth:Docker.closeis now idempotent. (#1034)
New Features
- Accept a typed
filtersmapping inDockerImages.list()(e.g.{"dangling": ["true"]}), matching the style ofvolumes.list(),networks.list(), andimages.prune(). A pre-encoded JSON string is still accepted for backwards compatibility, but emits aDeprecationWarningand will be removed in 1.0. (#696) - Add :py:meth:
DockerContainer.topto expose thecontainers/{id}/topAPI endpoint, accepting an optionalps_argsargument. (#959)
Miscellaneous
- Document how to bind-mount a host directory via
HostConfig.BindsandHostConfig.Mounts, including bind-propagation options (shared,slave, etc.) and the host-sidemount --make-sharedprerequisite -- by :user:achimnol. (#614) - Document
docker.containers.list(all=True)for listing stopped containers, and note that any keyword argument is forwarded as a query parameter to the Docker Engine ``GET /containers/jso
- v0.26.00.26.02026-02-17 · 2026-02-17 18:53 UTC
查看更新说明
New Features
- Introduce support in the library for the
networks/pruneAPI endpoint. (#691) - Introduce support in the library for the
images/pruneAPI endpoint. (#1001) - Introduce support in the library for the
containers/pruneAPI endpoint. (#1002) - Introduce support in the library for the
volumes/pruneAPI endpoint. (#1003) - Introduce support in the library for the
build/pruneAPI endpoint. (#1007)
Miscellaneous
- Fix entrypoint usage in broken container tests to unblock CI. (#1004)
- Introduce support in the library for the
- v0.25.00.25.02025-12-20 · 2025-12-20 04:51 UTC
查看更新说明
Breaking Changes
- Drop Python 3.9 support and add Python 3.14 support, updating dependencies such as aiohttp (minimum 3.8 to 3.10) and async-timeout (minimum to 5.0) for stdlib TaskGroup and timeout compatibility in Python 3.11+ (#976)
- Replace
**kwargswith explicit parameters inDockerContainer.{stop,restart,kill,delete}()methods, acceptingtfor server-side stop timeout andtimeoutfor client-side request timeouts for consistency with other methods covered in the previous PRs #983 and #990; since this is a BREAKING CHANGE for those who have used thetimeoutargument for theDockerContainer.restart()method calls, the users should replace it withtto keep the intended semantics (#991)
Bug Fixes
- Fix issue authenticating against private registries where the
X-Registry-Authheader would require URL-safe substitutions. (#941)
New Features
- Add support for Docker context endpoints with TLS, reading configuration from
~/.docker/contexts/and respectingDOCKER_CONTEXTenvironment variable andSkipTLSVerifyoption. (#811) - Add SSH protocol support for secure connections to remote Docker instances via "ssh://" URLs with mandatory host key verification (#982)
- Introduce the client-level
timeoutconfiguration which becomes the base timeout configuration while still allowing legacy individual per-API timeouts and merging it into the base timeout. Now setting individual float (total) timeout per-API call is HIGHLY DISCOURAGED in favor of composable timeouts via stdlib'sasyncio.timeout()async context manager. (#983)
Miscellaneous
- Improve the CI workflows to expand the test matrix for aiohttp 3.10/3.13 releases and let tests use the prebuilt artifact to ensure consistency with the release (#980)
- Isolate the docker instance for swarm and service tests via a docker-in-docker compose stack to avoid affecting the user environment (#981)
- Apply the default cooldown period (7 days) to the dependabot configuration (#984)
- v0.24.00.24.02024-11-21 · 2024-11-21 02:23 UTC
查看更新说明
Features
- Added Python 3.13 support (#927)
- Added timeout parameter for push method (#929)
Bugfixes
- Fix
DockerImages.build(),DockerImages.pull(),DockerImages.push()methods' incorrect return type declarations. (#909)
Deprecations and Removals
- Removed Python 3.8 support as it has reached end of life. (#924)
- v0.23.00.23.02024-09-23 · 2024-09-23 04:52 UTC
查看更新说明
Features
- Introduce a sentinel value to
_do_query()and its friend methods to allow configuring per-request infinite timeouts instead of always falling back to the session-level default timeout when setting the timeout argument toNone, and add the timeout arguments to image-related API wrappers (#900)
- Introduce a sentinel value to
用户点评
登录用户的真实使用记录,可按版本和硬件筛选还没有人点评。第一个说出真实体验的人最有价值。
============================== AsyncIO bindings for docker.io
.. image:: https://badge.fury.io/py/aiodocker.svg :target: https://badge.fury.io/py/aiodocker :alt: PyPI version
.. image:: https://img.shields.io/pypi/pyversions/aiodocker.svg :target: https://pypi.org/project/aiodocker/ :alt: Python Versions
.. image:: https://github.com/aio-libs/aiodocker/actions/workflows/ci-cd.yml/badge.svg?branch=main :target: https://github.com/aio-libs/aiodocker/actions/workflows/ci-cd.yml?query=branch%3Amain :alt: GitHub Actions status for the main branch
.. image:: https://codecov.io/gh/aio-libs/aiodocker/branch/main/graph/badge.svg :target: https://codecov.io/gh/aio-libs/aiodocker :alt: Code Coverage
.. image:: https://badges.gitter.im/Join%20Chat.svg :target: https://gitter.im/aio-libs/Lobby :alt: Chat on Gitter
A simple Docker HTTP API wrapper written with asyncio and aiohttp.
Installation
.. code-block:: sh
pip install aiodocker
Development
The recommended developer setup uses uv <https://docs.astral.sh/uv/>_, which
manages the virtualenv and resolves dependencies from the committed
uv.lock so every contributor and CI job builds against the same versions.
.. code-block:: sh
Install uv first: https://docs.astral.sh/uv/getting-started/installation/
uv sync --extra dev --extra lint --extra test --extra doc uv run pre-commit install
The Makefile helpers (make develop, make install, make lint,
make test) all assume uv.
Using pip instead (fallback)
If you can't install uv, you can still bootstrap with pip. The resulting
environment isn't pinned to ``uv.lock``, so versions may drift from CI.
.. code-block:: sh
python -m venv .venv && source .venv/bin/activate
pip install -U pip
pip install -e '.[dev,lint,test,doc]' # in zsh, you need to escape brackets
pre-commit install
Running tests
~~~~~~~~~~~~~
.. code-block:: sh
# Run all tests
make test
# Run individual tests
uv run pytest tests/test_images.py
Building packages
~~~~~~~~~~~~~~~~~
NOTE: Usually you don't need to run this step by yourself.
.. code-block:: sh
uv build
Documentation
=============
http://aiodocker.readthedocs.io
Examples
========
.. code-block:: python
import asyncio
import aiodocker
async def list_things(docker):
print('== Images ==')
for image in (await docker.images.list()):
tags = image['RepoTags'][0] if image['RepoTags'] else ''
print(image['Id'], tags)
print('== Containers ==')
for container in (await docker.containers.list()):
print(f" {container._id}")
async def run_container(docker):
print('== Running a hello-world container ==')
container = await docker.containers.create_or_replace(
config={
'Cmd': ['/bin/ash', '-c', 'echo "hello world"'],
'Image': 'alpine:latest',
},
name='testing',
)
await container.start()
logs = await container.log(stdout=True)
print(''.join(logs))
await container.delete(force=True)
async def main():
docker = aiodocker.Docker()
await list_things(docker)
await run_container(docker)
await docker.close()
if __name__ == "__main__":
asyncio.run(main())