|
| 1 | +# Using docker/compose SDK |
| 2 | + |
| 3 | +The `docker/compose` package can be used as a Go library by third-party applications to programmatically manage |
| 4 | +containerized applications defined in Compose files. This SDK provides a comprehensive API that enables developers to |
| 5 | +integrate Compose functionality directly into their applications, allowing them to load, validate, and manage |
| 6 | +multi-container environments without relying on the Compose CLI. Whether you need to orchestrate containers as part of |
| 7 | +a deployment pipeline, build custom management tools, or embed container orchestration into your application, the |
| 8 | +Compose SDK offers the same powerful capabilities that drive the Docker Compose command-line tool. |
| 9 | + |
| 10 | +## Setup the SDK |
| 11 | + |
| 12 | +To get started, create an SDK instance using the `NewComposeService()` function, which initializes a service with the |
| 13 | +necessary configuration to interact with the Docker daemon and manage Compose projects. This service instance provides |
| 14 | +methods for all core Compose operations including creating, starting, stopping, and removing containers, as well as |
| 15 | +loading and validating Compose files. The service handles the underlying Docker API interactions and resource |
| 16 | +management, allowing you to focus on your application logic. |
| 17 | + |
| 18 | +## Example Usage |
| 19 | + |
| 20 | +Here's a basic example demonstrating how to load a Compose project and start the services: |
| 21 | + |
| 22 | +```go |
| 23 | +package main |
| 24 | + |
| 25 | +import ( |
| 26 | + "context" |
| 27 | + "log" |
| 28 | + |
| 29 | + "github.com/docker/cli/cli/command" |
| 30 | + "github.com/docker/cli/cli/flags" |
| 31 | + "github.com/docker/compose/v2/pkg/api" |
| 32 | + "github.com/docker/compose/v2/pkg/compose" |
| 33 | +) |
| 34 | + |
| 35 | +func main() { |
| 36 | + ctx := context.Background() |
| 37 | + |
| 38 | + dockerCLI, err := command.NewDockerCli() |
| 39 | + if err != nil { |
| 40 | + log.Fatalf("Failed to create docker CLI: %v", err) |
| 41 | + } |
| 42 | + err = dockerCLI.Initialize(flags.ClientOptions{}) |
| 43 | + if err != nil { |
| 44 | + log.Fatalf("Failed to initialize docker CLI: %v", err) |
| 45 | + } |
| 46 | + |
| 47 | + // Create a new Compose service instance |
| 48 | + service, err := compose.NewComposeService(dockerCLI) |
| 49 | + if err != nil { |
| 50 | + log.Fatalf("Failed to create compose service: %v", err) |
| 51 | + } |
| 52 | + |
| 53 | + // Load the Compose project from a compose file |
| 54 | + project, err := service.LoadProject(ctx, api.ProjectLoadOptions{ |
| 55 | + ConfigPaths: []string{"compose.yaml"}, |
| 56 | + ProjectName: "my-app", |
| 57 | + }) |
| 58 | + if err != nil { |
| 59 | + log.Fatalf("Failed to load project: %v", err) |
| 60 | + } |
| 61 | + |
| 62 | + // Start the services defined in the Compose file |
| 63 | + err = service.Up(ctx, project, api.UpOptions{ |
| 64 | + Create: api.CreateOptions{}, |
| 65 | + Start: api.StartOptions{}, |
| 66 | + }) |
| 67 | + if err != nil { |
| 68 | + log.Fatalf("Failed to start services: %v", err) |
| 69 | + } |
| 70 | + |
| 71 | + log.Printf("Successfully started project: %s", project.Name) |
| 72 | +} |
| 73 | +``` |
| 74 | + |
| 75 | +This example demonstrates the core workflow: creating a service instance, loading a project from a Compose file, and |
| 76 | +starting the services. The SDK provides many additional operations for managing the lifecycle of your containerized |
| 77 | +application. |
| 78 | + |
| 79 | +## Customizing the SDK |
| 80 | + |
| 81 | +The `NewComposeService()` function accepts optional `compose.Option` parameters to customize the SDK behavior. These |
| 82 | +options allow you to configure I/O streams, concurrency limits, dry-run mode, and other advanced features: |
| 83 | + |
| 84 | +```go |
| 85 | + // Create a custom output buffer to capture logs |
| 86 | + var outputBuffer bytes.Buffer |
| 87 | + |
| 88 | + // Create a compose service with custom options |
| 89 | + service, err := compose.NewComposeService(dockerCLI, |
| 90 | + compose.WithOutputStream(&outputBuffer), // Redirect output to custom writer |
| 91 | + compose.WithErrorStream(os.Stderr), // Use stderr for errors |
| 92 | + compose.WithMaxConcurrency(4), // Limit concurrent operations |
| 93 | + compose.WithPrompt(compose.AlwaysOkPrompt()), // Auto-confirm all prompts |
| 94 | + ) |
| 95 | +``` |
| 96 | + |
| 97 | +### Available Options |
| 98 | + |
| 99 | +- **`WithOutputStream(io.Writer)`** - Redirect standard output to a custom writer |
| 100 | +- **`WithErrorStream(io.Writer)`** - Redirect error output to a custom writer |
| 101 | +- **`WithInputStream(io.Reader)`** - Provide a custom input stream for interactive prompts |
| 102 | +- **`WithStreams(out, err, in)`** - Set all I/O streams at once |
| 103 | +- **`WithMaxConcurrency(int)`** - Limit the number of concurrent operations against the Docker API |
| 104 | +- **`WithPrompt(Prompt)`** - Customize user confirmation behavior (use `AlwaysOkPrompt()` for non-interactive mode) |
| 105 | +- **`WithDryRun`** - Run operations in dry-run mode without actually applying changes |
| 106 | +- **`WithContextInfo(api.ContextInfo)`** - Set custom Docker context information |
| 107 | +- **`WithProxyConfig(map[string]string)`** - Configure HTTP proxy settings for builds |
| 108 | +- **`WithEventProcessor(progress.EventProcessor)`** - Receive progress events and operation notifications |
| 109 | + |
| 110 | +These options provide fine-grained control over the SDK's behavior, making it suitable for various integration |
| 111 | +scenarios including CLI tools, web services, automation scripts, and testing environments. |
| 112 | + |
| 113 | +## Tracking Operations with EventProcessor |
| 114 | + |
| 115 | +The `EventProcessor` interface allows you to monitor Compose operations in real-time by receiving events about changes |
| 116 | +applied to Docker resources such as images, containers, volumes, and networks. This is particularly useful for building |
| 117 | +user interfaces, logging systems, or monitoring tools that need to track the progress of Compose operations. |
| 118 | + |
| 119 | +### Understanding EventProcessor |
| 120 | + |
| 121 | +A Compose operation (like `Up`, `Down`, `Build`, etc.) performs a series of changes to Docker resources. The |
| 122 | +`EventProcessor` receives notifications about these changes through three key methods: |
| 123 | + |
| 124 | +- **`Start(ctx, operation)`** - Called when a Compose operation begins (e.g., "up") |
| 125 | +- **`On(events...)`** - Called with progress events for individual resource changes (e.g., container starting, image |
| 126 | + being pulled) |
| 127 | +- **`Done(operation, success)`** - Called when the operation completes, indicating success or failure |
| 128 | + |
| 129 | +Each event contains information about the resource being modified, its current status, and progress indicators when |
| 130 | +applicable (such as download progress for image pulls). |
| 131 | + |
| 132 | +### Event Status Types |
| 133 | + |
| 134 | +Events report resource changes with the following status types: |
| 135 | + |
| 136 | +- **Working** - Operation is in progress (e.g., creating, starting, pulling) |
| 137 | +- **Done** - Operation completed successfully |
| 138 | +- **Warning** - Operation completed with warnings |
| 139 | +- **Error** - Operation failed |
| 140 | + |
| 141 | +Common status text values include: `Creating`, `Created`, `Starting`, `Started`, `Running`, `Stopping`, `Stopped`, |
| 142 | +`Removing`, `Removed`, `Building`, `Built`, `Pulling`, `Pulled`, and more. |
| 143 | + |
| 144 | +### Built-in EventProcessor Implementations |
| 145 | + |
| 146 | +The SDK provides three ready-to-use `EventProcessor` implementations: |
| 147 | + |
| 148 | +- **`progress.NewTTYWriter(io.Writer)`** - Renders an interactive terminal UI with progress bars and task lists |
| 149 | + (similar to the Docker Compose CLI output) |
| 150 | +- **`progress.NewPlainWriter(io.Writer)`** - Outputs simple text-based progress messages suitable for non-interactive |
| 151 | + environments or log files |
| 152 | +- **`progress.NewJSONWriter()`** - Render events as JSON objects |
| 153 | +- **`progress.NewQuietWriter()`** - (default) Silently processes events without producing any output |
| 154 | + |
| 155 | +Using `EventProcessor`, a custom UI can be plugged into docker/compose |
| 156 | + |
0 commit comments