Docker.DotNet

repository·master·Indexed 25 days ago

https://github.com/dotnet/docker.dotnet

A fully asynchronous, object-oriented .NET client library for the Docker Remote API. It allows .NET applications to programmatically interact with the Docker daemon to manage containers and images, handle stream responses, and authenticate via TLS or Basic HTTP. The library includes the DockerClient entry point and utilizes SpecGen to generate C# models from the Docker engine-api.

Tokens
2.9K
Snippets
10
Records
11
Agent score
32%

What's inside Docker.DotNet

  1. Understand the structure of generated C# models

    master

    The SpecGen tool generates C# models that combine both QueryString parameters and JSON body models into a single object. This design simplifies the calling API by allowing a single parameter object to represent all data required for a remote API call.

    Query String Parameters

    Parameters intended for the URL query string are decorated with [QueryStringParameter]. To handle optionality, the tool uses nullable types (e.g., bool?). This allows the client to distinguish between a parameter being absent versus being explicitly set to a default value like false.

    Example of a model with query string parameters:

    [DataContract]
    public class ContainerAttachParameters
    {
        [QueryStringParameter("stream", false, typeof(BoolQueryStringConverter))]
        public bool? Stream { get; set; }
    
        [QueryStringParameter("stdin", false, typeof(BoolQueryStringConverter))]
        public bool? Stdin { get; set; }
    }

    JSON Body Parameters

    Parameters intended for the request body are decorated with [DataMember]. The EmitDefaultValue = false setting ensures that if a property's value matches its C# default value, it is omitted from the resulting JSON payload, preventing unnecessary data from being sent to the Docker engine.

    Example of a model with JSON body parameters:

    [DataContract]
    public class Config
    {
        [DataMember(Name = "Hostname", EmitDefaultValue = false)]
        public string Hostname { get; set; }
    
        [DataMember(Name = "Domainname", EmitDefaultValue = false)]
        public string Domainname { get; set; }
    }

    Customizations (Enums and Types)

    SpecGen allows for custom serialization logic to improve API usability. For example, it can map integer values from the engine-api to strongly-typed C# enums. This is achieved via a typeCustomizations map within the tool's source code (specgen.go).

    using System.Runtime.Serialization;
    
    namespace Docker.DotNet.Models
    {
        [DataContract]
        public class ContainerAttachParameters
        {
            [QueryStringParameter("stream", false, typeof(BoolQueryStringConverter))]
            public bool? Stream { get; set; }
    
            [QueryStringParameter("stdin", false, typeof(BoolQueryStringConverter))]
            public bool? Stdin { get; set; }
        }
    }
  2. Manage Docker Containers

    master

    Use the client.Containers property to perform lifecycle operations on containers.

    List containers

    IList<ContainerListResponse> containers = await client.Containers.ListContainersAsync(
        new ContainersListParameters() {
            Limit = 10,
        });

    Create a container

    await client.Containers.CreateContainerAsync(new CreateContainerParameters()
        {
            Image = "fedora/memcached",
            HostConfig = new HostConfig()
            {
                DNS = new[] { "8.8.8.8", "8.8.4.4" }
            }
        });

    Start a container

    await client.Containers.StartContainerAsync(
        "39e3317fd258",
        new ContainerStartParameters()
        );

    Stop a container

    Note: WaitBeforeKillSeconds is an optional uint?. This example waits 30 seconds before killing the container.

    var stopped = await client.Containers.StopContainerAsync(
        "39e3317fd258",
        new ContainerStopParameters
        {
            WaitBeforeKillSeconds = 30
        },
        CancellationToken.None);
    IList<ContainerListResponse> containers = await client.Containers.ListContainersAsync(
    	new ContainersListParameters(){
    		Limit = 10,
        });
  3. Initialize the DockerClient

    master

    The DockerClient is the primary entry point for interacting with the Docker daemon. You initialize it using DockerClientConfiguration.

    Connect to a remote endpoint via URI

    using Docker.DotNet;
    DockerClient client = new DockerClientConfiguration(
        new Uri("http://ubuntu-docker.cloudapp.net:4243"))
         .CreateClient();

    Connect to local Docker (Windows/Mac)

    For local daemons using named pipes (Windows) or Unix sockets (Mac), use the parameterless constructor:

    using Docker.DotNet;
    DockerClient client = new DockerClientConfiguration()
         .CreateClient();

    Connect using specific protocols (Named Pipes or Unix Sockets)

    // Windows Named Pipe
    using Docker.DotNet;
    DockerClient client = new DockerClientConfiguration(
        new Uri("npipe://./pipe/docker_engine"))
         .CreateClient();
    
    // Linux Unix Socket
    using Docker.DotNet;
    DockerClient client = new DockerClientConfiguration(
        new Uri("unix:///var/run/docker.sock"))
         .CreateClient();
    DockerClient client = new DockerClientConfiguration(
        new Uri("http://ubuntu-docker.cloudapp.net:4243"))
         .CreateClient();
  4. Manage Docker Images

    master

    Use the client.Images property to manage images, including pulling them from a registry.

    Pull an image from a registry

    You can pull images anonymously by passing null instead of an AuthConfig object.

    await client.Images.CreateImageAsync(
        new ImagesCreateParameters
        {
            FromImage = "fedora/memcached",
            Tag = "alpha",
        },
        new AuthConfig
        {
            Email = "test@example.com",
            Username = "test",
            Password = "pa$$w0rd"
        },
        new Progress<JSONMessage>());
    await client.Images.CreateImageAsync(
        new ImagesCreateParameters
        {
            FromImage = "fedora/memcached",
            Tag = "alpha",
        },
        new AuthConfig
        {
            Email = "test@example.com",
            Username = "test",
            Password = "pa$$w0rd"
        },
        new Progress<JSONMessage>());
  5. Authenticate with HTTPS (TLS)

    master

    To connect to a Docker instance running with TLS, use the Docker.DotNet.X509 package and the CertificateCredentials type.

    Setup

    Install the X509 package:

    Install-Package Docker.DotNet.X509

    Usage

    var credentials = new CertificateCredentials (new X509Certificate2 ("CertFile", "Password"));
    var config = new DockerClientConfiguration("http://ubuntu-docker.cloudapp.net:4243", credentials);
    DockerClient client = config.CreateClient();

    Handling Self-Signed Certificates

    If the server certificate is self-signed, you can disable validation globally or per credential:

    Globally:

    ServicePointManager.ServerCertificateValidationCallback += (o, c, ch, er) => true;

    Per Credential:

    var creds = new CertificateCredentials(...);
    creds.ServerCertificateValidationCallback += (o, c, ch, er) => true;

    Note: CertFile should be a .pfx (PKCS12) file. If you have .pem files, convert them using openssl.

    var credentials = new CertificateCredentials (new X509Certificate2 ("CertFile", "Password"));
    var config = new DockerClientConfiguration("http://ubuntu-docker.cloudapp.net:4243", credentials);
    DockerClient client = config.CreateClient();
  6. Update generated Docker.DotNet models using SpecGen

    master

    SpecGen is a tool used to reflect the Docker engine-api and generate C# classes for the Docker.DotNet.Models namespace. To update the models to a specific Docker engine-api version, follow these steps from your $GOPATH:

    1. Fetch the desired Docker engine-api version using go get:

      go get -u github.com/docker/docker@<release-tag>

      Note: Because the docker library is not a Go module, the version string may appear as v17.12.0-ce-rc1.0.20200916142827-bd33bbf0497b+incompatible even if it corresponds to a newer version like v19.03.13. Verify the commit hash (e.g., bd33bbf0497b) to ensure it matches the intended Docker version.

    2. Run the update script to regenerate the C# code:

      update-generated-code.cmd

    If changes exist in the engine-api, the Docker.DotNet/Models directory will be updated.

    go get -u github.com/docker/docker@<release-tag>
    update-generated-code.cmd
  7. Handle Docker Stream responses

    master

    Some endpoints, such as monitoring Docker events, return continuous streams. You can consume these using Stream and a CancellationToken to stop the stream.

    CancellationTokenSource cancellation = new CancellationTokenSource();
    Stream stream = await client.System.MonitorEventsAsync(
        new ContainerEventsParameters(), 
        new Progress<JSONMessage>(), 
        cancellation.Token
    );
    // Use a StreamReader to process the stream...

    To continuously stream without cancellation, pass CancellationToken.None.

    CancellationTokenSource cancellation = new CancellationTokenSource();
    Stream stream = await client.System.MonitorEventsAsync(new ContainerEventsParameters(), new Progress<JSONMessage>(), cancellation.Token);
  8. Install Docker.DotNet via NuGet

    master

    You can add the Docker.DotNet library to your project using several methods:

    Package Manager Console

    Install-Package Docker.DotNet

    Visual Studio Search for 'Docker.DotNet' in the NuGet Package Manager and click 'Install'.

    dotnet CLI

    dotnet add package Docker.DotNet

    Development Builds To use development builds without compiling, add the following NuGet source to your NuGet.Config or Visual Studio: https://ci.appveyor.com/nuget/docker-dotnet-hojfmn6hoed7

    dotnet add package Docker.DotNet
  9. Authenticate with Basic HTTP Authentication

    master

    If the Docker instance is secured with Basic HTTP Authentication, use the Docker.DotNet.BasicAuth package.

    Setup

    Install the BasicAuth package:

    Install-Package Docker.DotNet.BasicAuth

    Usage

    var credentials = new BasicAuthCredentials ("YOUR_USERNAME", "YOUR_PASSWORD");
    var config = new DockerClientConfiguration("tcp://ubuntu-docker.cloudapp.net:4243", credentials);
    DockerClient client = config.CreateClient();

    BasicAuthCredentials also supports SecureString for the username and password.

    var credentials = new BasicAuthCredentials ("YOUR_USERNAME", "YOUR_PASSWORD");
    var config = new DockerClientConfiguration("tcp://ubuntu-docker.cloudapp.net:4243", credentials);
    DockerClient client = config.CreateClient();
  10. Handle Docker exceptions

    master

    The following exceptions are commonly thrown by the library:

    • DockerApiException: Thrown when the Docker API returns a non-success result. Common subclasses include:
      • DockerContainerNotFoundException
      • DockerImageNotFoundException
    • TaskCanceledException: Thrown by System.Net.Http.HttpClient when a request times out (default timeout is 100 seconds).
      • Note: Long-running methods like WaitContainerAsync, StopContainerAsync, or methods returning a Stream (e.g., CreateImageAsync) have their timeout set to infinite by this library.
    • ArgumentNullException: Thrown when required parameters are missing or empty.
  11. Specify a specific Docker Remote API version

    master

    By default, the client does not specify a version number in requests. To use a specific version of the Docker Remote API, pass a Version object to CreateClient:

    var config = new DockerClientConfiguration(...);
    DockerClient client = config.CreateClient(new Version(1, 16));
    var config = new DockerClientConfiguration(...);
    DockerClient client = config.CreateClient(new Version(1, 16));