Containers

class aiodocker.containers.DockerContainers(docker: Docker)[source]
container(container_id: str, **kwargs) DockerContainer[source]
async create(config: JSONObject, *, name: str | None = None) DockerContainer[source]
async create_or_replace(name: str, config: JSONObject) DockerContainer[source]
exec(exec_id: str) Exec[source]

Return Exec instance for already created exec object.

async get(container_id: str, **kwargs) DockerContainer[source]
async list(**kwargs) list[DockerContainer][source]
async prune(*, filters: Mapping[str, Any] | None = None) dict[str, Any][source]

Delete stopped containers

Parameters:

filters – Filter expressions to limit which containers are pruned. Available filters: - until: Only remove containers created before given timestamp - label: Only remove containers with (or without, if label!=<key> is used) the specified labels

Returns:

Dictionary containing information about deleted containers and space reclaimed

async run(config: JSONObject, *, auth: Mapping | str | bytes | None = None, name: str | None = None) DockerContainer[source]

Create and start a container.

If container.start() will raise an error the exception will contain a container_id attribute with the id of the container.

Use auth for specifying credentials for pulling absent image from a private registry.

class aiodocker.containers.DockerContainer(docker: Docker, **kwargs)[source]
attach(*, stdout: bool = False, stderr: bool = False, stdin: bool = False, detach_keys: str | None = None, logs: bool = False, timeout: ClientTimeout | Sentinel | None = Sentinel.TOKEN) Stream[source]
async commit(*, repository: str | None = None, tag: str | None = None, message: str | None = None, author: str | None = None, changes: str | Sequence[str] | None = None, config: dict[str, Any] | None = None, pause: bool = True, timeout: float | ClientTimeout | Sentinel | None = Sentinel.TOKEN) dict[str, Any][source]

Commit a container to an image. Similar to the docker commit command.

async delete(*, force: bool = False, v: bool = False, link: bool = False, timeout: float | ClientTimeout | Sentinel | None = Sentinel.TOKEN) None[source]

Remove the container.

Parameters:
  • force – If True, kill the container before removing it (using SIGKILL). If False, the container must be stopped before it can be removed.

  • v – If True, remove anonymous volumes associated with the container.

  • link – If True, remove the specified link (legacy networking feature).

  • timeout – HTTP request timeout for the delete operation.

async exec(cmd: str | Sequence[str], stdout: bool = True, stderr: bool = True, stdin: bool = False, tty: bool = False, privileged: bool = False, user: str = '', environment: Mapping[str, str] | Sequence[str] | None = None, workdir: str | None = None, detach_keys: str | None = None) Exec[source]
async get_archive(path: str) TarFile[source]
property id: str
async kill(*, signal: str | None = None, timeout: float | ClientTimeout | Sentinel | None = Sentinel.TOKEN) None[source]

Kill the container by sending a signal.

Parameters:
  • signal – Signal to send to the container (e.g., “SIGKILL”, “SIGTERM”, “SIGHUP”). Can be a signal name (with or without SIG prefix) or a signal number. If None, uses the default SIGKILL signal.

  • timeout – HTTP request timeout for the kill operation.

log(*, stdout: bool = False, stderr: bool = False, follow: Literal[False] = False, timeout: float | ClientTimeout | Sentinel | None = SENTINEL, **kwargs) list[str][source]
log(*, stdout: bool = False, stderr: bool = False, follow: Literal[True], timeout: float | ClientTimeout | Sentinel | None = SENTINEL, **kwargs) AsyncIterator[str]
async pause() None[source]
async port(private_port: int | str) list[PortInfo] | None[source]
async put_archive(path, data)[source]
async rename(newname) None[source]
async resize(*, h: int, w: int) None[source]
async restart(*, t: int | None = None, timeout: float | ClientTimeout | Sentinel | None = Sentinel.TOKEN) None[source]

Restart the container.

Parameters:
  • t – Number of seconds to wait for the container to stop before killing it. If None, uses the container’s configured stop timeout (default 10 seconds). This is a Docker API parameter that controls the graceful shutdown period.

  • timeout – HTTP request timeout for the restart operation (infinite by default). This controls how long to wait for the Docker daemon to respond, not the container restart duration.

async show(**kwargs) dict[str, Any][source]
async start(**kwargs) None[source]
stats(*, stream: Literal[True] = True, timeout: float | ClientTimeout | Sentinel | None = SENTINEL) AsyncIterator[dict[str, Any]][source]
stats(*, stream: Literal[False], timeout: float | ClientTimeout | Sentinel | None = SENTINEL) list[dict[str, Any]]
async stop(*, t: int | None = None, signal: str | None = None, timeout: float | ClientTimeout | Sentinel | None = Sentinel.TOKEN) None[source]

Stop the container.

Parameters:
  • t – Number of seconds to wait for the container to stop before killing it. If None, uses the container’s configured stop timeout (default 10 seconds). This is a Docker API parameter that controls the graceful shutdown period.

  • signal – Signal to send to the container (e.g., “SIGTERM”, “SIGKILL”). If None, uses the default SIGTERM signal. This parameter may not be supported in older Docker API versions.

  • timeout – HTTP request timeout for the stop operation (infinite by default). This controls how long to wait for the Docker daemon to respond, not the container stop duration.

async top(*, ps_args: str | None = None) dict[str, Any][source]

List processes running inside the container.

Parameters:

ps_args – Arguments passed to ps (e.g. "aux"). If None, the Docker daemon default is used.

Returns:

Dict with Titles (column names) and Processes (list of rows) keys, as returned by the Docker API.

async unpause() None[source]
async wait(*, timeout: float | ClientTimeout | Sentinel | None = Sentinel.TOKEN, **kwargs) dict[str, Any][source]
async websocket(**params) ClientWebSocketResponse[source]

Example

Create a container

import asyncio
import aiodocker

config = {
        "Cmd": ["/bin/ls"],
        "Image": "alpine:latest",
        "AttachStdin": False,
        "AttachStdout": False,
        "AttachStderr": False,
        "Tty": False,
        "OpenStdin": False,
    }

async def create_container():
    docker = aiodocker.Docker()
    container = await docker.containers.create(config=config)
    print(container)
    await docker.close()

if __name__ == "__main__":
    asyncio.run(create_container())

List containers

By default, list() only returns running containers (equivalent to docker ps). To include stopped containers (equivalent to docker ps -a), pass all=True:

import asyncio
import aiodocker

async def list_containers():
    docker = aiodocker.Docker()
    # Running containers only
    running = await docker.containers.list()
    # All containers, including stopped ones
    all_containers = await docker.containers.list(all=True)
    for c in all_containers:
        print(c["Id"], c["State"])
    await docker.close()

if __name__ == "__main__":
    asyncio.run(list_containers())

Any keyword argument is forwarded as a query parameter to the Docker Engine GET /containers/json endpoint, so filters, limit, and size work the same way — see the Docker Engine API reference.

Bind-mount a host directory

containers.create() forwards its config dict to the Docker Engine POST /containers/create endpoint, so any HostConfig field is available. Two ways to bind-mount a host path:

LegacyHostConfig.Binds takes "<host>:<container>[:<opts>]" strings. Options are comma-separated and include ro, rw, z/Z (SELinux relabel), and the propagation modes shared / rshared / slave / rslave / private / rprivate:

config = {
    "Image": "alpine:latest",
    "Cmd": ["/bin/ls", "/data"],
    "HostConfig": {
        "Binds": ["/host/path:/data:ro,shared"],
    },
}

RecommendedHostConfig.Mounts is a list of structured mount specs. Propagation is a named field, which is easier to read and harder to mistype:

config = {
    "Image": "alpine:latest",
    "Cmd": ["/bin/ls", "/data"],
    "HostConfig": {
        "Mounts": [
            {
                "Type": "bind",
                "Source": "/host/path",
                "Target": "/data",
                "ReadOnly": True,
                "BindOptions": {"Propagation": "shared"},
            },
        ],
    },
}

Note

Propagation modes other than rprivate require the host-side mount to already have a compatible propagation type — e.g. shared only works if /host/path is itself a shared mount on the host (see findmnt -o TARGET,PROPAGATION and mount --make-shared). This is a Linux kernel constraint, not an aiodocker limitation; if the host mount is private, Docker will silently downgrade or reject the propagation flag.