types-docker

7.1.0.20260409 · active · verified Sat Apr 11

types-docker is a type stub package providing accurate annotations for the `docker` Python library. It enables static type checkers like MyPy or Pyright to verify code using the Docker SDK for Python, ensuring type safety and improving developer experience. This package is part of the `typeshed` project and tracks the `docker` library's versions, aiming for daily updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to the Docker daemon and run a basic 'hello-world' container using the `docker` library, leveraging `types-docker` for static type checking. It assumes Docker Desktop or a Docker daemon is running and accessible.

import docker
import os

def main():
    # Connect to the Docker daemon using environment variables or default socket
    # Requires Docker Desktop or daemon running.
    # For auth, Docker typically uses local socket or environment variables like DOCKER_HOST, DOCKER_TLS_VERIFY, DOCKER_CERT_PATH.
    # No specific auth key needed in os.environ for basic local setup.
    client: docker.DockerClient = docker.from_env()

    print("Docker client connected.")

    # Run a simple 'hello-world' container
    print("Running 'hello-world' container...")
    try:
        container = client.containers.run('hello-world', remove=True, detach=True)
        print(f"Container ID: {container.id}")
        # Wait for container to finish and print its logs
        container.wait()
        logs = container.logs().decode('utf-8')
        print("Container logs:")
        print(logs)
        print("Container finished and removed.")
    except docker.errors.ContainerError as e:
        print(f"Container error: {e}")
    except docker.errors.ImageNotFound as e:
        print(f"Image not found: {e}. Please ensure 'hello-world' image is available or can be pulled.")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

    # Example: List all running containers (if any)
    print("\nListing running containers:")
    for c in client.containers.list():
        print(f" - {c.name} ({c.status})")


if __name__ == "__main__":
    main()

view raw JSON →