aiodocker

aio-libsApache-2.0活跃维护

基于 asyncio 和 aiohttp 的异步 Docker API 客户端,让 Python 应用以非阻塞方式管理容器、镜像和网络。

Python Docker API client based on asyncio and aiohttp

v0.27.0发布于 2026-05-27 07:06 UTC538star118fork同步于 2026-11-07 07:32 UTC

怎么上手

由 README 提炼,执行前请确认
pip install aiodocker
硬件要求按 README 说明

README 未说明;需能访问 Docker 守护进程,本身为纯 Python 客户端,不涉及 GPU 或显存。

下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

基于 asyncio 和 aiohttp 的 Docker HTTP API 异步 Python 客户端,让异步程序直接管理容器与镜像

基于 asyncio 和 aiohttp 的异步 Docker API 客户端,让 Python 应用以非阻塞方式管理容器、镜像和网络。

核心能力

  • 用 asyncio 协程调用 Docker HTTP API
  • 封装 images 与 containers 的列表、创建、启动、删除
  • 提供 create_or_replace 按名称创建或替换容器
  • 支持异步读取容器日志(container.log)
  • 基于 aiohttp 实现异步 HTTP 通信

容易踩的坑

需要本机或可访问的 Docker 守护进程在运行;使用后需调用 await docker.close() 释放连接;示例依赖本地已有 alpine:latest 镜像,否则需先拉取。

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

5 个版本v0.27.0
  1. v0.27.00.27.0最新正式版2026-05-27 · 2026-05-27 07:06 UTC

    Breaking Changes

    • images.push(), images.pull(), images.build(), and images.import_image() now raise DockerStreamError when the Docker Engine reports an error in the progress stream, instead of silently returning the error chunk as part of the response. Existing except DockerError blocks continue to catch these failures because DockerStreamError is a subclass. Callers that intentionally inspected the returned list for an error key must update their code to catch the exception instead. (#445)
    • images.pull() (and its Docker.pull alias) no longer triggers the Docker Engine's "pull all tags" behavior when tag is omitted and from_image has no embedded tag or digest; it now pulls "latest" instead. Callers that relied on the previous all-tags behavior must pass tag="" explicitly to opt back in. (#974)
    • Raise the minimum required aiohttp to >=3.11.13. Earlier releases contain a break inside a finally block in aiohttp/web_protocol.py which Python 3.14 turns into a SyntaxWarning under 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 exercises aiohttp~=3.11.0 and aiohttp~=3.13.0 instead 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 a Content-Type: application/json header, causing the daemon to reject the request with a JSON decode error. (#288)
    • Raise DockerStreamError (a DockerError subclass) when the Docker Engine reports an error inside the JSON progress stream returned by images.push(), images.pull(), images.build(), and images.import_image(). Previously these calls returned HTTP 200 from the Engine even when the upstream registry rejected the operation (e.g. 403 Forbidden from 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 FlowControlDataQueue from aiohttp since it is deprecated and will be removed in aiohttp 4.0, and pin aiohttp<4.0 until the dependency is migrated off the class. (#919)
    • Fix container membership check by renaming the misspelled __hasitem__ to __contains__ so the in operator works on DockerContainer instances. (#967)
    • Default images.pull() to the "latest" tag when neither a tag argument nor an embedded tag/digest in from_image is provided, matching the behavior of the docker pull CLI. (#974)
    • Fix the inverted condition in Stream.__del__ so a ResourceWarning is emitted when a stream is garbage-collected while still holding a live, unclosed response. (#1033)
    • Stop closing caller-supplied session and connector from :meth:Docker.close; only resources created internally are torn down, and :meth:Docker.close is now idempotent. (#1034)

    New Features

    • Accept a typed filters mapping in DockerImages.list() (e.g. {"dangling": ["true"]}), matching the style of volumes.list(), networks.list(), and images.prune(). A pre-encoded JSON string is still accepted for backwards compatibility, but emits a DeprecationWarning and will be removed in 1.0. (#696)
    • Add :py:meth:DockerContainer.top to expose the containers/{id}/top API endpoint, accepting an optional ps_args argument. (#959)

    Miscellaneous

    • Document how to bind-mount a host directory via HostConfig.Binds and HostConfig.Mounts, including bind-propagation options (shared, slave, etc.) and the host-side mount --make-shared prerequisite -- 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
  2. v0.26.00.26.02026-02-17 · 2026-02-17 18:53 UTC
    查看更新说明

    New Features

    • Introduce support in the library for the networks/prune API endpoint. (#691)
    • Introduce support in the library for the images/prune API endpoint. (#1001)
    • Introduce support in the library for the containers/prune API endpoint. (#1002)
    • Introduce support in the library for the volumes/prune API endpoint. (#1003)
    • Introduce support in the library for the build/prune API endpoint. (#1007)

    Miscellaneous

    • Fix entrypoint usage in broken container tests to unblock CI. (#1004)
  3. 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 **kwargs with explicit parameters in DockerContainer.{stop,restart,kill,delete}() methods, accepting t for server-side stop timeout and timeout for 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 the timeout argument for the DockerContainer.restart() method calls, the users should replace it with t to keep the intended semantics (#991)

    Bug Fixes

    • Fix issue authenticating against private registries where the X-Registry-Auth header would require URL-safe substitutions. (#941)

    New Features

    • Add support for Docker context endpoints with TLS, reading configuration from ~/.docker/contexts/ and respecting DOCKER_CONTEXT environment variable and SkipTLSVerify option. (#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 timeout configuration 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's asyncio.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)
  4. 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)
  5. 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 to None, and add the timeout arguments to image-related API wrappers (#900)

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    ============================== 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())