Skip to main content

Bollard

A Pythonic, zero-dependency client for the Docker and Podman Engine APIs. Prioritizes descriptive naming, context managers, and cross-platform ease of use.

Installation

pip install bollard

Project Structure

For a detailed overview of the project's architecture, see ARCHITECTURE.md.

Key Features

  • Pythonic API: list_containers instead of ps; remove_image instead of rmi.
  • Zero Dependencies: Uses only the Python standard library (http.client, socket, json).
  • Smart Connection: Auto-detects Docker/Podman sockets (Unix, Windows Pipes, DOCKER_HOST).
  • User Friendly: Auto-starts the Podman machine if the connection fails, healing stale forwarding sockets first; discovery failures raise EndpointDiscoveryError with a last_failure attribute for actionable host messages.
  • Resource Safety: Context managers for client connections and ephemeral containers.
  • Streaming Output: Real-time progress updates for long-running operations like pull and build.
  • .dockerignore Support: Respects .dockerignore files when building images.
  • Full Lifecycle: Manage Containers, Images, Networks, and Volumes.

Usage

Basic Connection

from bollard import DockerClient

with DockerClient() as client:
    for image in client.list_images():
        print(f"Image: {image.tags[0]}")

Managing Containers

with DockerClient() as client:
    # Run a container and get logs
    container = client.run_container("alpine:latest", command="echo 'Hello World'")
    print(container.logs())

    # Stop and remove
    container.stop()
    container.remove(force=True)

Ephemeral Containers (Auto-Cleanup)

Use with client.container(...) to automatically remove the container after the block exits, even if errors occur.

with DockerClient().container("alpine") as container:
    container.exec(["echo", "Running inside container"])
# Container is automatically removed

Streaming Image Operations

Methods pull_image, build_image, and push_image, when called with progress=True, return a generator that yields progress updates.

with DockerClient() as client:
    # Pull an image with progress
    for progress in client.pull_image("alpine:latest", progress=True):
        if "status" in progress:
            print(f"{progress['status']} {progress.get('progress', '')}")

    # Build from directory
    for log in client.build_image(".", "my-app:latest", progress=True):
        if "stream" in log:
            print(log["stream"], end="")

Managing Networks & Volumes

Create and manage Docker networks and volumes using Resource objects.

with DockerClient() as client:
    # Networks
    net = client.create_network("my-net", driver="bridge")
    print(net.id)
    net.remove()

    # Volumes
    vol = client.create_volume("my-data")
    print(vol.name)
    vol.remove()

File Operations

Copy files and directories in and out of containers directly from the Container object.

with DockerClient() as client:
    with client.container("alpine:latest", command="sleep 60") as container:
        # Copy host -> container
        container.copy_to("local_data/", "/dest/path/")

        # Copy container -> host
        container.copy_from("/src/path/data.txt", "local_output/")

Real-world Example: Stirling-PDF Conversion

This example demonstrates running a Stirling-PDF container to convert a "Hello World" HTML file into a PDF and then retrieving it.

from bollard import DockerClient
from time import sleep

env = {"SECURITY_ENABLE_LOGIN": "false"}

with DockerClient().container("frooodle/s-pdf", environment=env) as container:
        # Wait for the container to be ready
        res = ""
        while "HTTP" not in res:
            res = container.exec("curl -s -I http://localhost:8080")
            sleep(1)

        # Convert the HTML to PDF
        container.exec("sh -c 'echo \"<h1>Test PDF</h1>\" > /test.html'")
        result = container.exec(
            'curl -s -w "%{http_code}" '
            "-F 'fileInput=@/test.html' "
            "http://localhost:8080/api/v1/convert/html/pdf "
            "-o /test.pdf"
        )

        # Copy the PDF to the host
        container.copy_from("/test.pdf", ".")

Kubernetes YAML Support

Execute Kubernetes YAML files directly using Podman's native play kube feature.

with DockerClient() as client:
    # Requires a valid Kubernetes YAML file (Pod, Deployment, etc.)
    result = client.play_kube("pod.yaml")

    # Returns the JSON response from Podman describing created resources
    print("Created Pods:", result.get("Pods"))

Metadata

Release files for bollard 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for bollard 0.3.0
File Size Uploaded Provenance Actions
bollard-0.3.0.tar.gz 63.5 kB Without provenance Details for bollard-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for bollard 0.3.0
File Interpreter ABI Platform Actions
bollard-0.3.0-py3-none-any.whl Python 3 none any Details for bollard-0.3.0-py3-none-any.whl

Total release size: 93.7 kB

Release files / bollard-0.3.0.tar.gz

Download URL bollard-0.3.0.tar.gz
Size 63.5 kB
Tags Source
SHA-256 checksum
How to use checksums
4b9fcb340e71f8f71f675c5e6be35ce18b0bfc7be5c8257a041fb5cc02fe5450
BLAKE2b-256 checksum
How to use checksums
4ed675b288358bb84df95a5da93f669ec61e5574a80cd13563f7c8a7ad4ace5e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.12.19 {"installer":{"name":"uv","version":"0.12.19","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / bollard-0.3.0-py3-none-any.whl

Download URL bollard-0.3.0-py3-none-any.whl
Size 30.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
9aa67f3aee91d1df0909d57f76fddf3a15a2e4124457c1188acec6e9edc8ea71
BLAKE2b-256 checksum
How to use checksums
a99189b8d71110b415d34ba1e1cab75128d717fb35b735d9458c9070601fb55d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.12.19 {"installer":{"name":"uv","version":"0.12.19","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for bollard 0.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page