Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/fussybeaver/bollard/llms.txt

Use this file to discover all available pages before exploring further.

The container API covers the full lifecycle of Docker containers — from creation through runtime management to removal. All methods are on the Docker struct. Options structs live in bollard::query_parameters and body structs live in bollard::models.

Methods

list_containers

pub async fn list_containers(
    &self,
    options: Option<ListContainersOptions>,
) -> Result<Vec<ContainerSummary>, Error>
Returns a list of containers. By default only running containers are returned. Options: ListContainersOptionsBuilder
FieldTypeDescription
allboolReturn all containers including stopped ones.
limiti64Maximum number of containers to return.
sizeboolInclude the size of container root filesystem.
filters&HashMap<String, Vec<String>>Filter by status, name, label, health, network, id, etc.
Returns: Vec<ContainerSummary>
use bollard::Docker;
use bollard::query_parameters::ListContainersOptionsBuilder;
use std::collections::HashMap;

let docker = Docker::connect_with_socket_defaults().unwrap();

let mut filters = HashMap::new();
filters.insert("health".to_string(), vec!["unhealthy".to_string()]);

let options = ListContainersOptionsBuilder::default()
    .all(true)
    .filters(&filters)
    .build();

let containers = docker.list_containers(Some(options)).await.unwrap();

create_container

pub async fn create_container(
    &self,
    options: Option<CreateContainerOptions>,
    config: ContainerCreateBody,
) -> Result<ContainerCreateResponse, Error>
Prepares a container for a subsequent start_container call. Options: CreateContainerOptionsBuilder
FieldTypeDescription
name&strAssign a name to the container.
platform&strTarget platform (e.g. "linux/amd64").
Config: bollard::models::ContainerCreateBody — key fields:
FieldTypeDescription
imageOption<String>Image name/tag to base the container on.
cmdOption<Vec<String>>Command override for the container entrypoint.
envOption<Vec<String>>Environment variables as KEY=value strings.
exposed_portsOption<HashMap<String, Value>>Ports to expose.
host_configOption<HostConfig>Runtime resource constraints, mounts, port bindings, restart policy, etc.
Returns: ContainerCreateResponse — contains id and warnings.
use bollard::Docker;
use bollard::query_parameters::CreateContainerOptionsBuilder;
use bollard::models::ContainerCreateBody;

let docker = Docker::connect_with_socket_defaults().unwrap();

let options = CreateContainerOptionsBuilder::default()
    .name("my-container")
    .build();

let config = ContainerCreateBody {
    image: Some("alpine:latest".to_string()),
    cmd: Some(vec!["echo".to_string(), "hello".to_string()]),
    ..Default::default()
};

let response = docker.create_container(Some(options), config).await.unwrap();
println!("Created container ID: {}", response.id);

start_container

pub async fn start_container(
    &self,
    container_name: &str,
    options: Option<StartContainerOptions>,
) -> Result<(), Error>
Starts a container that was previously created with create_container. Pass None for options unless you need to supply a detach_keys override. Returns: ()
docker.start_container("my-container", None).await.unwrap();

wait_container

pub fn wait_container(
    &self,
    container_name: &str,
    options: Option<WaitContainerOptions>,
) -> impl Stream<Item = Result<ContainerWaitResponse, Error>>
Blocks until the container stops and returns its exit status. Returns a Stream that yields a single ContainerWaitResponse item. Non-zero exit codes are surfaced as Err(DockerContainerWaitError { error, code }). Options: WaitContainerOptionsBuilder
FieldTypeDescription
condition&strWait until a given condition is met: "not-running" (default), "next-exit", or "removed".
Returns: impl Stream<Item = Result<ContainerWaitResponse, Error>>
use bollard::Docker;
use futures_util::StreamExt;

let docker = Docker::connect_with_socket_defaults().unwrap();

let mut stream = docker.wait_container("my-container", None);
if let Some(result) = stream.next().await {
    match result {
        Ok(resp) => println!("Exit code: {}", resp.status_code),
        Err(e)   => eprintln!("Wait error: {e}"),
    }
}

stop_container

pub async fn stop_container(
    &self,
    container_name: &str,
    options: Option<StopContainerOptions>,
) -> Result<(), Error>
Sends SIGTERM to the container and waits for it to stop, then sends SIGKILL if the timeout elapses. Options: StopContainerOptionsBuilder
FieldTypeDescription
ti64Seconds to wait before forcibly killing the container.
Returns: ()
use bollard::query_parameters::StopContainerOptionsBuilder;

let options = StopContainerOptionsBuilder::default().t(30).build();
docker.stop_container("my-container", Some(options)).await.unwrap();

restart_container

pub async fn restart_container(
    &self,
    container_name: &str,
    options: Option<RestartContainerOptions>,
) -> Result<(), Error>
Options: RestartContainerOptionsBuildert: i64 seconds to wait before kill. Returns: ()

kill_container

pub async fn kill_container(
    &self,
    container_name: &str,
    options: Option<KillContainerOptions>,
) -> Result<(), Error>
Sends a signal to a container without waiting for it to stop. Options: KillContainerOptionsBuilder
FieldTypeDescription
signal&strSignal name or number (e.g. "SIGINT", "9"). Defaults to SIGKILL.
Returns: ()

pause_container

pub async fn pause_container(&self, container_name: &str) -> Result<(), Error>
Freezes all processes in the container using the cgroups freezer. No options. Returns: ()

unpause_container

pub async fn unpause_container(&self, container_name: &str) -> Result<(), Error>
Resumes a container that was paused with pause_container. No options. Returns: ()

rename_container

pub async fn rename_container(
    &self,
    container_name: &str,
    options: RenameContainerOptions,
) -> Result<(), Error>
Options: RenameContainerOptionsBuilder
FieldTypeDescription
name&strThe new name for the container.
Returns: ()

update_container

pub async fn update_container(
    &self,
    container_name: &str,
    config: ContainerUpdateBody,
) -> Result<(), Error>
Updates runtime resource constraints on a running container without restarting it. Config: bollard::models::ContainerUpdateBody — notable fields: memory, memory_swap, cpu_shares, cpu_period, cpu_quota, cpuset_cpus, restart_policy. Returns: ()

remove_container

pub async fn remove_container(
    &self,
    container_name: &str,
    options: Option<RemoveContainerOptions>,
) -> Result<(), Error>
Options: RemoveContainerOptionsBuilder
FieldTypeDescription
vboolRemove anonymous volumes attached to the container.
forceboolForce-remove even if the container is running.
linkboolRemove the specified link and not the underlying container.
Returns: ()

inspect_container

pub async fn inspect_container(
    &self,
    container_name: &str,
    options: Option<InspectContainerOptions>,
) -> Result<ContainerInspectResponse, Error>
Returns low-level information about a container including its state, mounts, network settings, and host config. Options: InspectContainerOptionsBuilder
FieldTypeDescription
sizeboolReturn the sizes of SizeRootFs and SizeRw.
Returns: ContainerInspectResponse

attach_container

pub async fn attach_container(
    &self,
    container_name: &str,
    options: Option<AttachContainerOptions>,
) -> Result<AttachContainerResults, Error>
Attaches to a running container to read its output or write to its stdin over an HTTP upgrade connection. Options: AttachContainerOptionsBuilder
FieldTypeDescription
stdinboolAttach to container stdin.
stdoutboolAttach to container stdout.
stderrboolAttach to container stderr.
streamboolStream live output.
logsboolReplay container logs.
detach_keys&strKey sequence for detaching (e.g. "ctrl-c").
Returns: AttachContainerResults
pub struct AttachContainerResults {
    pub output: Pin<Box<dyn Stream<Item = Result<LogOutput, Error>> + Send>>,
    pub input: Pin<Box<dyn AsyncWrite + Send>>,
}
output is a Stream of LogOutput items. input is an AsyncWrite handle for sending data to the container’s stdin.

attach_container_websocket

pub async fn attach_container_websocket(
    &self,
    container_name: &str,
    options: Option<AttachContainerOptions>,
) -> Result<AttachContainerResults, Error>
Attaches via the WebSocket protocol (GET /containers/{id}/attach/ws). Returns the same AttachContainerResults structure as attach_container.
Requires the websocket Cargo feature. Docker’s WebSocket attach endpoint uses golang.org/x/net/websocket server-side, which has known RFC 6455 compatibility issues. For production workloads prefer attach_container (HTTP upgrade over TCP).

resize_container_tty

pub async fn resize_container_tty(
    &self,
    container_name: &str,
    options: ResizeContainerTTYOptions,
) -> Result<(), Error>
Resizes the TTY of a running container. Only meaningful when the container was created with tty: true. Options: ResizeContainerTTYOptionsBuilder
FieldTypeDescription
hi64Height of the TTY in rows.
wi64Width of the TTY in columns.
Returns: ()

top_processes

pub async fn top_processes(
    &self,
    container_name: &str,
    options: Option<TopOptions>,
) -> Result<ContainerTopResponse, Error>
Lists processes running inside a container, similar to docker top. Options: TopOptionsBuilder
FieldTypeDescription
ps_args&strps arguments to pass (e.g. "aux").
Returns: ContainerTopResponse — contains titles: Vec<String> and processes: Vec<Vec<String>>.

logs

pub fn logs(
    &self,
    container_name: &str,
    options: Option<LogsOptions>,
) -> impl Stream<Item = Result<LogOutput, Error>>
Streams the log output (stdout and/or stderr) of a container. Each item is a LogOutput enum variant. Set follow: true to tail live output; set follow: false (or omit it) to retrieve the existing log and close the stream. Options: LogsOptionsBuilder
FieldTypeDescription
followboolKeep the stream open and follow new log entries.
stdoutboolInclude stdout log lines.
stderrboolInclude stderr log lines.
sincei64Show logs since this Unix timestamp.
untili64Show logs up to this Unix timestamp.
timestampsboolPrefix each line with an RFC 3339 timestamp.
tail&strNumber of lines to show from the end (e.g. "100"), or "all".
Returns: impl Stream<Item = Result<LogOutput, Error>>
use bollard::Docker;
use bollard::query_parameters::LogsOptionsBuilder;
use futures_util::StreamExt;

let docker = Docker::connect_with_socket_defaults().unwrap();

let options = LogsOptionsBuilder::default()
    .stdout(true)
    .stderr(true)
    .tail("50")
    .build();

let mut stream = docker.logs("my-container", Some(options));
while let Some(item) = stream.next().await {
    match item {
        Ok(log) => print!("{log}"),
        Err(e)  => eprintln!("Log error: {e}"),
    }
}

container_changes

pub async fn container_changes(
    &self,
    container_name: &str,
) -> Result<Option<Vec<FilesystemChange>>, Error>
Returns a list of filesystem changes inside the container since it was created. No options parameter. Returns: Option<Vec<FilesystemChange>>None if there are no changes. Each FilesystemChange has a path: String and kind: ChangeType (0 = modified, 1 = added, 2 = deleted).

stats

pub fn stats(
    &self,
    container_name: &str,
    options: Option<StatsOptions>,
) -> impl Stream<Item = Result<ContainerStatsResponse, Error>>
Returns a live stream of resource usage statistics for a container (CPU, memory, network I/O, block I/O). Options: StatsOptionsBuilder
FieldTypeDescription
streamboolStream stats continuously. Set false for a single snapshot.
one_shotboolDo not pre-read stats; get one result and close.
Returns: impl Stream<Item = Result<ContainerStatsResponse, Error>>
stats returns a Stream. Consume it with StreamExt::next or TryStreamExt::try_next. When stream: false, the stream produces exactly one item then closes.

prune_containers

pub async fn prune_containers(
    &self,
    options: Option<PruneContainersOptions>,
) -> Result<ContainerPruneResponse, Error>
Deletes all stopped containers. Options: PruneContainersOptionsBuilder — supports filters (until, label). Returns: ContainerPruneResponse — contains containers_deleted: Vec<String> and space_reclaimed: i64.

upload_to_container

pub async fn upload_to_container(
    &self,
    container_name: &str,
    options: Option<UploadToContainerOptions>,
    tar: BodyType,
) -> Result<(), Error>
Uploads a tar archive and extracts it into the container filesystem. Use bollard::body_full(bytes) for in-memory data or bollard::body_try_stream(stream) for streaming uploads. Options: UploadToContainerOptionsBuilder
FieldTypeDescription
path&strDestination path inside the container (e.g. "/opt").
Returns: ()

upload_to_container_streaming

#[deprecated(since = "0.19.0", note = "Use upload_to_container")]
pub async fn upload_to_container_streaming(
    &self,
    container_name: &str,
    options: Option<UploadToContainerOptions>,
    tar: impl Stream<Item = Bytes> + Send + 'static,
) -> Result<(), Error>
Deprecated since 0.19.0. Use upload_to_container with bollard::body_stream(stream) instead.

download_from_container

pub fn download_from_container(
    &self,
    container_name: &str,
    options: Option<DownloadFromContainerOptions>,
) -> impl Stream<Item = Result<Bytes, Error>>
Downloads a tar archive of a path inside the container’s filesystem. The archive may be compressed with gzip, bzip2, or xz depending on the daemon. Options: DownloadFromContainerOptionsBuilder
FieldTypeDescription
path&strPath inside the container to archive (e.g. "/opt").
Returns: impl Stream<Item = Result<Bytes, Error>>
use bollard::Docker;
use bollard::query_parameters::DownloadFromContainerOptionsBuilder;
use futures_util::TryStreamExt;

let docker = Docker::connect_with_socket_defaults().unwrap();

let options = DownloadFromContainerOptionsBuilder::default()
    .path("/opt")
    .build();

let bytes: Vec<_> = docker
    .download_from_container("my-container", Some(options))
    .try_collect()
    .await
    .unwrap();
println!("Downloaded {} chunks", bytes.len());

export_container

pub fn export_container(
    &self,
    container_name: &str,
) -> impl Stream<Item = Result<Bytes, Error>>
Exports the entire container filesystem as an uncompressed TAR archive. No options parameter. Returns: impl Stream<Item = Result<Bytes, Error>>
use bollard::Docker;
use futures_util::TryStreamExt;
use tokio::io::AsyncWriteExt;

let docker = Docker::connect_with_socket_defaults().unwrap();

let chunks: Vec<_> = docker
    .export_container("my-container")
    .try_collect()
    .await
    .unwrap();

let mut file = tokio::fs::File::create("container.tar").await.unwrap();
for chunk in chunks {
    file.write_all(&chunk).await.unwrap();
}

get_container_archive_info

pub async fn get_container_archive_info(
    &self,
    container_name: &str,
    options: Option<ContainerArchiveInfoOptions>,
) -> Result<PathStatResponse, Error>
Returns filesystem metadata for a path inside the container via a HEAD request. The result is decoded from the X-Docker-Container-Path-Stat response header. Options: ContainerArchiveInfoOptionsBuilder
FieldTypeDescription
path&strPath inside the container to inspect.
Returns: PathStatResponse — contains name, size, file_mode, modification_time, link_target.

create_checkpoint

pub async fn create_checkpoint(
    &self,
    container_name: &str,
    options: CreateCheckpointOptions,
) -> Result<(), Error>
Creates a CRIU checkpoint from a running container. Config: bollard::container::CreateCheckpointOptions
FieldTypeDescription
checkpoint_idStringName for the checkpoint.
checkpoint_dirOption<String>Custom checkpoint storage directory.
exitboolStop the container after creating the checkpoint.
Experimental feature. Requires Docker daemon with experimental features enabled and CRIU installed on the host (Linux only).

list_checkpoints

pub async fn list_checkpoints(
    &self,
    container_name: &str,
    options: Option<ListCheckpointsOptions>,
) -> Result<Vec<Checkpoint>, Error>
Lists all checkpoints for a container. Returns an empty Vec if no checkpoints exist. Options: bollard::container::ListCheckpointsOptionscheckpoint_dir: Option<String>. Returns: Vec<Checkpoint> — each item has a name: String.

delete_checkpoint

pub async fn delete_checkpoint(
    &self,
    container_name: &str,
    checkpoint_id: &str,
    options: Option<DeleteCheckpointOptions>,
) -> Result<(), Error>
Deletes a named checkpoint. Options: bollard::container::DeleteCheckpointOptionscheckpoint_dir: Option<String>. Returns: ()

Container Lifecycle Example

use bollard::Docker;
use bollard::models::ContainerCreateBody;
use bollard::query_parameters::{
    CreateContainerOptionsBuilder,
    StatsOptionsBuilder,
    RemoveContainerOptionsBuilder,
};
use futures_util::StreamExt;

#[tokio::main]
async fn main() {
    let docker = Docker::connect_with_socket_defaults().unwrap();

    // 1. Create
    let options = CreateContainerOptionsBuilder::default()
        .name("demo-container")
        .build();
    let config = ContainerCreateBody {
        image: Some("alpine:latest".to_string()),
        cmd: Some(vec!["sleep".to_string(), "60".to_string()]),
        ..Default::default()
    };
    let created = docker.create_container(Some(options), config).await.unwrap();
    println!("Container ID: {}", created.id);

    // 2. Start
    docker.start_container(&created.id, None).await.unwrap();
    println!("Container started");

    // 3. One-shot stats
    let stats_options = StatsOptionsBuilder::default()
        .stream(false)
        .one_shot(true)
        .build();
    let mut stats_stream = docker.stats(&created.id, Some(stats_options));
    if let Some(Ok(stats)) = stats_stream.next().await {
        println!("CPU usage: {:?}", stats.cpu_stats);
    }

    // 4. Remove (force)
    let rm_options = RemoveContainerOptionsBuilder::default()
        .force(true)
        .build();
    docker.remove_container(&created.id, Some(rm_options)).await.unwrap();
    println!("Container removed");
}

LogOutput Enum

LogOutput is the item type yielded by attach_container, logs, and start_exec streams.
pub enum LogOutput {
    StdErr { message: Bytes },
    StdOut { message: Bytes },
    StdIn  { message: Bytes },
    Console { message: Bytes },
}
It implements Display (UTF-8 lossy decode) and AsRef<[u8]>. The raw bytes can be retrieved with into_bytes() -> Bytes.

Build docs developers (and LLMs) love