Skip to content

Full Example

Dustin Horne edited this page May 14, 2024 · 3 revisions

Scenario: You have a subdirectory under the current directory called CustomContainer. Inside of that folder is a Dockerfile for Postgres with Citus. The docker file accepts two arguments (for the postgres username and postgres password), and you want to build it from code and output the messages to the console. Finally, you want to write the exit code from the process to the console.

var cmd = CommandBuilder.Create("docker")
    .WithArgument("build")
    .WithArgument("-f Dockerfile")
    .WithArgument("--build-arg POSTGRES_USER=postgres")
    .WithArgument("--build-arg POSTGRES_PASSWORD=$uper$ecretPa$$w0rd")
    .WithArgument("--progress=plain")
    .WithArgument("--no-cache")
    .WithArgument($"-t {_name}:latest")
    .WithArgument(".")
    .WithWorkingDirectory(Path.Combine(Directory.GetCurrentDirectory(), "CustomContainer"))
    .WithAggressiveOutputProcessing()
    .WithOutput(1000) //Only cache the last 1k messages if unprocessed
    .Build();

if(cmd.Start(cancellationToken))
{
    await foreach (var msg in cmd.ReadOutputAsync(cancellationToken))
    {
        await Console.Out.WriteLineAsync($"{msg.MessageType}: {msg.Data}");
    }

    var exitCode = await cmd.WaitForExitAsync();

    await Console.Out.WriteLineAsync($"Process exited with code: {exitCode}");
}
else
{
    await Console.Out.WriteLineAsync("Process failed to start");
}

Clone this wiki locally