### Start Docker Container in C# Source: https://github.com/testcontainers/docker.dotnet/blob/main/README.md Code snippet to start a previously created Docker container using its ID with the Docker.DotNet client. Requires the Docker.DotNet library. ```csharp using Docker.DotNet; using Docker.DotNet.Models; await client.Containers.StartContainerAsync( "39e3317fd258", new ContainerStartParameters()); ``` -------------------------------- ### Create and Start Docker Containers using C# Source: https://context7.com/testcontainers/docker.dotnet/llms.txt Creates new Docker containers from specified images and starts them. Supports configuring container name, environment variables, exposed ports, port bindings, restart policies, DNS, labels, and volume mounts. Requires the Docker.DotNet library. ```csharp using Docker.DotNet; using Docker.DotNet.Models; DockerClient client = new DockerClientConfiguration().CreateClient(); // Create container with basic configuration CreateContainerResponse container = await client.Containers.CreateContainerAsync( new CreateContainerParameters { Image = "nginx:latest", Name = "my-nginx-server", Hostname = "nginx-host", Env = new[] { "NGINX_PORT=8080", "ENVIRONMENT=production" }, ExposedPorts = new Dictionary { ["80/tcp"] = default(EmptyStruct) }, HostConfig = new HostConfig { PortBindings = new Dictionary> { ["80/tcp"] = new List { new PortBinding { HostIP = "0.0.0.0", HostPort = "8080" } } }, RestartPolicy = new RestartPolicy { Name = RestartPolicyKind.UnlessStopped }, DNS = new[] { "8.8.8.8", "8.8.4.4" } }, Labels = new Dictionary { ["app"] = "web", ["environment"] = "production" } }); Console.WriteLine($"Container created: {container.ID}"); // Start the container bool started = await client.Containers.StartContainerAsync( container.ID, new ContainerStartParameters()); if (started) { Console.WriteLine("Container started successfully"); } // Create container with volume mounts CreateContainerResponse volumeContainer = await client.Containers.CreateContainerAsync( new CreateContainerParameters { Image = "postgres:15", Name = "my-postgres", Env = new[] { "POSTGRES_PASSWORD=secretpassword" }, HostConfig = new HostConfig { Binds = new[] { "/host/data:/var/lib/postgresql/data", "postgres-backup:/backup:ro" }, Memory = 1024 * 1024 * 1024 // 1GB } }); await client.Containers.StartContainerAsync(volumeContainer.ID, new ContainerStartParameters()); ``` -------------------------------- ### Create Docker Container in C# Source: https://github.com/testcontainers/docker.dotnet/blob/main/README.md Example code for creating a new Docker container from a specified image using the Docker.DotNet client. Allows configuration of host-specific settings like DNS servers. Requires the Docker.DotNet library. ```csharp using Docker.DotNet; using Docker.DotNet.Models; await client.Containers.CreateContainerAsync( new CreateContainerParameters { Image = "fedora/memcached", HostConfig = new HostConfig { DNS = new[] { "8.8.8.8", "8.8.4.4" } } }); ``` -------------------------------- ### HTTP Basic Authentication to Docker (.NET) Source: https://github.com/testcontainers/docker.dotnet/blob/main/README.md This example demonstrates how to authenticate to a Docker instance using basic HTTP authentication. It requires the `Docker.DotNet.Enhanced.BasicAuth` package and uses the `BasicAuthCredentials` class. ```csharp var credentials = new BasicAuthCredentials ("YOUR_USERNAME", "YOUR_PASSWORD"); var config = new DockerClientConfiguration("tcp://ubuntu-docker.cloudapp.net:4243", credentials); DockerClient client = config.CreateClient(); ``` -------------------------------- ### List Docker Containers in C# Source: https://github.com/testcontainers/docker.dotnet/blob/main/README.md Example code to list Docker containers using the Docker.DotNet client. Allows specifying a limit for the number of containers returned. Returns a list of ContainerListResponse objects. Requires the Docker.DotNet library. ```csharp using Docker.DotNet; using Docker.DotNet.Models; IList containers = await client.Containers.ListContainersAsync( new ContainersListParameters { Limit = 10, }); ``` -------------------------------- ### Docker Volume Management in C# (.NET) Source: https://context7.com/testcontainers/docker.dotnet/llms.txt This C# code snippet demonstrates how to interact with Docker volumes using the Docker.DotNet SDK. It covers creating, listing, inspecting, removing, and pruning volumes, providing functionalities for persistent data storage management in .NET applications. Ensure the Docker.DotNet package is installed and Docker is running. ```csharp using Docker.DotNet; using Docker.DotNet.Models; DockerClient client = new DockerClientConfiguration().CreateClient(); // Create volume VolumeResponse volume = await client.Volumes.CreateAsync( new VolumesCreateParameters { Name = "app-data", Driver = "local", DriverOpts = new Dictionary { ["type"] = "none", ["o"] = "bind", ["device"] = "/path/on/host" }, Labels = new Dictionary { ["app"] = "myapp", ["environment"] = "production" } }); Console.WriteLine($"Volume created: {volume.Name}"); Console.WriteLine($"Mountpoint: {volume.Mountpoint}"); // List all volumes VolumesListResponse volumes = await client.Volumes.ListAsync(); Console.WriteLine($"Total volumes: {volumes.Volumes.Count}"); foreach (var vol in volumes.Volumes) { Console.WriteLine($"Name: {vol.Name}"); Console.WriteLine($"Driver: {vol.Driver}"); Console.WriteLine($"Mountpoint: {vol.Mountpoint}"); Console.WriteLine($"Scope: {vol.Scope}"); Console.WriteLine("---"); } // List volumes with filters VolumesListResponse filteredVolumes = await client.Volumes.ListAsync( new VolumesListParameters { Filters = new Dictionary> { ["label"] = new Dictionary { ["app=myapp"] = true }, ["dangling"] = new Dictionary { ["false"] = true } } }); // Inspect volume VolumeResponse volumeInfo = await client.Volumes.InspectAsync("app-data"); Console.WriteLine($"Volume name: {volumeInfo.Name}"); Console.WriteLine($"Created at: {volumeInfo.CreatedAt}"); Console.WriteLine($"Status: {volumeInfo.Status}"); // Remove volume await client.Volumes.RemoveAsync( "app-data", force: false); // Don't force removal if in use Console.WriteLine("Volume removed"); // Prune unused volumes VolumesPruneResponse pruneResult = await client.Volumes.PruneAsync( new VolumesPruneParameters { Filters = new Dictionary> { ["label!"] = new Dictionary { ["keep=true"] = true } } }); Console.WriteLine($"Volumes removed: {string.Join(", ", pruneResult.VolumesDeleted)}"); Console.WriteLine($"Space reclaimed: {pruneResult.SpaceReclaimed} bytes"); ``` -------------------------------- ### Handle Docker Stream Responses (.NET) Source: https://github.com/testcontainers/docker.dotnet/blob/main/README.md This example shows how to handle stream responses from Docker Engine API endpoints, such as monitoring system events. It uses a `Stream` and a `Progress` to process incoming JSON messages. ```csharp Stream stream = await client.System.MonitorEventsAsync( new ContainerEventsParameters(), new Progress(), CancellationToken.None); ``` -------------------------------- ### Handle Docker Exceptions and Timeouts with Docker.NET Source: https://context7.com/testcontainers/docker.dotnet/llms.txt This C# code provides examples of how to gracefully handle various exceptions that can occur during Docker operations using the Docker.NET SDK. It covers specific exceptions like `DockerContainerNotFoundException`, `DockerImageNotFoundException`, general `DockerApiException`, network issues via `HttpRequestException`, and timeouts using `CancellationTokenSource` and client-level timeout configuration. ```csharp using Docker.DotNet; using Docker.DotNet.Models; using System; using System.Net.Http; DockerClient client = new DockerClientConfiguration().CreateClient(); try { // Attempt to inspect non-existent container var container = await client.Containers.InspectContainerAsync("nonexistent"); } catch (DockerContainerNotFoundException ex) { Console.WriteLine($"Container not found: {ex.Message}"); Console.WriteLine($"Status Code: {ex.StatusCode}"); } catch (DockerApiException ex) { Console.WriteLine($"Docker API error: {ex.Message}"); Console.WriteLine($"Status Code: {ex.StatusCode}"); Console.WriteLine($"Response Body: {ex.ResponseBody}"); } catch (HttpRequestException ex) { Console.WriteLine($"Network error: {ex.Message}"); } try { // Attempt to inspect non-existent image var image = await client.Images.InspectImageAsync("nonexistent:tag"); } catch (DockerImageNotFoundException ex) { Console.WriteLine($"Image not found: {ex.Message}"); } try { // Attempt operation with timeout using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); var containers = await client.Containers.ListContainersAsync( new ContainersListParameters { All = true }, cts.Token); } catch (TaskCanceledException ex) { Console.WriteLine($"Operation timed out: {ex.Message}"); } catch (OperationCanceledException ex) { Console.WriteLine($"Operation was cancelled: {ex.Message}"); } // Configure client timeout var config = new DockerClientConfiguration( new Uri("http://localhost:2375"), defaultTimeout: TimeSpan.FromSeconds(30)); DockerClient timeoutClient = config.CreateClient(); try { // All operations will timeout after 30 seconds await timeoutClient.Containers.ListContainersAsync( new ContainersListParameters { All = true }); } finally { timeoutClient.Dispose(); } ``` -------------------------------- ### Initialize Docker Client in C# Source: https://github.com/testcontainers/docker.dotnet/blob/main/README.md Demonstrates how to initialize the Docker.DotNet client to connect to a Docker daemon. Supports remote endpoints, Docker Desktop on Windows via named pipes, and Docker Desktop on Mac via Unix sockets. Requires the Docker.DotNet library. ```csharp using Docker.DotNet; DockerClient client = new DockerClientConfiguration( new Uri("http://ubuntu-docker.cloudapp.net:4243")) .CreateClient(); ``` ```csharp using Docker.DotNet; DockerClient client = new DockerClientConfiguration() .CreateClient(); ``` ```csharp // Default Docker Engine on Windows using Docker.DotNet; DockerClient client = new DockerClientConfiguration( new Uri("npipe://./pipe/docker_engine")) .CreateClient(); ``` ```csharp // Default Docker Engine on Linux using Docker.DotNet; DockerClient client = new DockerClientConfiguration( new Uri("unix:///var/run/docker.sock")) .CreateClient(); ``` -------------------------------- ### Build Docker Image from Dockerfile in C# Source: https://context7.com/testcontainers/docker.dotnet/llms.txt Builds a Docker image from a Dockerfile and build context using Docker.DotNet. It creates a tar archive containing the Dockerfile and other necessary files, then uses the client to build the image with specified tags, build arguments, and labels. Progress is reported via a progress handler. ```csharp using Docker.DotNet; using Docker.DotNet.Models; using System.IO; using ICSharpCode.SharpZipLib.Tar; DockerClient client = new DockerClientConfiguration().CreateClient(); // Create tar archive of build context using (var tarStream = new MemoryStream()) { using (var tarArchive = new TarOutputStream(tarStream, System.Text.Encoding.UTF8)) { tarArchive.IsStreamOwner = false; // Add Dockerfile var dockerfileContent = @" FROM nginx:alpine COPY index.html /usr/share/nginx/html/ EXPOSE 80 CMD [""nginx"", ""-g"", ""daemon off;""] "; var dockerfileBytes = System.Text.Encoding.UTF8.GetBytes(dockerfileContent); var dockerfileEntry = TarEntry.CreateTarEntry("Dockerfile"); dockerfileEntry.Size = dockerfileBytes.Length; tarArchive.PutNextEntry(dockerfileEntry); tarArchive.Write(dockerfileBytes, 0, dockerfileBytes.Length); tarArchive.CloseEntry(); // Add index.html var htmlContent = "

Hello from Docker.DotNet!

"; var htmlBytes = System.Text.Encoding.UTF8.GetBytes(htmlContent); var htmlEntry = TarEntry.CreateTarEntry("index.html"); htmlEntry.Size = htmlBytes.Length; tarArchive.PutNextEntry(htmlEntry); tarArchive.Write(htmlBytes, 0, htmlBytes.Length); tarArchive.CloseEntry(); tarArchive.Close(); } tarStream.Position = 0; // Build image var buildProgress = new Progress(message => { if (!string.IsNullOrEmpty(message.Stream)) { Console.Write(message.Stream); } if (!string.IsNullOrEmpty(message.ErrorMessage)) { Console.WriteLine($"ERROR: {message.ErrorMessage}"); } }); await client.Images.BuildImageFromDockerfileAsync( new ImageBuildParameters { Tags = new[] { "myapp:latest", "myapp:v1.0" }, Dockerfile = "Dockerfile", BuildArgs = new Dictionary { ["BUILD_DATE"] = DateTime.UtcNow.ToString("o"), ["VERSION"] = "1.0.0" }, Labels = new Dictionary { ["maintainer"] = "developer@example.com", ["version"] = "1.0.0" }, Remove = true, // Remove intermediate containers ForceRemove = true, NoCache = false }, tarStream, null, // No auth configs needed for base images from Docker Hub null, // No additional headers buildProgress, CancellationToken.None); Console.WriteLine("Image built successfully"); } ``` -------------------------------- ### Initialize Docker Client in C# Source: https://context7.com/testcontainers/docker.dotnet/llms.txt Demonstrates how to create a DockerClient instance to connect to the Docker daemon. Supports local connections via named pipes or Unix sockets, remote HTTP connections, specifying API versions, custom timeouts, and proper resource disposal. ```csharp using Docker.DotNet; // Connect to local Docker daemon (auto-detects platform) // Windows: npipe://./pipe/docker_engine // Linux/Mac: unix:/var/run/docker.sock DockerClient client = new DockerClientConfiguration() .CreateClient(); // Connect to remote Docker daemon via HTTP DockerClient remoteClient = new DockerClientConfiguration( new Uri("http://192.168.1.100:2375")) .CreateClient(); // Connect to Docker daemon with specific API version DockerClient versionedClient = new DockerClientConfiguration() .CreateClient(new Version(1, 49)); // Custom timeout configuration var config = new DockerClientConfiguration( new Uri("http://localhost:2375"), credentials: null, defaultTimeout: TimeSpan.FromSeconds(120)); DockerClient customClient = config.CreateClient(); // Don't forget to dispose when done using (client) { // Perform Docker operations } ``` -------------------------------- ### Copy Files To and From Docker Containers with Docker.NET Source: https://context7.com/testcontainers/docker.dotnet/llms.txt This C# code demonstrates how to copy files between the host and a Docker container. It utilizes tar archives for the transfer and shows how to both upload a file to a specified path in the container and download a file from the container, extracting its content. Dependencies include Docker.DotNet and ICSharpCode.SharpZipLib. ```csharp using Docker.DotNet; using Docker.DotNet.Models; using System.IO; using ICSharpCode.SharpZipLib.Tar; DockerClient client = new DockerClientConfiguration().CreateClient(); // Copy file TO container using (var tarStream = new MemoryStream()) { // Create tar archive with file using (var tarArchive = new TarOutputStream(tarStream, System.Text.Encoding.UTF8)) { tarArchive.IsStreamOwner = false; var fileContent = "Hello from host!"; var fileBytes = System.Text.Encoding.UTF8.GetBytes(fileContent); var entry = TarEntry.CreateTarEntry("config.txt"); entry.Size = fileBytes.Length; entry.ModTime = DateTime.UtcNow; tarArchive.PutNextEntry(entry); tarArchive.Write(fileBytes, 0, fileBytes.Length); tarArchive.CloseEntry(); } tarStream.Position = 0; // Extract to container await client.Containers.ExtractArchiveToContainerAsync( "my-nginx-server", new CopyToContainerParameters { Path = "/etc/nginx/", NoOverwriteDirNonDir = false, AllowOverwriteDirWithFile = true }, tarStream); Console.WriteLine("File copied to container"); } // Copy file FROM container ContainerArchiveResponse archive = await client.Containers.GetArchiveFromContainerAsync( "my-nginx-server", new ContainerPathStatParameters { Path = "/etc/nginx/nginx.conf", AllowCopyFromContainer = true }, statOnly: false); Console.WriteLine($"File name: {archive.Stat.Name}"); Console.WriteLine($"Size: {archive.Stat.Size} bytes"); Console.WriteLine($"Mode: {archive.Stat.Mode}"); // Extract from tar stream using (var tarStream = new TarInputStream(archive.Stream)) { TarEntry entry; while ((entry = tarStream.GetNextEntry()) != null) { if (entry.IsDirectory) continue; var buffer = new byte[entry.Size]; tarStream.Read(buffer, 0, buffer.Length); string content = System.Text.Encoding.UTF8.GetString(buffer); Console.WriteLine($"File content:\n{content}"); } } ``` -------------------------------- ### Docker Client Authentication with Basic Auth in C# Source: https://context7.com/testcontainers/docker.dotnet/llms.txt Illustrates how to connect to a Docker daemon using HTTP Basic Authentication. Demonstrates providing username and password directly, and using SecureString for enhanced security with the password. ```csharp using Docker.DotNet; using Docker.DotNet.BasicAuth; using System.Security.SecureString; // Authenticate with username and password var credentials = new BasicAuthCredentials("username", "password"); var config = new DockerClientConfiguration( new Uri("http://protected-docker.example.com:2375"), credentials); DockerClient client = config.CreateClient(); // Using SecureString for password (recommended) var securePassword = new System.Security.SecureString(); foreach (char c in "password") { securePassword.AppendChar(c); } securePassword.MakeReadOnly(); var secureCredentials = new BasicAuthCredentials("username", securePassword); var secureConfig = new DockerClientConfiguration( new Uri("http://protected-docker.example.com:2375"), secureCredentials); DockerClient secureClient = secureConfig.CreateClient(); ``` -------------------------------- ### Specify Remote API Version Source: https://github.com/testcontainers/docker.dotnet/blob/main/README.md Demonstrates how to initialize the Docker client with a specific Docker Remote API version. ```APIDOC ## Docker Client Initialization with Specific API Version ### Description Initializes the Docker client to communicate with a specific version of the Docker Remote API, overriding the default behavior. ### Method N/A (Client Configuration) ### Endpoint N/A (Client Configuration) ### Parameters #### Request Body (Implicit) - **DockerClientConfiguration** (object) - Required - An instance of `DockerClientConfiguration`. - **apiVersion** (Version) - Required - The specific version of the Docker Remote API to use (e.g., `new Version(1, 49)`). ### Request Example ```csharp var config = new DockerClientConfiguration(...); // Initialize with appropriate credentials or settings DockerClient client = config.CreateClient(new Version(1, 49)); ``` ``` -------------------------------- ### List and Inspect Docker Images with Docker.DotNet Source: https://context7.com/testcontainers/docker.dotnet/llms.txt Shows how to list all Docker images on a host, filter images based on criteria, inspect a specific image for detailed information, and retrieve its history using the Docker.DotNet library. This includes accessing image metadata such as tags, size, creation date, and configuration. ```csharp using Docker.DotNet; using Docker.DotNet.Models; DockerClient client = new DockerClientConfiguration().CreateClient(); // List all images IList images = await client.Images.ListImagesAsync( new ImagesListParameters { All = true }); foreach (var image in images) { Console.WriteLine($"ID: {image.ID}"); Console.WriteLine($"Tags: {string.Join(", ", image.RepoTags)}"); Console.WriteLine($"Size: {image.Size / 1024 / 1024} MB"); Console.WriteLine($"Created: {DateTimeOffset.FromUnixTimeSeconds(image.Created).DateTime}"); Console.WriteLine("---"); } // List images with filters IList filteredImages = await client.Images.ListImagesAsync( new ImagesListParameters { Filters = new Dictionary> { ["reference"] = new Dictionary { ["nginx:*"] = true }, ["dangling"] = new Dictionary { ["false"] = true } } }); // Inspect image ImageInspectResponse imageInfo = await client.Images.InspectImageAsync("nginx:latest"); Console.WriteLine($"Image ID: {imageInfo.ID}"); Console.WriteLine($"Architecture: {imageInfo.Architecture}"); Console.WriteLine($"OS: {imageInfo.Os}"); Console.WriteLine($"Docker Version: {imageInfo.DockerVersion}"); Console.WriteLine($"Parent: {imageInfo.Parent}"); // Environment variables if (imageInfo.Config?.Env != null) { Console.WriteLine("Environment variables:"); foreach (var env in imageInfo.Config.Env) { Console.WriteLine($" {env}"); } } // Exposed ports if (imageInfo.Config?.ExposedPorts != null) { Console.WriteLine("Exposed ports:"); foreach (var port in imageInfo.Config.ExposedPorts.Keys) { Console.WriteLine($" {port}"); } } // Image layers Console.WriteLine($"Layers: {imageInfo.RootFS?.Layers?.Count ?? 0}"); // Get image history IList history = await client.Images.GetImageHistoryAsync( "nginx:latest"); foreach (var layer in history) { Console.WriteLine($"Created: {DateTimeOffset.FromUnixTimeSeconds(layer.Created).DateTime}"); Console.WriteLine($"Created By: {layer.CreatedBy}"); Console.WriteLine($"Size: {layer.Size} bytes"); Console.WriteLine("---"); } ``` -------------------------------- ### HTTPS Authentication to Docker with Certificates (.NET) Source: https://github.com/testcontainers/docker.dotnet/blob/main/README.md This code illustrates how to authenticate to a Docker instance secured with TLS (HTTPS) using X.509 certificates. It requires the `Docker.DotNet.Enhanced.X509` package and shows how to configure certificate credentials and optionally disable server certificate validation. ```csharp var credentials = new CertificateCredentials(new X509Certificate2("CertFile", "Password")); var config = new DockerClientConfiguration("http://ubuntu-docker.cloudapp.net:4243", credentials); DockerClient client = config.CreateClient(); ``` ```csharp var credentials = new CertificateCredentials(new X509Certificate2("CertFile", "Password")); credentials.ServerCertificateValidationCallback = (o, c, ch, er) => true; ``` -------------------------------- ### Pull Docker Image in C# Source: https://github.com/testcontainers/docker.dotnet/blob/main/README.md Demonstrates how to pull a Docker image from a registry (e.g., Docker Hub) using the Docker.DotNet client. Supports authentication via AuthConfig. Requires the Docker.DotNet library and a Progress handler for status updates. ```csharp using Docker.DotNet; using Docker.DotNet.Models; await client.Images.CreateImageAsync( new ImagesCreateParameters { FromImage = "fedora/memcached", Tag = "alpha", }, new AuthConfig { Email = "test@example.com", Username = "test", Password = "pa$$w0rd" }, new Progress()); ``` -------------------------------- ### List Docker Containers using C# Source: https://context7.com/testcontainers/docker.dotnet/llms.txt Retrieves information about Docker containers. Supports listing all containers (running and stopped) and filtering by status or labels. Requires the Docker.DotNet library. ```csharp using Docker.DotNet; using Docker.DotNet.Models; DockerClient client = new DockerClientConfiguration().CreateClient(); // List all containers (running and stopped) IList allContainers = await client.Containers.ListContainersAsync( new ContainersListParameters { All = true }); foreach (var container in allContainers) { Console.WriteLine($"ID: {container.ID}"); Console.WriteLine($"Name: {string.Join(", ", container.Names)}"); Console.WriteLine($"Image: {container.Image}"); Console.WriteLine($"State: {container.State}"); Console.WriteLine($"Status: {container.Status}"); Console.WriteLine("---"); } // List only running containers with filters IList runningContainers = await client.Containers.ListContainersAsync( new ContainersListParameters { Limit = 10, Filters = new Dictionary> { ["status"] = new Dictionary { ["running"] = true } } }); // List containers by label IList labeledContainers = await client.Containers.ListContainersAsync( new ContainersListParameters { All = true, Filters = new Dictionary> { ["label"] = new Dictionary { ["environment=production"] = true } } }); ``` -------------------------------- ### Interact with Docker Daemon using C# Source: https://context7.com/testcontainers/docker.dotnet/llms.txt This C# code snippet demonstrates how to use the Docker.DotNet library to connect to a Docker daemon, ping it to check accessibility, retrieve detailed version and system information, and monitor real-time Docker events with filtering capabilities. It requires the Docker.DotNet NuGet package and a running Docker daemon. ```csharp using Docker.DotNet; using Docker.DotNet.Models; DockerClient client = new DockerClientConfiguration().CreateClient(); // Ping Docker daemon try { await client.System.PingAsync(); Console.WriteLine("Docker daemon is accessible"); } catch (Exception ex) { Console.WriteLine($"Cannot reach Docker daemon: {ex.Message}"); } // Get Docker version information VersionResponse version = await client.System.GetVersionAsync(); Console.WriteLine($"Docker Version: {version.Version}"); Console.WriteLine($"API Version: {version.APIVersion}"); Console.WriteLine($"Min API Version: {version.MinAPIVersion}"); Console.WriteLine($"Git Commit: {version.GitCommit}"); Console.WriteLine($"Go Version: {version.GoVersion}"); Console.WriteLine($"OS: {version.Os}"); Console.WriteLine($"Arch: {version.Arch}"); Console.WriteLine($"Kernel Version: {version.KernelVersion}"); Console.WriteLine($"Build Time: {version.BuildTime}"); // Get system information SystemInfoResponse systemInfo = await client.System.GetSystemInfoAsync(); Console.WriteLine($"Name: {systemInfo.Name}"); Console.WriteLine($"Server Version: {systemInfo.ServerVersion}"); Console.WriteLine($"Operating System: {systemInfo.OperatingSystem}"); Console.WriteLine($"Total Memory: {systemInfo.MemTotal / 1024 / 1024 / 1024} GB"); Console.WriteLine($"CPUs: {systemInfo.NCPU}"); Console.WriteLine($"Docker Root Dir: {systemInfo.DockerRootDir}"); Console.WriteLine($"Driver: {systemInfo.Driver}"); Console.WriteLine($"\nContainers: {systemInfo.Containers}"); Console.WriteLine($" Running: {systemInfo.ContainersRunning}"); Console.WriteLine($" Paused: {systemInfo.ContainersPaused}"); Console.WriteLine($" Stopped: {systemInfo.ContainersStopped}"); Console.WriteLine($"\nImages: {systemInfo.Images}"); // Monitor Docker events var eventProgress = new Progress(message => { Console.WriteLine($"[{message.Type}] {message.Action} - {message.Actor.ID}"); Console.WriteLine($" Time: {DateTimeOffset.FromUnixTimeSeconds(message.Time).DateTime}"); if (message.Actor.Attributes != null) { foreach (var attr in message.Actor.Attributes) { Console.WriteLine($" {attr.Key}: {attr.Value}"); } } }); // Monitor events with filters await client.System.MonitorEventsAsync( new ContainerEventsParameters { Since = DateTime.UtcNow.AddMinutes(-5).ToString("o"), Filters = new Dictionary> { ["type"] = new Dictionary { ["container"] = true, ["image"] = true }, ["event"] = new Dictionary { ["start"] = true, ["stop"] = true, ["die"] = true } } }, eventProgress, CancellationToken.None); ``` -------------------------------- ### Specify Remote API Version (.NET) Source: https://github.com/testcontainers/docker.dotnet/blob/main/README.md This snippet shows how to initialize the Docker client to specify a particular version of the Docker Remote API for requests. This is useful when you need to ensure compatibility with a specific API version. ```csharp var config = new DockerClientConfiguration(...); DockerClient client = config.CreateClient(new Version(1, 49)); ``` -------------------------------- ### Stop a Container Source: https://github.com/testcontainers/docker.dotnet/blob/main/README.md Demonstrates how to stop a running Docker container by its ID. Includes an optional wait time before forceful killing. ```APIDOC ## POST /containers/{id}/stop ### Description Stops a running container. Optionally waits for a specified duration before killing the container. ### Method POST ### Endpoint /containers/{id}/stop ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the container to stop. #### Query Parameters - **WaitBeforeKillSeconds** (uint?) - Optional - The time in seconds to wait before killing the container. If not specified, the container is stopped immediately. ### Request Example ```csharp // Assuming 'client' is an instance of DockerClient bool hasStopped = await client.Containers.StopContainerAsync( "39e3317fd258", new ContainerStopParameters { WaitBeforeKillSeconds = 30 }, CancellationToken.None); ``` ### Response #### Success Response (200) - **value** (bool) - True if the container was successfully stopped, false otherwise. #### Response Example ```json true ``` ``` -------------------------------- ### HTTP Basic Authentication Source: https://github.com/testcontainers/docker.dotnet/blob/main/README.md Configures the Docker client to connect to a Docker daemon secured with HTTP Basic Authentication. ```APIDOC ## Docker Client Configuration with HTTP Basic Authentication ### Description Connects to a Docker daemon over TCP using HTTP Basic Authentication with provided username and password. ### Method N/A (Client Configuration) ### Endpoint N/A (Client Configuration) ### Parameters #### Request Body (Implicit) - **username** (string or SecureString) - Required - The username for authentication. - **password** (string or SecureString) - Required - The password for authentication. - **dockerHostUri** (string) - Required - The URI of the Docker daemon (e.g., "tcp://ubuntu-docker.cloudapp.net:4243"). ### Request Example ```csharp // Using BasicAuthCredentials for 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(); ``` ``` -------------------------------- ### Monitor Events Stream Source: https://github.com/testcontainers/docker.dotnet/blob/main/README.md Shows how to monitor Docker events, which are streamed continuously. Useful for tracking container lifecycle events. ```APIDOC ## GET /events ### Description Continuously streams events from the Docker daemon. Events include statuses like create, start, stop, and destroy. ### Method GET ### Endpoint /events ### Parameters #### Query Parameters - **ContainerEventsParameters** (object) - Optional - Parameters for filtering container events. - **Progress** - Optional - A progress handler to receive streamed JSON messages. - **CancellationToken** - Optional - A token to cancel the streaming operation. ### Request Example ```csharp // Assuming 'client' is an instance of DockerClient // Assuming JSONMessage is a defined class for event data Stream stream = await client.System.MonitorEventsAsync( new ContainerEventsParameters(), new Progress(), CancellationToken.None); ``` ### Response #### Success Response (200) - **stream** (Stream) - A stream of JSON objects representing Docker events. #### Response Example ```json {"status":"create","id":"dfdf82bd3881","from":"base:latest","time":1374067924} {"status":"start","id":"dfdf82bd3881","from":"base:latest","time":1374067924} ``` ``` -------------------------------- ### Manage Docker Networks with Docker.DotNet SDK in C# Source: https://context7.com/testcontainers/docker.dotnet/llms.txt This C# code snippet utilizes the Docker.DotNet SDK to perform various Docker network operations. It covers creating a custom bridge network with IPAM configuration, listing all available networks, inspecting a specific network's details, connecting a container to a network with specific IP and aliases, disconnecting a container, deleting a network, and pruning unused networks. Dependencies include the Docker.DotNet NuGet package. ```csharp using Docker.DotNet; using Docker.DotNet.Models; DockerClient client = new DockerClientConfiguration().CreateClient(); // Create custom bridge network NetworksCreateResponse network = await client.Networks.CreateNetworkAsync( new NetworksCreateParameters { Name = "my-app-network", Driver = "bridge", CheckDuplicate = true, IPAM = new IPAM { Config = new List { new IPAMConfig { Subnet = "172.25.0.0/16", Gateway = "172.25.0.1" } } }, Options = new Dictionary { ["com.docker.network.bridge.name"] = "br-myapp" }, Labels = new Dictionary { ["environment"] = "production", ["project"] = "myapp" } }); Console.WriteLine($"Network created: {network.ID}"); // List all networks IList networks = await client.Networks.ListNetworksAsync(); foreach (var net in networks) { Console.WriteLine($"Name: {net.Name}"); Console.WriteLine($"ID: {net.ID}"); Console.WriteLine($"Driver: {net.Driver}"); Console.WriteLine($"Scope: {net.Scope}"); Console.WriteLine("---"); } // Inspect network NetworkResponse networkInfo = await client.Networks.InspectNetworkAsync("my-app-network"); Console.WriteLine($"Network Name: {networkInfo.Name}"); Console.WriteLine($"Subnet: {networkInfo.IPAM?.Config?.FirstOrDefault()?.Subnet}"); Console.WriteLine($"Gateway: {networkInfo.IPAM?.Config?.FirstOrDefault()?.Gateway}"); // Connect container to network await client.Networks.ConnectNetworkAsync( "my-app-network", new NetworkConnectParameters { Container = "my-nginx-server", EndpointConfig = new EndpointSettings { IPAddress = "172.25.0.10", Aliases = new[] { "webserver", "nginx" } } }); Console.WriteLine("Container connected to network"); // Disconnect container from network await client.Networks.DisconnectNetworkAsync( "my-app-network", new NetworkDisconnectParameters { Container = "my-nginx-server", Force = true // Force disconnect even if container is running }); // Delete network await client.Networks.DeleteNetworkAsync("my-app-network"); Console.WriteLine("Network deleted"); // Prune unused networks NetworksPruneResponse pruneResult = await client.Networks.PruneNetworksAsync(); Console.WriteLine($"Networks deleted: {string.Join(", ", pruneResult.NetworksDeleted)}"); Console.WriteLine($"Space reclaimed: {pruneResult.SpaceReclaimed} bytes"); ``` -------------------------------- ### Pull and Create Docker Images with Docker.DotNet Source: https://context7.com/testcontainers/docker.dotnet/llms.txt Demonstrates how to pull images from Docker Hub (public and private registries) and import images from tarball streams using the Docker.DotNet library. It includes handling authentication for private registries and progress reporting. ```csharp using Docker.DotNet; using Docker.DotNet.Models; DockerClient client = new DockerClientConfiguration().CreateClient(); // Pull image from Docker Hub (public) var pullProgress = new Progress(message => { Console.WriteLine($"{message.Status} {message.ID} {message.ProgressMessage}"); }); await client.Images.CreateImageAsync( new ImagesCreateParameters { FromImage = "nginx", Tag = "latest" }, null, // No auth for public images pullProgress, CancellationToken.None); Console.WriteLine("Image pulled successfully"); // Pull image with authentication (private registry) await client.Images.CreateImageAsync( new ImagesCreateParameters { FromImage = "registry.example.com/private/app", Tag = "v1.0.0" }, new AuthConfig { Username = "myuser", Password = "mypassword", ServerAddress = "registry.example.com" }, pullProgress, CancellationToken.None); // Pull image from Docker Hub with authentication await client.Images.CreateImageAsync( new ImagesCreateParameters { FromImage = "privateuser/privateimage", Tag = "latest" }, new AuthConfig { Username = "dockerhubuser", Password = "dockerhubpassword", Email = "user@example.com" }, pullProgress); // Import image from tarball stream using (var imageStream = File.OpenRead("/path/to/image.tar")) { await client.Images.CreateImageAsync( new ImagesCreateParameters { FromSrc = "-", // Read from stream Repo = "myimportedimage", Tag = "latest" }, imageStream, null, pullProgress); } ``` -------------------------------- ### Docker Client Authentication with TLS in C# Source: https://context7.com/testcontainers/docker.dotnet/llms.txt Shows how to configure the Docker client for certificate-based authentication (TLS) to connect to a secure Docker daemon. Includes loading certificates from PFX files and handling self-signed certificates by disabling validation. ```csharp using Docker.DotNet; using Docker.DotNet.X509; using System.Security.Cryptography.X509Certificates; // Load certificate from PFX file var credentials = new CertificateCredentials( new X509Certificate2("client.pfx", "certificatePassword")); // Connect with TLS var config = new DockerClientConfiguration( new Uri("https://secure-docker.example.com:2376"), credentials); DockerClient client = config.CreateClient(); // Disable certificate validation (for self-signed certificates) var unsafeCredentials = new CertificateCredentials( new X509Certificate2("client.pfx", "password")); unsafeCredentials.ServerCertificateValidationCallback = (o, c, ch, er) => true; var unsafeConfig = new DockerClientConfiguration( new Uri("https://self-signed-docker.example.com:2376"), unsafeCredentials); DockerClient unsafeClient = unsafeConfig.CreateClient(); ``` -------------------------------- ### Inspect Docker Container Information (.NET) Source: https://context7.com/testcontainers/docker.dotnet/llms.txt Retrieves detailed information about a specific Docker container using its ID or name. This includes metadata such as creation time, state, image, and network settings. It also shows how to fetch size information. ```csharp using Docker.DotNet; using Docker.DotNet.Models; DockerClient client = new DockerClientConfiguration().CreateClient(); // Inspect container by ID or name ContainerInspectResponse containerInfo = await client.Containers.InspectContainerAsync( "my-nginx-server"); Console.WriteLine($"Container ID: {containerInfo.ID}"); Console.WriteLine($"Created: {containerInfo.Created}"); Console.WriteLine($"State Running: {containerInfo.State.Running}"); Console.WriteLine($"State Status: {containerInfo.State.Status}"); Console.WriteLine($"State Started At: {containerInfo.State.StartedAt}"); Console.WriteLine($"State Finished At: {containerInfo.State.FinishedAt}"); Console.WriteLine($"State Exit Code: {containerInfo.State.ExitCode}"); Console.WriteLine($"Image: {containerInfo.Image}"); Console.WriteLine($"Platform: {containerInfo.Platform}"); // Access network information foreach (var network in containerInfo.NetworkSettings.Networks) { Console.WriteLine($"Network: {network.Key}"); Console.WriteLine($" IP Address: {network.Value.IPAddress}"); Console.WriteLine($" Gateway: {network.Value.Gateway}"); Console.WriteLine($" MAC Address: {network.Value.MacAddress}"); } // Inspect with size information ContainerInspectResponse containerWithSize = await client.Containers.InspectContainerAsync( "my-nginx-server", new ContainerInspectParameters { Size = true }); Console.WriteLine($"Size Root Fs: {containerWithSize.SizeRootFs}"); Console.WriteLine($"Size Rw: {containerWithSize.SizeRw}"); ``` -------------------------------- ### Read Docker Container Logs (.NET) Source: https://context7.com/testcontainers/docker.dotnet/llms.txt Demonstrates how to retrieve logs (stdout and stderr) from Docker containers. It covers streaming logs in real-time using a progress callback and fetching logs as a stream for manual processing, with options for timestamps and log history. ```csharp using Docker.DotNet; using Docker.DotNet.Models; using System; using System.Threading; DockerClient client = new DockerClientConfiguration().CreateClient(); // Stream logs with progress callback var progress = new Progress(log => { Console.WriteLine($"[LOG] {log}"); }); await client.Containers.GetContainerLogsAsync( "my-nginx-server", new ContainerLogsParameters { ShowStdout = true, ShowStderr = true, Follow = true, // Stream logs in real-time Timestamps = true, Tail = "100" // Only last 100 lines }, progress, CancellationToken.None); // Get logs as MultiplexedStream for manual processing MultiplexedStream logStream = await client.Containers.GetContainerLogsAsync( "my-nginx-server", new ContainerLogsParameters { ShowStdout = true, ShowStderr = true, Since = DateTime.UtcNow.AddHours(-1).ToString("o") // Last hour }); // Read from multiplexed stream var buffer = new byte[4096]; var result = await logStream.ReadOutputAsync(buffer, 0, buffer.Length, CancellationToken.None); string logContent = System.Text.Encoding.UTF8.GetString(buffer, 0, result.Count); Console.WriteLine(logContent); logStream.Dispose(); ``` -------------------------------- ### Manage Docker Container Lifecycle (.NET) Source: https://context7.com/testcontainers/docker.dotnet/llms.txt Provides methods for controlling the lifecycle of Docker containers, including stopping, restarting, pausing, and removing them. It demonstrates using parameters for graceful shutdowns and force removals. ```csharp using Docker.DotNet; using Docker.DotNet.Models; DockerClient client = new DockerClientConfiguration().CreateClient(); string containerId = "my-nginx-server"; // Stop container gracefully (wait 30 seconds before killing) bool stopped = await client.Containers.StopContainerAsync( containerId, new ContainerStopParameters { WaitBeforeKillSeconds = 30 }, CancellationToken.None); Console.WriteLine($"Container stopped: {stopped}"); // Restart container await client.Containers.RestartContainerAsync( containerId, new ContainerRestartParameters { WaitBeforeKillSeconds = 10 }); Console.WriteLine("Container restarted"); // Pause container (freeze all processes) await client.Containers.PauseContainerAsync(containerId); Console.WriteLine("Container paused"); // Unpause container (resume all processes) await client.Containers.UnpauseContainerAsync(containerId); Console.WriteLine("Container unpaused"); // Kill container immediately with SIGKILL await client.Containers.KillContainerAsync( containerId, new ContainerKillParameters { Signal = "SIGKILL" }); Console.WriteLine("Container killed"); // Remove container (must be stopped first) await client.Containers.RemoveContainerAsync( containerId, new ContainerRemoveParameters { Force = true, // Force removal even if running RemoveVolumes = true // Remove associated volumes }); Console.WriteLine("Container removed"); // Wait for container to stop ContainerWaitResponse waitResponse = await client.Containers.WaitContainerAsync( "long-running-container", CancellationToken.None); Console.WriteLine($"Container exited with status code: {waitResponse.StatusCode}"); ``` -------------------------------- ### Push Docker Image to Registry in C# Source: https://context7.com/testcontainers/docker.dotnet/llms.txt Tags a locally built Docker image with a registry-specific repository name and tag, then pushes it to the specified registry. Handles authentication for private registries and reports push progress. Supports pushing to both private registries and Docker Hub. ```csharp using Docker.DotNet; using Docker.DotNet.Models; DockerClient client = new DockerClientConfiguration().CreateClient(); // Tag image for registry await client.Images.TagImageAsync( "myapp:latest", new ImageTagParameters { RepositoryName = "registry.example.com/mycompany/myapp", Tag = "v1.0.0" }); // Push to private registry var pushProgress = new Progress(message => { if (!string.IsNullOrEmpty(message.Status)) { Console.WriteLine($"{message.Status} {message.ProgressMessage}"); } }); await client.Images.PushImageAsync( "registry.example.com/mycompany/myapp", new ImagePushParameters { Tag = "v1.0.0" }, new AuthConfig { Username = "registryuser", Password = "registrypassword", ServerAddress = "registry.example.com" }, pushProgress, CancellationToken.None); Console.WriteLine("Image pushed successfully"); // Push to Docker Hub await client.Images.TagImageAsync( "myapp:latest", new ImageTagParameters { RepositoryName = "dockerhubuser/myapp", Tag = "latest" }); await client.Images.PushImageAsync( "dockerhubuser/myapp", new ImagePushParameters { Tag = "latest" }, new AuthConfig { Username = "dockerhubuser", Password = "dockerhubpassword" }, pushProgress); ```