### v2 Docker Compose Example Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/migrate-v2-to-v3/code-examples.md This v2 example demonstrates building and starting Docker Compose services from a file, then accessing the running containers. ```csharp using Ductus.FluentDocker.Builders; using Ductus.FluentDocker.Services; using var svc = new Builder() .UseContainer() .UseCompose() .FromFile("docker-compose.yml") .RemoveOrphans() .WaitForHttp("web", "http://localhost:8000/health") .Build() .Start(); var containers = svc.Containers; ``` -------------------------------- ### Kernel Setup with Docker CLI (v3) Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/migrate-v2-to-v3/api-mapping.md Required kernel setup before using any builders in v3. This example uses the default Docker CLI. ```csharp using var kernel = FluentDockerKernel.Create() .WithDockerCli("docker", d => d.AsDefault()) .Build(); ``` -------------------------------- ### Build All Examples Source: https://github.com/mariotoffia/fluentdocker/blob/master/Examples/README.md Navigate to the Examples directory and run 'dotnet build' to build all the example projects. ```bash cd Examples dotnet build ``` -------------------------------- ### Quick Start: Podman CLI Container Management Source: https://github.com/mariotoffia/fluentdocker/blob/master/FluentDocker/README.md Illustrates using FluentDocker with the Podman CLI to manage containers. This example deploys an Nginx container using a Podman driver. ```csharp await using var kernel = FluentDockerKernel.Create() .WithPodmanCli("podman", d => d.AsDefault()) .Build(); await using var results = await new Builder() .WithinDriver("podman", kernel) .UseContainer(c => c .UseImage("docker.io/library/nginx:alpine") .ExposePort("80 المحتوى")) .BuildAsync(); ``` -------------------------------- ### FluentDocker Kernel and Container Resource Setup Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/testing/core.md This example demonstrates setting up a Docker CLI kernel and a Redis container resource using FluentDocker's fluent API. The container is configured to use a specific image, name, and wait for a port to be available. ```csharp var kernel = await FluentDockerKernel.Create() .WithDockerCli("docker-cli", d => d.AsDefault()) .BuildAsync(); await using var resource = new ContainerResource(kernel, builder => builder.UseImage("redis:alpine") .WithName("test-redis") .WaitForPort("6379/tcp")); await resource.InitializeAsync(); // Use the container var logs = await resource.GetLogsAsync(); ``` -------------------------------- ### Legacy xUnit Redis Test Setup Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/testing/migration-from-legacy.md Example of configuring a Redis container using the legacy FluentDocker.XUnit package. ```csharp using Ductus.FluentDocker.XUnit; public class RedisFixture : FluentDockerTestBase { protected override void ConfigureContainer(IContainerBuilder builder) { builder .UseImage("redis:alpine") .ExposePort("6379") .WaitForPort("6379/tcp"); } } public class RedisTests : IClassFixture { private readonly RedisFixture _fixture; public RedisTests(RedisFixture fixture) => _fixture = fixture; [Fact] public void IsRunning() { Assert.Equal(ServiceRunningState.Running, _fixture.Container.State); } } ``` -------------------------------- ### Example Run Output Source: https://github.com/mariotoffia/fluentdocker/blob/master/Examples/EventDriven/README.md This output shows a typical execution of the event-driven example, including the number of hosts, Docker socket status, service startup confirmation, and a list of captured Docker events. ```bash Number of hosts:1 unix:///var/run/docker.sock native Running Spinning up a postgres and wait for ready state... Service is running Events: FluentDocker.Model.Events.ContainerCreateEvent FluentDocker.Model.Events.NetworkConnectEvent FluentDocker.Model.Events.ContainerStartEvent ``` -------------------------------- ### Create and Start Nginx Container Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/containers.md Demonstrates how to create and automatically start an Nginx container using FluentDocker. The `Build()` method handles both creation and initiation. ```csharp using var results = new Builder() .WithinDriver("docker", kernel) .UseContainer(c => c .UseImage("nginx:alpine")) .Build(); var container = results.Containers.First(); // Container is already running at this point ``` -------------------------------- ### Run Simple Example Source: https://github.com/mariotoffia/fluentdocker/blob/master/Examples/README.md Navigate to the Simple directory and run the .NET project to demonstrate basic container creation and management. ```bash cd Simple && dotnet run ``` -------------------------------- ### Execute Commands on Container Lifecycle (v3) Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/migrate-v2-to-v3/code-examples.md This example demonstrates how to use FluentDocker v3 to execute commands automatically when a container starts or is being disposed. This is useful for setup and cleanup tasks. ```csharp // v3: Execute commands automatically on container start/stop using var results = new Builder() .WithinDriver("docker", kernel) .UseContainer(c => c .UseImage("ubuntu:22.04") .WithCommand("sleep", "infinity") .ExecuteOnRunning("mkdir", "-p", "/app/data") .ExecuteOnRunning("chmod", "777", "/app/data") .ExecuteOnDisposing("rm", "-rf", "/app/data/temp")) .Build(); ``` -------------------------------- ### Create and Start Container Source: https://github.com/mariotoffia/fluentdocker/blob/master/README.md Demonstrates how to create and start a new container using the Docker CLI driver. It configures an Nginx image, exposes port 80, and retrieves container configuration and stats. ```csharp using var results = new Builder() .WithinDockerCli("docker", kernel) .UseContainer(c => c .UseImage("nginx:latest") .ExposePort("80")) .Build(); var container = results.Containers.First(); // Get configuration var config = container.GetConfiguration(true); // Container stats (v3) var stats = await container.GetStatsAsync(); Console.WriteLine($"CPU: {stats.CpuPercent:F2}%"); ``` -------------------------------- ### New xUnit Redis Test Setup with XunitContainerFixture Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/testing/migration-from-legacy.md Example of configuring a Redis container using the new FluentDocker.Testing.Xunit package and XunitContainerFixture. ```csharp using FluentDocker.Testing.Xunit; public class RedisFixture : XunitContainerFixture { public RedisFixture() { InitializeAsync(builder => builder .UseImage("redis:alpine") .ExposePort("6379") .WaitForPort("6379/tcp") ).GetAwaiter().GetResult(); } } public class RedisTests : IClassFixture { private readonly RedisFixture _fixture; public RedisTests(RedisFixture fixture) => _fixture = fixture; [Fact] public async Task IsRunning() { var info = await _fixture.Container.InspectAsync(); Assert.True(info.State.Running); } } ``` -------------------------------- ### Custom Image Testing Setup Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/images.md Sets up a custom Docker image for testing, including installing dependencies and exposing ports. This is part of a test class implementing IDisposable. ```csharp public class CustomImageTest : IDisposable { private readonly FluentDockerKernel _kernel; private readonly BuildResults _results; public CustomImageTest() { _kernel = FluentDockerKernel.Create() .WithDockerCli("docker", d => d.AsDefault()) .Build(); _results = new Builder() .WithinDriver("docker", _kernel) .UseImage("test-app:latest", img => img .From("node:18-alpine") .UseWorkDir("/app") .Copy("./test-fixtures/", "/app/") .Run("npm install") .ExposePorts(3000) .Command("npm", "test")) .UseContainer(c => c .UseImage("test-app:latest") .ExposePort(3000, 3000) .WaitForPort("3000/tcp", 30000)) .Build(); } [Fact] public async Task App_ReturnsHealthy() { var container = _results.Containers.First(); var endpoint = container.ToHostExposedEndpoint("3000/tcp"); var response = await $"http://localhost:{endpoint.Port}/health".Wget(); Assert.Contains("healthy", response); } public void Dispose() { _results?.Dispose(); _kernel?.Dispose(); } } ``` -------------------------------- ### Run ComposeV2 Example Source: https://github.com/mariotoffia/fluentdocker/blob/master/Examples/README.md Navigate to the ComposeV2 directory and run the .NET project to demonstrate Docker Compose V2, directory copying, and template string interpolation. ```bash cd ComposeV2 && dotnet run ``` -------------------------------- ### Standard Container with Podman CLI Source: https://github.com/mariotoffia/fluentdocker/blob/master/README.md Example of creating and configuring a standard container using the Podman CLI driver. It mirrors the Docker CLI example, setting up an Nginx image, exposing port 80, and waiting for the port. ```csharp await using var podmanResults = await new Builder() .WithinPodmanCli("podman", kernel) .UseContainer(c => c .UseImage("nginx:alpine") .ExposePort("80") .WaitForPort("80/tcp", 30000)) .BuildAsync(); var podmanEndpoint = podmanResults.Containers.First() .ToHostExposedEndpoint("80/tcp"); ``` -------------------------------- ### Run DockerInDockerLinux Example Source: https://github.com/mariotoffia/fluentdocker/blob/master/Examples/README.md Navigate to the DockerInDockerLinux directory and run the .NET project to show interaction with Docker when running inside a Docker container. ```bash cd DockerInDockerLinux && dotnet run ``` -------------------------------- ### CMD and ENTRYPOINT Dockerfile Instructions Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/images.md Specifies the default command to run when a container starts or sets the default executable. ```csharp .Command("node", "app.js") .Entrypoint("docker-entrypoint.sh") ``` -------------------------------- ### Multi-Stage Build Example Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/images.md Demonstrates a multi-stage Docker build for a Node.js application, copying build artifacts from a builder stage to a production stage. ```csharp var results = new Builder() .WithinDriver("docker", kernel) .UseImage("myapp:latest", img => img // Build stage .From("node:18-alpine", "builder") .UseWorkDir("/app") .Copy("package*.json", "./") .Run("npm ci") .Copy(".", ".") .Run("npm run build") // Production stage .From("nginx:alpine") .Copy("/app/dist", "/usr/share/nginx/html", fromAlias: "builder") .ExposePorts(80)) .Build(); ``` -------------------------------- ### Install act with Homebrew Source: https://github.com/mariotoffia/fluentdocker/blob/master/DEVELOPMENT.md Installs the 'act' tool, which allows local testing of GitHub Actions workflows, using Homebrew. ```bash # Install act with Homebrew brew install act ``` -------------------------------- ### NUnit Podman Kubernetes Setup Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/testing/nunit.md Shows how to set up a Kubernetes deployment using Podman for NUnit tests, including custom kernel factory configuration. ```csharp [OneTimeSetUp] public async Task Setup() { (_kernel, _resource) = await NUnitResourceHelpers.CreatePodmanKubernetesAsync( new KubePlayConfig { YamlPath = "pod.yaml" }, kernelFactory: async () => await FluentDockerKernel.Create() .WithPodmanCli("podman", d => d.AsDefault()) .BuildAsync()); } ``` -------------------------------- ### RUN Dockerfile Instruction Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/images.md Illustrates executing commands within a Docker build stage, such as package installation. ```csharp .Run("apt-get update && apt-get install -y curl") .Run("npm install") ``` -------------------------------- ### NUnit Docker Compose Setup Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/testing/nunit.md Illustrates setting up Docker Compose services for NUnit tests using NUnitResourceHelpers.CreateComposeAsync. ```csharp [OneTimeSetUp] public async Task Setup() { (_kernel, _resource) = await NUnitResourceHelpers.CreateComposeAsync( c => c .WithComposeFile("docker-compose.yml") .WithRemoveOrphans()); } ``` -------------------------------- ### Stop and Start Container Cycle Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/containers.md Shows how to stop a running container and then start it again using FluentDocker's container service methods. ```csharp using var results = new Builder() .WithinDriver("docker", kernel) .UseContainer(c => c .UseImage("nginx:alpine")) .Build(); var container = results.Containers.First(); // Stop the running container await container.StopAsync(); // Start again await container.StartAsync(); ``` -------------------------------- ### Install FluentDocker NuGet Packages Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/index.md Adds the FluentDocker library and its testing adapters for xUnit, MSTest, and NUnit to a .NET project. ```bash dotnet add package FluentDocker dotnet add package FluentDocker.Testing.Xunit # xUnit adapter dotnet add package FluentDocker.Testing.MsTest # MSTest adapter dotnet add package FluentDocker.Testing.NUnit # NUnit adapter ``` -------------------------------- ### Volume Mount Examples Source: https://github.com/mariotoffia/fluentdocker/blob/master/README.md Illustrates how to mount volumes into a container. This includes mounting a directory from the host and using a named Docker volume. ```csharp // Host path mount .WithVolume("/host/path", "/container/path") // Named volume .WithVolume("my-vol", "/data") ``` -------------------------------- ### Standalone Kernel and Builder Setup Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/testing.md Use this pattern when you need direct control over the Docker kernel and builder without relying on test base classes. It's suitable for complex test setups requiring custom configurations. ```csharp public class NginxTests : IAsyncLifetime { private FluentDockerKernel _kernel; private BuildResults _results; public async ValueTask InitializeAsync() { _kernel = await FluentDockerKernel.Create() .WithDockerCli("docker", d => d.AsDefault()) .BuildAsync(); _results = await new Builder() .WithinDriver("docker", _kernel) .UseContainer(c => c .UseImage("nginx:alpine") .ExposePort("80") .WaitForPort("80/tcp", 30000)) .BuildAsync(); } public async ValueTask DisposeAsync() { if (_results is IAsyncDisposable ad) await ad.DisposeAsync(); if (_kernel is IAsyncDisposable kd) await kd.DisposeAsync(); } [Fact] public async Task Nginx_AcceptsConnections() { var container = _results.Containers.First(); var endpoint = container.ToHostExposedEndpoint("80/tcp"); using var client = new HttpClient(); var response = await client.GetStringAsync( $"http://localhost:{endpoint.Port}"); Assert.Contains("nginx", response); } } ``` -------------------------------- ### NUnit Assembly-Level Docker Setup Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/testing/nunit.md Shows how to configure Docker resources at the assembly level for NUnit tests using SetUpFixture and NUnitResourceHelpers.CreateContainerAsync. ```csharp [SetUpFixture] public class GlobalDockerSetup { private FluentDockerKernel _kernel; private ContainerResource _resource; [OneTimeSetUp] public async Task Setup() { (_kernel, _resource) = await NUnitResourceHelpers.CreateContainerAsync( builder => builder.UseImage("redis:alpine")); } [OneTimeTearDown] public async Task Teardown() { await NUnitResourceHelpers.DisposeAsync(_resource, _kernel); } } ``` -------------------------------- ### Podman Kubernetes Example with MSTest Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/testing/mstest.md Shows how to deploy Kubernetes resources using Podman for MSTest integration. Employs CreatePodmanKubernetesAsync with KubePlayConfig and custom kernel factory. ```csharp [ClassInitialize] public static async Task ClassInit(TestContext context) { (_kernel, _resource) = await MsTestResourceHelpers.CreatePodmanKubernetesAsync( new KubePlayConfig { YamlPath = "pod.yaml" }, kernelFactory: async () => await FluentDockerKernel.Create() .WithPodmanCli("podman", d => d.AsDefault()) .BuildAsync()); } ``` -------------------------------- ### Run EventDriven Example Source: https://github.com/mariotoffia/fluentdocker/blob/master/Examples/README.md Navigate to the EventDriven directory and run the .NET project to demonstrate Docker event streaming using the IStreamDriver interface. ```bash cd EventDriven && dotnet run ``` -------------------------------- ### xUnit IAsyncLifetime - v2 Example Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/migrate-v2-to-v3/test-migration.md Demonstrates the v2 pattern for setting up and tearing down a container using xUnit's IAsyncLifetime. Requires Ductus.FluentDocker.MsTest or Ductus.FluentDocker.XUnit packages. ```csharp using Ductus.FluentDocker.Builders; using Ductus.FluentDocker.Services; using Xunit; public class PostgresTests : IAsyncLifetime { private IContainerService _container; public async Task InitializeAsync() { _container = new Builder() .UseContainer() .UseImage("postgres:15-alpine") .WithEnvironment("POSTGRES_PASSWORD=test") .ExposePort(5432) .WaitForPort("5432/tcp", 30000) .Build() .Start(); } public Task DisposeAsync() { _container?.Dispose(); return Task.CompletedTask; } [Fact] public void Container_IsRunning() { Assert.Equal(ServiceRunningState.Running, _container.State); } } ``` -------------------------------- ### Writing a Postgres Plugin Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/testing/plugins.md Example of a plugin class that registers a PostgreSQL container resource. It demonstrates dependency injection for the kernel and factory registration. ```csharp // In a separate package, e.g., FluentDocker.Testing.Plugin.Postgres using FluentDocker.Testing.Core; using FluentDocker.Testing.Core.Plugins; public class PostgresPlugin : ITestPlugin { private readonly FluentDockerKernel _kernel; public PostgresPlugin(FluentDockerKernel kernel) => _kernel = kernel ?? throw new ArgumentNullException(nameof(kernel)); public string Id => "FluentDocker.Testing.Plugin.Postgres"; public void Register(ITestPluginRegistry registry) { registry.RegisterFactory( "postgres", _ => new ContainerResource( _kernel, builder => builder .UseImage("postgres:16-alpine") .WithEnvironment("POSTGRES_PASSWORD", "test") .ExposePort("5432") .WaitForPort("5432/tcp"))); } } ``` -------------------------------- ### Quick Start with Docker Compose Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/getting-started.md For multi-container applications, use Docker Compose with FluentDocker. This snippet shows how to use a docker-compose.yml file. ```csharp using FluentDocker.Builders; using FluentDocker.Kernel; // kernel created as shown above using var results = new Builder() .WithinDriver("docker", kernel) .UseCompose(c => c .WithComposeFile("docker-compose.yml") .WithRemoveOrphans()) .Build(); // Access compose services foreach (var compose in results.ComposeServices) { Console.WriteLine($"Compose project: {compose.Name}"); } ``` -------------------------------- ### Install FluentDocker Package Source: https://github.com/mariotoffia/fluentdocker/blob/master/FluentDocker/README.md Add the FluentDocker NuGet package to your .NET project to begin using its features. ```shell dotnet add package FluentDocker ``` -------------------------------- ### Remove Docker Machine and Use New Kernel/Builder Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/migration.md Shows how to replace Docker Machine discovery with the new `FluentDockerKernel` and `Builder` setup. ```csharp // OLD - Remove this code var machines = new Hosts().Discover(); var machine = machines.First(x => x.Name == "default"); // NEW - Create kernel and use WithinDriver using var kernel = FluentDockerKernel.Create() .WithDockerCli("docker", d => d.AsDefault()) .Build(); using var results = new Builder() .WithinDriver("docker", kernel) .UseContainer(c => c .UseImage("nginx:alpine")) .Build(); ``` -------------------------------- ### NUnit Generic Resource Setup Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/testing/nunit.md Illustrates setting up a generic or custom ITestResource for NUnit tests using NUnitResourceHelpers.CreateResourceAsync. ```csharp [OneTimeSetUp] public async Task Setup() { (_kernel, _resource) = await NUnitResourceHelpers.CreateResourceAsync( kernel => new ContainerResource(kernel, c => c.UseImage("redis:alpine").WaitForPort("6379/tcp"))); } ``` -------------------------------- ### NUnit Docker Swarm Stack Setup Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/testing/nunit.md Demonstrates setting up a Docker Swarm stack for NUnit tests using NUnitResourceHelpers.CreateSwarmStackAsync with StackDeployConfig. ```csharp [OneTimeSetUp] public async Task Setup() { (_kernel, _resource) = await NUnitResourceHelpers.CreateSwarmStackAsync( new StackDeployConfig { StackName = "my-stack", ComposeFiles = { "docker-compose.yml" } }); } ``` -------------------------------- ### NUnit Container Setup and Teardown Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/testing/nunit.md Demonstrates setting up and tearing down a Redis container for NUnit tests using NUnitResourceHelpers.CreateContainerAsync and DisposeAsync. ```csharp [TestFixture] public class RedisTests { private FluentDockerKernel _kernel; private ContainerResource _resource; [OneTimeSetUp] public async Task Setup() { (_kernel, _resource) = await NUnitResourceHelpers.CreateContainerAsync( builder => builder .UseImage("redis:alpine") .WaitForPort("6379/tcp")); } [OneTimeTearDown] public async Task Teardown() { await NUnitResourceHelpers.DisposeAsync(_resource, _kernel); } [Test] public async Task Redis_IsRunning() { var info = await _resource.InspectAsync(); Assert.That(info.State.Running, Is.True); } } ``` -------------------------------- ### Docker Compose Example with MSTest Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/testing/mstest.md Illustrates setting up Docker resources defined in a docker-compose.yml file for MSTest integration. Uses CreateComposeAsync for managing multi-container applications. ```csharp [ClassInitialize] public static async Task ClassInit(TestContext context) { (_kernel, _resource) = await MsTestResourceHelpers.CreateComposeAsync( builder => builder .WithComposeFile("docker-compose.yml") .WithProjectName("integration-tests")); } ``` -------------------------------- ### Install FluentDocker Test Adapters Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/getting-started.md Optional packages for integrating FluentDocker with popular .NET testing frameworks like xUnit, MSTest, and NUnit. ```bash dotnet add package FluentDocker.Testing.Xunit # xUnit adapter dotnet add package FluentDocker.Testing.MsTest # MSTest adapter dotnet add package FluentDocker.Testing.NUnit # NUnit adapter ``` -------------------------------- ### Legacy MSTest Redis Test Setup Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/testing/migration-from-legacy.md Example of configuring a Redis container using the legacy Ductus.FluentDocker.MsTest package. ```csharp using Ductus.FluentDocker.MsTest; [TestClass] public class RedisTests : FluentDockerTestBase { protected override void ConfigureContainer(IContainerBuilder builder) { builder .UseImage("redis:alpine") .ExposePort("6379") .WaitForPort("6379/tcp"); } [TestMethod] public void IsRunning() { Assert.AreEqual(ServiceRunningState.Running, Container.State); } } ``` -------------------------------- ### Basic Plugin Usage in Tests Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/testing/plugins.md Demonstrates how to initialize the FluentDocker kernel, add a plugin host, register a plugin, and create a container resource. ```csharp using var kernel = await FluentDockerKernel.Create() .WithDockerCli("docker", d => d.AsDefault()) .BuildAsync(); var host = new TestPluginHost(); host.Add(new PostgresPlugin(kernel)); var resource = host.Create("postgres"); await resource.InitializeAsync(); // Use the container... await resource.DisposeAsync(); ``` -------------------------------- ### xUnit IAsyncLifetime - v3 Example Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/migrate-v2-to-v3/test-migration.md Illustrates the v3 approach for managing containers with xUnit's IAsyncLifetime, utilizing FluentDockerKernel and lambda-scoped configuration. Requires FluentDocker.Testing packages. ```csharp using FluentDocker.Builders; using FluentDocker.Kernel; using FluentDocker.Services; using FluentDocker.Services.Extensions; using Xunit; public class PostgresTests : IAsyncLifetime { private FluentDockerKernel _kernel; private BuildResults _results; private IContainerService _container; public async ValueTask InitializeAsync() { _kernel = await FluentDockerKernel.Create() .WithDockerCli("docker", d => d.AsDefault()) .BuildAsync(); _results = await new Builder() .WithinDriver("docker", _kernel) .UseContainer(c => c .UseImage("postgres:15-alpine") .WithEnvironment("POSTGRES_PASSWORD=test") .ExposePort("5432") .WaitForPort("5432/tcp", 30000)) .BuildAsync(); _container = _results.Containers.First(); } public async ValueTask DisposeAsync() { if (_results is IAsyncDisposable ad) await ad.DisposeAsync(); if (_kernel is IAsyncDisposable kd) await kd.DisposeAsync(); } [Fact] public void Container_IsRunning() { Assert.Equal(ServiceRunningState.Running, _container.State); } } ``` -------------------------------- ### Multi-Container Topology Test Base Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/testing/xunit.md Example of using XunitTopologyTestBase for testing multi-container setups. Override ConfigureTopology to define networks and containers. The topology is fresh for each test. ```csharp public class MultiContainerTests : XunitTopologyTestBase { protected override void ConfigureTopology(Builder b) { b.UseNetwork(n => n.WithName("test-net")); b.UseContainer(c => c .UseImage("redis:alpine") .WithNetwork("test-net")); b.UseContainer(c => c .UseImage("nginx:alpine") .WithNetwork("test-net")); } [Fact] public void Both_Containers_Running() => Assert.Equal(2, Resource.Containers.Count); } ``` -------------------------------- ### Run ContainerStats Example Source: https://github.com/mariotoffia/fluentdocker/blob/master/Examples/README.md Navigate to the ContainerStats directory and run the .NET project to demonstrate v3 features like container resource monitoring and static IPv4 assignment. ```bash cd ContainerStats && dotnet run ``` -------------------------------- ### App Compose Test Base Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/testing/xunit.md Example of using XunitComposeTestBase for testing Docker Compose applications. Override ConfigureCompose to specify the compose file and project name. The compose setup is fresh for each test. ```csharp public class AppTests : XunitComposeTestBase { protected override void ConfigureCompose(IComposeBuilder b) => b.WithComposeFile("docker-compose.yml") .WithProjectName("app-tests"); [Fact] public void Service_IsAvailable() => Assert.NotNull(Service); } ``` -------------------------------- ### Inspect Docker Volume Details Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/volumes.md This example shows how to inspect a Docker volume to retrieve its metadata. It creates a volume and then uses the `InspectAsync` method to get details such as name, driver, scope, and creation timestamp. ```csharp using var results = new Builder() .WithinDriver("docker", kernel) .UseVolume(v => v.WithName("inspect-vol")) .Build(); var volume = results.Volumes.First(); var info = await volume.InspectAsync(); Console.WriteLine($"Name: {info.Name}"); Console.WriteLine($"Driver: {info.Driver}"); Console.WriteLine($"Scope: {info.Scope}"); Console.WriteLine($"Created: {info.Created}"); ``` -------------------------------- ### App Compose Fixture Base Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/testing/xunit.md Example of defining and using an AppComposeFixtureBase with IClassFixture. This fixture provides a shared Docker Compose setup for all tests within a class. The compose services are initialized once and disposed after all tests in the class complete. ```csharp public class AppFixture : XunitComposeFixtureBase { protected override void ConfigureCompose(IComposeBuilder b) => b.WithComposeFile("docker-compose.yml") .WithProjectName("integration"); } public class AppTests : IClassFixture { private readonly AppFixture _f; public AppTests(AppFixture f) => _f = f; [Fact] public void Service_IsAvailable() => Assert.NotNull(_f.Service); } ``` -------------------------------- ### Isolated Network Testing Setup Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/networking.md This C# code sets up an isolated Docker network, a PostgreSQL database container, and an API container within that network for testing. Each test run gets its own isolated network. The database is assigned a static IP and the API is configured to connect to it. ```csharp public class NetworkIsolatedTest : IDisposable { private readonly FluentDockerKernel _kernel; private readonly BuildResults _netResults; private readonly BuildResults _dbResults; private readonly BuildResults _apiResults; public NetworkIsolatedTest() { _kernel = FluentDockerKernel.Create() .WithDockerCli("docker", d => d.AsDefault()) .Build(); // Each test run gets isolated network var testId = Guid.NewGuid().ToString("N")[..8]; _netResults = new Builder() .WithinDriver("docker", _kernel) .UseNetwork(n => n .WithName($"test-{testId}") .WithSubnet("10.200.0.0/24") .RemoveOnDispose()) .Build(); _dbResults = new Builder() .WithinDriver("docker", _kernel) .UseContainer(c => c .WithName($"db-{testId}") .UseImage("postgres:15-alpine") .WithEnvironment("POSTGRES_PASSWORD=test") .WithNetwork($"test-{testId}") .WithIPv4("10.200.0.10") .WaitForPort("5432/tcp", 30000)) .Build(); _apiResults = new Builder() .WithinDriver("docker", _kernel) .UseContainer(c => c .WithName($"api-{testId}") .UseImage("myapi:test") .WithEnvironment("DB_HOST=10.200.0.10") .WithNetwork($"test-{testId}") .ExposePort("8080") .WaitForPort("8080/tcp", 30000)) .Build(); } [Fact] public void Api_CanConnectToDatabase() { var api = _apiResults.Containers.First(); // Test connectivity via the API container Assert.NotNull(api); } public void Dispose() { _apiResults?.Dispose(); _dbResults?.Dispose(); _netResults?.Dispose(); _kernel?.Dispose(); } } ``` -------------------------------- ### Quick Start: Docker CLI Container Management Source: https://github.com/mariotoffia/fluentdocker/blob/master/FluentDocker/README.md Demonstrates how to use FluentDocker with the Docker CLI to build and run a PostgreSQL container. It configures the container with an image, exposed port, environment variable, and waits for the port to be ready. ```csharp using FluentDocker.Builders; using FluentDocker.Kernel; await using var kernel = FluentDockerKernel.Create() .WithDockerCli("docker", d => d.AsDefault()) .Build(); await using var results = await new Builder() .WithinDriver("docker", kernel) .UseContainer(c => c .UseImage("postgres:15-alpine") .ExposePort("5432") .WithEnvironment("POSTGRES_PASSWORD", "mysecretpassword") .WaitForPort("5432/tcp", 30000)) .BuildAsync(); var container = results.Containers.First(); // Container is running and ready to accept connections on port 5432 ``` -------------------------------- ### COPY and ADD Dockerfile Instructions Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/images.md Demonstrates copying files and directories into a Docker image, including fetching remote archives with ADD and specifying ownership. ```csharp .Copy("src/", "/app/src/") .Copy("package.json", "/app/") .Copy("src/", "/app/src/", chownUserAndGroup: "node:node") .Copy("/app/dist", "/usr/share/nginx/html", fromAlias: "builder") // COPY --from .Add("https://example.com/file.tar.gz", "/app/") // ADD can fetch URLs ``` -------------------------------- ### Start Docker Compose Services Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/compose.md Builds and starts services defined in a docker-compose.yml file using the specified kernel. Services are automatically started during the Build() call. ```csharp using var results = new Builder() .WithinDriver("docker", kernel) .UseCompose(c => c .WithComposeFile("docker-compose.yml")) .Build(); // Services are started during Build() -- no separate Start() call. var compose = results.ComposeServices.First(); Console.WriteLine($"Project: {compose.ProjectName}"); ``` -------------------------------- ### Verify Docker Installation Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/getting-started.md Check if Docker is installed and running correctly by verifying its version and info. ```bash docker --version docker info ``` -------------------------------- ### Copy Files to Container on Start Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/containers.md Copies specified local files or directories into the container after it starts. This is a lifecycle hook. ```csharp using var results = new Builder() .WithinDriver("docker", kernel) .UseContainer(c => c .UseImage("nginx:alpine") .CopyToOnStart("/local/nginx.conf", "/etc/nginx/nginx.conf") .CopyToOnStart("/local/html/", "/usr/share/nginx/html/")) .Build(); ``` -------------------------------- ### Migrate Simple Container: v2 to v3 Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/migrate-v2-to-v3/code-examples.md Compares v2 and v3 syntax for building and starting a simple Nginx container. v3 uses a kernel, lambda configuration, and auto-starts containers. ```csharp using Ductus.FluentDocker.Builders; using Ductus.FluentDocker.Services; using var container = new Builder() .UseContainer() .UseImage("nginx:alpine") .ExposePort(80) .WaitForPort("80/tcp", 30000) .Build() .Start(); var endpoint = container.ToHostExposedEndpoint("80/tcp"); Console.WriteLine($"Nginx available at: {endpoint}"); ``` ```csharp using FluentDocker.Builders; using FluentDocker.Kernel; using FluentDocker.Services.Extensions; // Step 1: Create a kernel with a Docker CLI driver // (multiple kernels per app/test session are supported) using var kernel = FluentDockerKernel.Create() .WithDockerCli("docker", d => d.AsDefault()) .Build(); // Step 2: Build container — Build() auto-starts, returns BuildResults using var results = new Builder() .WithinDriver("docker", kernel) .UseContainer(c => c .UseImage("nginx:alpine") .ExposePort("80") .WaitForPort("80/tcp", 30000)) .Build(); var container = results.Containers.First(); var endpoint = container.ToHostExposedEndpoint("80/tcp"); Console.WriteLine($"Nginx available at: {endpoint}"); ``` -------------------------------- ### Network Building: v2 vs v3 Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/migrate-v2-to-v3/api-mapping.md Demonstrates the difference in building a Docker network named 'my-net' between v2 and v3. ```csharp // v2 var svc = new Builder() .UseNetwork("my-net") .Build(); ``` ```csharp // v3 var results = new Builder() .WithinDriver("docker", kernel) .UseNetwork(n => n.WithName("my-net")) .Build(); var network = results.Networks[0]; ``` -------------------------------- ### Quick Start: Docker Compose Management Source: https://github.com/mariotoffia/fluentdocker/blob/master/FluentDocker/README.md Demonstrates how to use FluentDocker to manage Docker Compose projects. This snippet shows how to specify the compose file, project name, and force recreation of services. ```csharp await using var results = await new Builder() .WithinDriver("docker", kernel) .UseCompose(c => c .WithComposeFile("docker-compose.yml") .WithProjectName("myapp") .WithForceRecreate()) .BuildAsync(); ``` -------------------------------- ### Start Docker Compose with Specific Profiles Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/compose.md Activates and starts only the services associated with the specified profiles ('debug', 'monitoring') in the docker-compose.yml file. ```csharp using var results = new Builder() .WithinDriver("docker", kernel) .UseCompose(c => c .WithComposeFile("docker-compose.yml") .WithProfiles("debug", "monitoring")) .Build(); ``` -------------------------------- ### Basic Container Example with MSTest Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/testing/mstest.md Demonstrates how to set up and tear down a single Docker container for MSTest integration using ClassInitialize and ClassCleanup attributes. Ensures the container is running and inspects its state. ```csharp [TestClass] public class RedisTests { private static FluentDockerKernel _kernel; private static ContainerResource _resource; [ClassInitialize] public static async Task ClassInit(TestContext context) { (_kernel, _resource) = await MsTestResourceHelpers.CreateContainerAsync( builder => builder .UseImage("redis:alpine") .WaitForPort("6379/tcp")); } [ClassCleanup] public static async Task ClassCleanup() { await MsTestResourceHelpers.DisposeAsync(_resource, _kernel); } [TestMethod] public async Task Redis_IsRunning() { var info = await _resource.InspectAsync(); Assert.IsTrue(info.State.Running); } } ``` -------------------------------- ### Container Building: v2 vs v3 Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/migrate-v2-to-v3/api-mapping.md Compares the v2 and v3 builder patterns for creating and starting a PostgreSQL container. Note that v3's Build() auto-starts the container. ```csharp // v2 var svc = new Builder() .UseContainer() .UseImage("postgres:alpine") .WithEnvironment("POSTGRES_PASSWORD=secret") .ExposePort(5432, 5432) .Build(); svc.Start(); ``` ```csharp // v3 var results = new Builder() .WithinDriver("docker", kernel) .UseContainer(c => c .UseImage("postgres:alpine") .WithEnvironment("POSTGRES_PASSWORD=secret") .ExposePort(5432, 5432)) .Build(); // Build() auto-starts; no explicit Start() needed. var container = results.Containers[0]; ``` -------------------------------- ### Start Docker Compose Services Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/compose.md Starts services defined in a docker-compose.yml file and waits for them to be ready. Sets a 60-second timeout for the wait operation. ```csharp using var results = new Builder() .WithinDriver("docker", kernel) .UseCompose(c => c .WithComposeFile("docker-compose.yml") .WithWait() .WithWaitTimeout(60)) .Build(); var rmq = results.Containers.First(c => c.Name.Contains("rabbitmq")); var amqp = rmq.ToHostExposedEndpoint("5672/tcp"); var mgmt = rmq.ToHostExposedEndpoint("15672/tcp"); Console.WriteLine($"AMQP: amqp://guest:guest@localhost:{amqp.Port}"); Console.WriteLine($"Management: http://localhost:{mgmt.Port}"); ``` -------------------------------- ### Create and Run Nginx Container Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/getting-started.md This C# example demonstrates creating a FluentDocker kernel and using the Builder to define and run an Nginx container, exposing port 80. ```csharp using System.Linq; using FluentDocker.Builders; using FluentDocker.Kernel; using FluentDocker.Services.Extensions; // Step 1: Create a kernel (multiple kernels per app are supported) using var kernel = FluentDockerKernel.Create() .WithDockerCli("docker", d => d.AsDefault()) .Build(); // Step 2: Build and start an nginx container using var results = new Builder() .WithinDriver("docker", kernel) .UseContainer(c => c .UseImage("nginx:alpine") .ExposePort("80")) .Build(); // Get the assigned host port var container = results.Containers.First(); var endpoint = container.ToHostExposedEndpoint("80/tcp"); Console.WriteLine($"Nginx running at: http://localhost:{endpoint.Port}"); // All containers stop and are removed when results is disposed ``` -------------------------------- ### Using a Plugin Package for Postgres Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/testing/migration-from-legacy.md An alternative to direct configuration is to use available plugin packages, such as FluentDocker.Testing.Plugin.Postgres. ```csharp var host = new TestPluginHost(); host.Add(new PostgresPlugin(kernel)); var resource = host.Create("postgres"); await resource.InitializeAsync(); ``` -------------------------------- ### Install Testing Framework Integration Source: https://github.com/mariotoffia/fluentdocker/blob/master/FluentDocker/README.md Choose and install the appropriate FluentDocker testing integration package for your preferred .NET testing framework (XUnit, NUnit, or MSTest). ```shell dotnet add package FluentDocker.Testing.Xunit ``` ```shell dotnet add package FluentDocker.Testing.NUnit ``` ```shell dotnet add package FluentDocker.Testing.MsTest ``` -------------------------------- ### Setup, Run, and Teardown DevLocal Tests Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/test-categories.md Execute DevLocal tests which require Docker Swarm and a local registry. This involves a setup, test run, and teardown sequence. ```bash # 1. Start infrastructure make devlocal-setup # 2. Run DevLocal tests make test-devlocal # 3. Tear down infrastructure make devlocal-teardown ``` -------------------------------- ### HTTP Extensions Basic GET Request Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/utilities.md Perform a simple HTTP GET request using the Wget extension method. This is useful for basic health checks or retrieving simple data from an endpoint. ```csharp using FluentDocker.Extensions; // Simple GET var response = await "http://localhost:8080/health".Wget(); Console.WriteLine(response); // Response body ``` -------------------------------- ### FROM Dockerfile Instruction Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/images.md Shows how to specify the base image for a Docker build stage, including named stages and platform targeting. ```csharp .From("node:18-alpine") .From("node:18-alpine", "builder") // Named stage .From("node:18-alpine", platform: "linux/amd64") // With platform ``` -------------------------------- ### MsTest: Compose Setup with MsTestResourceHelpers Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/testing/migration-from-legacy.md Migrate from FluentDockerComposeTestBase to MsTestResourceHelpers.CreateComposeAsync for managing Docker Compose in MsTest. ```csharp using FluentDocker.Testing.MsTest; [TestClass] public class ComposeTests { private static FluentDockerKernel _kernel; private static ComposeResource _resource; [ClassInitialize] public static async Task ClassInit(TestContext context) { (_kernel, _resource) = await MsTestResourceHelpers.CreateComposeAsync( builder => builder .WithComposeFile("docker-compose.yml") .WithProjectName("tests")); } [ClassCleanup] public static async Task ClassCleanup() { await MsTestResourceHelpers.DisposeAsync(_resource, _kernel); } } ``` -------------------------------- ### v3 Docker Compose with Multiple Files and Environment Variables Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/migrate-v2-to-v3/code-examples.md This v3 example shows how to use multiple compose files, set a project name, environment variables, and environment files, along with force recreation and build options. ```csharp // v3: compose with overrides and environment variables using var results = new Builder() .WithinDriver("docker", kernel) .UseCompose(c => c .WithComposeFiles("docker-compose.yml", "docker-compose.override.yml") .WithProjectName("myproject") .WithEnvironment("TAG", "v2.1.0") .WithEnvFile(".env.production") .WithForceRecreate() .WithBuild() .WithRemoveOrphans() .WithWait() .WithWaitTimeout(60)) .Build(); ``` -------------------------------- ### Create FluentDocker Kernel with Podman Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/index.md Initializes the FluentDocker kernel with Podman CLI support, including options to auto-start the machine. ```csharp using var kernel = await FluentDockerKernel.Create() .WithPodmanCli("podman", d => d.WithAutoStartMachine().AsDefault()) .BuildAsync(); await using var results = await new Builder() .WithinDriver("podman", kernel) .UseContainer(c => c .UseImage("nginx:alpine") .ExposePort("80") .WaitForPort("80/tcp", 30000)) .BuildAsync(); ``` -------------------------------- ### Getting Container Statistics Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/migration.md Demonstrates how to retrieve and display CPU and Memory usage statistics for a running container. ```csharp var stats = await container.GetStatsAsync(); Console.WriteLine($"CPU: {stats.Cpu.UsagePercent:F2}%"); Console.WriteLine($"Memory: {stats.Memory.Usage} bytes"); ``` -------------------------------- ### Deploy Services Across Multiple Environments Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/architecture.md This snippet demonstrates deploying services to different Docker environments (e.g., 'dev' and 'prod') using a single FluentDocker kernel. It shows how to configure distinct Docker hosts and certificates for each environment and then build and start services within them. ```csharp public async Task DeployAsync(CancellationToken cancellationToken) { var kernel = await FluentDockerKernel.Create() .WithDockerCli("dev", d => { }) .WithDockerApi("prod", d => d .AtHost("tcp://prod:2376") .WithCertificates("/certs")) .BuildAsync(cancellationToken); var deployment = await new Builder() .WithinDriver("dev", kernel) .UseContainer(c => c.UseImage("myapp:dev")) .UseContainer(c => c.UseImage("postgres:14")) .WithinDriver("prod") // Reuses kernel .UseContainer(c => c.UseImage("myapp:v1.0")) .BuildAsync(cancellationToken); // Start all services in parallel var startTasks = deployment.All .OfType() .Select(c => c.StartAsync(cancellationToken)); await Task.WhenAll(startTasks); // Cleanup await deployment.DisposeAllAsync(); } ``` -------------------------------- ### xUnit v2 Fixture and Test Setup Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/migrate-v2-to-v3/test-migration.md Illustrates the v2 approach for xUnit integration using FluentDockerTestBase. This involves overriding the Build method to configure the container and using a fixture class to manage the test lifecycle. ```csharp using Ductus.FluentDocker.Builders; using Ductus.FluentDocker.XUnit; using Xunit; public class NginxFixture : FluentDockerTestBase { protected override ContainerBuilder Build() { return new Builder() .UseContainer() .UseImage("nginx:alpine") .ExposePort(80) .WaitForPort("80/tcp", 30000); } } public class NginxTests : IClassFixture { private readonly NginxFixture _fixture; public NginxTests(NginxFixture fixture) => _fixture = fixture; [Fact] public void Container_IsRunning() { Assert.Equal(ServiceRunningState.Running, _fixture.Container.State); } } ``` -------------------------------- ### v2 File Copy Operations Source: https://github.com/mariotoffia/fluentdocker/blob/master/docs/migrate-v2-to-v3/code-examples.md Examples of copying files to and from a container using v2's synchronous methods. ```csharp using Ductus.FluentDocker.Extensions; // Copy file to container container.CopyTo("/path/on/host/config.json", "/app/config.json"); // Copy file from container container.CopyFrom("/app/logs/output.log", "/path/on/host/output.log"); ``` -------------------------------- ### Set up local .env file for act secrets Source: https://github.com/mariotoffia/fluentdocker/blob/master/DEVELOPMENT.md Copies the example environment file to a new file and opens it for editing. This file is used by 'act' to provide secrets for local workflow testing. ```bash # First, create a .env file based on .env.example cp .env.example .env # Edit the .env file with your secret values vim .env # or use any editor ```