Container Lifecycle Manager
A self-contained program that demonstrates full container lifecycle management using the Docker Go SDK. It pulls an nginx:alpine image, creates and starts a container, streams logs for 5 seconds, then gracefully stops and removes the container, all programmatically without the Docker CLI.
package main
import (
"context"
"fmt"
"io"
"log"
"os"
"time"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/image"
"github.com/docker/docker/client"
"github.com/docker/docker/pkg/stdcopy"
)
func main() {
ctx := context.Background()
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil {
log.Fatal(err)
}
defer cli.Close()
imageName := "nginx:alpine"
containerName := "devctl-nginx-demo"
// Pull the image
fmt.Printf("Pulling %s...\n", imageName)
pullResp, err := cli.ImagePull(ctx, imageName, image.PullOptions{})
if err != nil {
log.Fatalf("pull: %v", err)
}
io.Copy(io.Discard, pullResp)
pullResp.Close()
fmt.Println("✓ Image pulled")
// Create and start the container
resp, err := cli.ContainerCreate(ctx,
&container.Config{Image: imageName},
nil, nil, nil, containerName,
)
if err != nil {
log.Fatalf("create: %v", err)
}
containerID := resp.ID
if err := cli.ContainerStart(ctx, containerID, container.StartOptions{}); err != nil {
log.Fatalf("start: %v", err)
}
fmt.Printf("✓ Container %s started (ID: %s)\n", containerName, containerID[:12])
// Stream logs for 5 seconds
logCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
logReader, err := cli.ContainerLogs(logCtx, containerID, container.LogsOptions{
ShowStdout: true,
ShowStderr: true,
Follow: true,
})
if err != nil {
log.Printf("logs: %v", err)
} else {
fmt.Println("--- Container Logs ---")
stdcopy.StdCopy(os.Stdout, os.Stderr, logReader)
logReader.Close()
fmt.Println("--- End Logs ---")
}
// Cleanup: stop and remove
timeout := 5
cli.ContainerStop(ctx, containerID, container.StopOptions{Timeout: &timeout})
cli.ContainerRemove(ctx, containerID, container.RemoveOptions{Force: true})
fmt.Printf("✓ Container %s removed\n", containerName)
}