bollard

repository·master·Indexed 23 days ago

https://github.com/fussybeaver/bollard

An asynchronous Rust client library for interacting with the Docker and Podman APIs. Leveraging Hyper and Tokio, it provides a modern async/await interface for container management, including capabilities for listing, creating, starting, stopping, and inspecting containers, as well as streaming statistics and logs. It supports multiple transport protocols including HTTP, Unix sockets, Windows named pipes, and SSH, with configurable TLS/SSL providers via Rustls.

Tokens
15.1K
Snippets
49
Records
70
Agent score
79%

What's inside bollard

  1. Understanding the bollard-stubs crate

    master

    The bollard-stubs crate is an autogenerated API crate containing data types that represent the underlying data model used by the Bollard API client.

    Important Note: These data types are generated specifically for the Bollard API client and are not intended for direct library consumption. Because they are autogenerated stubs, their structure may change as the parent project evolves.

  2. Connect to the container runtime

    master

    Bollard provides several ways to establish a connection to Docker or Podman depending on your environment and security requirements. All connection methods require a Tokio Runtime.

    Automatically detects the best available socket on the local machine.

    use bollard::Docker;
    Docker::connect_with_local_defaults();

    Podman Connection

    Explicitly connects to Podman with automatic rootless/system socket discovery (Unix only). It probes $DOCKER_HOST, then rootless Podman sockets, then the system Podman socket, and finally falls back to the Docker socket.

    use bollard::Docker;
    Docker::connect_with_podman_defaults();

    Unix Socket / Windows Named Pipe

    Connects to the standard /var/run/docker.sock (Unix) or //./pipe/docker_engine (Windows).

    use bollard::Docker;
    #[cfg(unix)]
    Docker::connect_with_socket_defaults();

    HTTP Connection

    Connects to the location in $DOCKER_HOST, or localhost:2375 if the variable is missing.

    use bollard::Docker;
    Docker::connect_with_http_defaults();

    SSL via Rustls

    Connects via HTTPS using $DOCKER_HOST. It searches $DOCKER_CERT_PATH for key.pem, cert.pem, and ca.pem.

    use bollard::Docker;
    #[cfg(feature = "ssl")]
    Docker::connect_with_ssl_defaults();

    SSH Connection

    Connects via SSH using $DOCKER_HOST or ssh://localhost.

    use bollard::Docker;
    #[cfg(feature = "ssh")]
    Docker::connect_with_ssh_defaults();
  3. Fetch protobuf files for the Bollard project

    master

    To prepare the protobuf files for use within the Bollard project, run the fetch binary. This process fetches remote protobuf files and replaces import statements with local equivalents to ensure they are compatible with prost parsing.

    cargo run --bin fetch --features fetch
  4. How to generate the bollard-stubs code

    master

    The bollard-stubs crate contains autogenerated data types representing the underlying Docker/Podman data model. To regenerate these stubs, you must use the Maven build tool. This process requires a Java JDK 8 environment.

    mvn -D org.slf4j.simpleLogger.defaultLogLevel=debug clean compiler:compile generate-resources
  5. Access models and query parameters

    master

    Bollard re-exports types from bollard-stubs to simplify dependencies.

    • Use bollard::models for request/response data structures (e.g., ContainerCreateBody).
    • Use bollard::query_parameters for options builders (e.g., CreateContainerOptionsBuilder).

    This ensures version compatibility without needing to add bollard-stubs to your own Cargo.toml.

    use bollard::Docker;
    use bollard::models::ContainerCreateBody;
    use bollard::query_parameters::CreateContainerOptionsBuilder;
    
    async fn example() -> Result<(), Box<dyn std::error::Error>> {
        let docker = Docker::connect_with_socket_defaults()?;
    
        let config = ContainerCreateBody {
            image: Some("alpine:latest".to_string()),
            ..Default::default()
        };
    
        let options = CreateContainerOptionsBuilder::default()
            .name("my_container")
            .build();
    
        docker.create_container(Some(options), config).await?;
        Ok(())
    }
  6. Configure Bollard feature flags

    master

    Bollard uses feature flags to manage different transport protocols, security providers, and specialized capabilities.

    Transport Features

    • http: HTTP/TCP connector for remote Docker/Podman.
    • pipe: Unix socket / Windows named pipe for local Docker/Podman.
    • ssh: SSH tunnel connector.

    TLS/SSL Features (Choose one)

    • ssl: Rustls with ring provider (recommended).
    • aws-lc-rs: Rustls with aws-lc-rs provider (FIPS-compliant).
    • ssl_providerless: Rustls without a crypto provider (requires manual CryptoProvider setup).
    • webpki: Use Mozilla's root certificates instead of OS native certs.

    DateTime Features (Choose one)

    Specialized Features

    • buildkit: Full BuildKit support (includes ssl). Requires either chrono or time feature.
    • websocket: WebSocket support for attach_container_websocket using tokio-tungstenite.
    • json_data_content: Include raw JSON payload in deserialization errors (development use).
  7. Understand PingInfo and SwarmStatus

    master

    The PingInfo struct provides metadata extracted from the /_ping endpoint headers. Key fields include:

    • api_version: The daemon's maximum API version.
    • builder_version: The default builder advertised ("1" for classic, "2" for BuildKit).
    • os_type: The daemon's operating system.
    • experimental: Boolean indicating if experimental mode is active.
    • swarm_status: An optional SwarmStatus if the daemon is part of a swarm.

    SwarmStatus contains:

    • node_state: The membership state (e.g., active, inactive, pending).
    • control_available: A boolean that is true if the node is a manager and can serve control-plane requests.
  8. How Docker CLI context resolution works

    master

    Bollard implements Docker CLI context resolution to ensure compatibility with existing Docker configurations. The resolution logic follows a specific hierarchy:

    Precedence Order

    1. DOCKER_HOST: If this environment variable is set and non-empty, it overrides all other settings.
    2. DOCKER_CONTEXT: If set, this environment variable specifies a context name.
    3. currentContext: If DOCKER_CONTEXT is not set, Bollard looks for the currentContext key in the Docker configuration file ($DOCKER_CONFIG/config.json).
    4. Default Host: If no context is identified, the default_host provided to the resolution function is used.

    Context Lookup

    When a context name is identified (via DOCKER_CONTEXT or config.json), Bollard looks up the endpoint host in the context metadata directory: $DOCKER_CONFIG/contexts/meta/<dir>/meta.json.

    • A context name of "default" or an empty string refers to the platform default and returns the default_host immediately without disk lookup.
    • Any other name is searched for within the metadata directory. If the name does not match any meta.json file, an error is returned.