image

package module
v0.1.0-alpha013 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 16, 2025 License: Apache-2.0 Imports: 26 Imported by: 1

README

Docker Images

This package provides a simple API to create and manage Docker images.

Installation

go get github.com/docker/go-sdk/image

Pulling images

Usage
err = image.Pull(ctx, "nginx:alpine")
if err != nil {
    log.Fatalf("failed to pull image: %v", err)
}
Customizing the Pull operation

The Pull operation can be customized using functional options. The following options are available:

  • WithPullClient(cli client.SDKClient) image.PullOption: The client to use to pull the image. If not provided, the default client will be used.
  • WithPullOptions(options apiimage.PullOptions) image.PullOption: The options to use to pull the image. The type of the options is "github.com/moby/moby/api/types/image".
  • WithPullHandler(pullHandler func(r io.ReadCloser) error) image.PullOption: The handler to use to pull the image, which acts as a callback to the pull operation.

First, you need to import the following packages:

import (
	"context"

    apiimage "github.com/moby/moby/api/types/image"
	"github.com/docker/go-sdk/client"
	"github.com/docker/go-sdk/image"
)

And in your code:

ctx := context.Background()
dockerClient, err := client.New(ctx)
if err != nil {
    log.Fatalf("failed to create docker client: %v", err)
}
defer dockerClient.Close()

err = image.Pull(ctx,
    "nginx:alpine",
    image.WithPullClient(dockerClient),
    image.WithPullOptions(apiimage.PullOptions{}),
    image.WithPullHandler(func(r io.ReadCloser) error {
        // do something with the reader
        return nil
    }),
)
if err != nil {
    log.Fatalf("failed to pull image: %v", err)
}

Removing images

Usage
err = image.Remove(ctx, "nginx:alpine")
if err != nil {
    log.Fatalf("failed to remove image: %v", err)
}
Customizing the Remove operation

The Remove operation can be customized using functional options. The following options are available:

  • WithRemoveClient(cli client.SDKClient) image.RemoveOption: The client to use to remove the image. If not provided, the default client will be used.
  • WithRemoveOptions(options dockerimage.RemoveOptions) image.RemoveOption: The options to use to remove the image. The type of the options is "github.com/moby/moby/api/types/image".

First, you need to import the following packages:

import (
	"context"

    dockerimage "github.com/moby/moby/api/types/image"
	"github.com/docker/go-sdk/client"
	"github.com/docker/go-sdk/image"
)

In your code:

ctx := context.Background()
dockerClient, err := client.New(ctx)
if err != nil {
    log.Println("failed to create docker client", err)
    return
}
defer dockerClient.Close()

resp, err := image.Remove(ctx, img, image.WithRemoveOptions(dockerimage.RemoveOptions{
    Force:         true,
    PruneChildren: true,
}))
if err != nil {
    log.Println("failed to remove image", err)
    return
}

Building images

Usage
// path to the build context
buildPath := path.Join("testdata", "build")

// create a reader from the build context
contextArchive, err := image.ArchiveBuildContext(buildPath, "Dockerfile")
if err != nil {
    log.Println("error creating reader", err)
    return
}

// using a buffer to capture the build output
buf := &bytes.Buffer{}

tag, err := image.Build(
    context.Background(), contextArchive, "example:test",
    image.WithBuildOptions(build.ImageBuildOptions{
        Dockerfile: "Dockerfile",
    }),
    image.WithLogWriter(buf),
)
if err != nil {
    log.Println("error building image", err)
    return
}
Archiving the build context

The build context can be archived using the ArchiveBuildContext function. This function will return a reader that can be used to build the image.

buildPath := path.Join("testdata", "build")

contextArchive, err := image.ArchiveBuildContext(buildPath, "Dockerfile")
if err != nil {
    log.Println("error creating reader", err)
    return
}

This function needs the relative path to the build context and the Dockerfile path inside the build context. The Dockerfile path is relative to the build context.

Customizing the Build operation

The Build operation can be customized using functional options. The following options are available:

  • WithBuildClient(cli client.SDKClient) image.BuildOption: The client to use to build the image. If not provided, the default client will be used.
  • WithLogWriter(writer io.Writer) image.BuildOption: The writer to use to write the build output. If not provided, the build output will be written to the standard output.
  • WithBuildOptions(options build.ImageBuildOptions) image.BuildOption: The options to use to build the image. The type of the options is "github.com/moby/moby/api/types/build". If set, the tag and context reader will be overridden with the arguments passed to the Build function.

First, you need to import the following packages:

import (
	"context"

    "github.com/moby/moby/api/types/build"
	"github.com/docker/go-sdk/client"
	"github.com/docker/go-sdk/image"
)

And in your code:

ctx := context.Background()
dockerClient, err := client.New(ctx)
if err != nil {
    log.Fatalf("failed to create docker client: %v", err)
}
defer dockerClient.Close()

// using a buffer to capture the build output
buf := &bytes.Buffer{}

err = image.Build(ctx, contextArchive, "example:test",
    image.WithBuildClient(dockerClient),
    image.WithBuildOptions(build.ImageBuildOptions{
        Dockerfile: "Dockerfile",
    }),
    image.WithLogWriter(buf),
)
if err != nil {
    log.Println("error building image", err)
    return
}

Extracting images from a Dockerfile

There are three functions to extract images from a Dockerfile:

  • ImagesFromDockerfile(dockerfile string, buildArgs map[string]*string) ([]string, error): Extracts images from a Dockerfile.
  • ImagesFromReader(r io.Reader, buildArgs map[string]*string) ([]string, error): Extracts images from a Dockerfile reader.
  • ImagesFromTarReader(r io.ReadSeeker, dockerfile string, buildArgs map[string]*string) ([]string, error): Extracts images from a Dockerfile reader that is a tar reader.

A Dockerfile can exist in different formats:

  • A single Dockerfile file.
  • A Dockerfile in a reader, which can be a file or a buffer.
  • A Dockerfile inside a tar reader, as part of a build context.

The first two cases are handled by the ImagesFromDockerfile and ImagesFromReader functions.

images, err := image.ImagesFromDockerfile("Dockerfile", nil)
if err != nil {
    log.Println("error extracting images", err)
    return
}

The ImagesFromTarReader function is useful when the Dockerfile is inside a tar reader, as part of a build context.

images, err := image.ImagesFromTarReader(contextArchive, "Dockerfile", nil)
if err != nil {
    log.Println("error extracting images", err)
    return
}

In this case, the contextArchive is a tar reader, and the Dockerfile is the path to the Dockerfile inside the tar reader.

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func ArchiveBuildContext

func ArchiveBuildContext(dir string, dockerfile string) (r io.ReadCloser, err error)

ArchiveBuildContext creates a TAR archive reader from a directory. It returns an error if the directory cannot be read or if the files cannot be read. This function is useful for creating a build context to build an image. The dockerfile path needs to be relative to the build context.

func Build

func Build(ctx context.Context, contextReader io.Reader, tag string, opts ...BuildOption) (string, error)

Build will build and image from context and Dockerfile, then return the tag. It uses "Dockerfile" as the Dockerfile path, although it can be overridden by the build options. In the case the build options contains tags or a context reader, they will be overridden by the arguments passed to the function, which are mandatory.

Example
package main

import (
	"bytes"
	"context"
	"fmt"
	"log"
	"log/slog"
	"path"

	dockerclient "github.com/moby/moby/client"

	"github.com/docker/go-sdk/client"
	"github.com/docker/go-sdk/image"
)

func main() {
	// using a buffer to capture the build output
	buf := &bytes.Buffer{}
	logger := slog.New(slog.NewTextHandler(buf, nil))

	cli, err := client.New(context.Background(), client.WithLogger(logger))
	if err != nil {
		log.Println("error creating docker client", err)
		return
	}
	defer func() {
		err := cli.Close()
		if err != nil {
			log.Println("error closing docker client", err)
		}
	}()

	buildPath := path.Join("testdata", "build")

	contextArchive, err := image.ArchiveBuildContext(buildPath, "Dockerfile")
	if err != nil {
		log.Println("error creating reader", err)
		return
	}

	tag, err := image.Build(
		context.Background(), contextArchive, "example:test",
		image.WithBuildOptions(dockerclient.ImageBuildOptions{
			Dockerfile: "Dockerfile",
		}),
	)
	if err != nil {
		log.Println("error building image", err)
		return
	}
	defer func() {
		_, err = image.Remove(context.Background(), tag, image.WithRemoveOptions(dockerclient.ImageRemoveOptions{
			Force:         true,
			PruneChildren: true,
		}))
		if err != nil {
			log.Println("error removing image", err)
		}
	}()

	fmt.Println(tag)

}
Output:

example:test

func BuildFromDir

func BuildFromDir(ctx context.Context, dir string, dockerfile string, tag string, opts ...BuildOption) (string, error)

BuildFromDir builds an image from a directory and the path to the Dockerfile in the directory, then returns the tag. It uses ArchiveBuildContext to create a archive reader from the directory.

Example
package main

import (
	"bytes"
	"context"
	"fmt"
	"log"
	"log/slog"
	"path"

	dockerclient "github.com/moby/moby/client"

	"github.com/docker/go-sdk/client"
	"github.com/docker/go-sdk/image"
)

func main() {
	// using a buffer to capture the build output
	buf := &bytes.Buffer{}
	logger := slog.New(slog.NewTextHandler(buf, nil))

	cli, err := client.New(context.Background(), client.WithLogger(logger))
	if err != nil {
		log.Println("error creating docker client", err)
		return
	}
	defer func() {
		err := cli.Close()
		if err != nil {
			log.Println("error closing docker client", err)
		}
	}()

	buildPath := path.Join("testdata", "build")

	tag, err := image.BuildFromDir(
		context.Background(), buildPath, "Dockerfile", "example:test",
		image.WithBuildOptions(dockerclient.ImageBuildOptions{
			Dockerfile: "Dockerfile",
		}),
	)
	if err != nil {
		log.Println("error building image", err)
		return
	}
	defer func() {
		_, err = image.Remove(context.Background(), tag, image.WithRemoveOptions(dockerclient.ImageRemoveOptions{
			Force:         true,
			PruneChildren: true,
		}))
		if err != nil {
			log.Println("error removing image", err)
		}
	}()

	fmt.Println(tag)

}
Output:

example:test

func DisplayProgress

func DisplayProgress(out io.Writer) func(r io.ReadCloser) error

DisplayProgress creates a pull handler that displays formatted pull progress to the given writer. It automatically detects if the writer is a terminal and enables colors and progress bars accordingly. If the writer is not a terminal, it displays plain text progress information.

This is useful when you want to customize where progress is displayed while maintaining the formatted output. For example:

err := image.Pull(ctx, "nginx:latest",
	image.WithPullHandler(image.DisplayProgress(os.Stderr)))
Example
package main

import (
	"bytes"
	"context"
	"fmt"
	"strings"

	"github.com/docker/go-sdk/image"
)

func main() {
	// Display formatted pull progress to a custom writer (buffer in this example).
	// Verifies that DisplayProgress formats the output (not raw JSON).
	buff := &bytes.Buffer{}

	err := image.Pull(context.Background(), "nginx:latest",
		image.WithPullHandler(image.DisplayProgress(buff)))

	fmt.Println(err)
	// Every single message from Docker starts with { and contains ",
	// so raw JSON will always have {", while formatted output strips
	// away the JSON structure.
	fmt.Println(!strings.Contains(buff.String(), "{\""))

}
Output:

<nil>
true

func ImagesFromDockerfile

func ImagesFromDockerfile(dockerfile string, buildArgs map[string]*string) ([]string, error)

ImagesFromDockerfile extracts images from the Dockerfile sourced from dockerfile.

func ImagesFromReader

func ImagesFromReader(r io.Reader, buildArgs map[string]*string) ([]string, error)

ImagesFromReader extracts images from the Dockerfile sourced from r. Use this function if you want to extract images from a Dockerfile that is not in a tar reader.

func ImagesFromTarReader

func ImagesFromTarReader(r io.ReadSeeker, dockerfile string, buildArgs map[string]*string) ([]string, error)

ImagesFromTarReader extracts images from the Dockerfile sourced from a tar reader. The name of the Dockerfile in the tar reader must be the same as the dockerfile parameter. Use this function if you want to extract images from a Dockerfile that is in a tar reader.

func ParseDockerIgnore

func ParseDockerIgnore(targetDir string) (bool, []string, error)

ParseDockerIgnore returns if the file exists, the excluded files and an error if any

func Pull

func Pull(ctx context.Context, imageName string, opts ...PullOption) error

Pull pulls an image from a remote registry, retrying on non-permanent errors. See client.IsPermanentClientError for the list of non-permanent errors. It first extracts the registry credentials from the image name, and sets them in the pull options. It needs to be called with a valid image name, and optional pull options, see PullOption. It's possible to override the default pull handler function by using the WithPullHandler option.

Example
package main

import (
	"context"
	"fmt"

	"github.com/docker/go-sdk/image"
)

func main() {
	err := image.Pull(context.Background(), "nginx:latest")

	fmt.Println(err)

}
Output:

<nil>
Example (WithClient)
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/docker/go-sdk/client"
	"github.com/docker/go-sdk/image"
)

func main() {
	dockerClient, err := client.New(context.Background())
	if err != nil {
		log.Printf("error creating client: %s", err)
		return
	}
	defer dockerClient.Close()

	err = image.Pull(context.Background(), "nginx:latest", image.WithPullClient(dockerClient))

	fmt.Println(err)

}
Output:

<nil>
Example (WithPullHandler)
package main

import (
	"bytes"
	"context"
	"fmt"
	"io"
	"strings"

	dockerclient "github.com/moby/moby/client"
	v1 "github.com/opencontainers/image-spec/specs-go/v1"

	"github.com/docker/go-sdk/image"
)

func main() {
	opts := dockerclient.ImagePullOptions{Platforms: []v1.Platform{
		{
			OS:           "linux",
			Architecture: "amd64",
		},
	}}

	buff := &bytes.Buffer{}

	err := image.Pull(context.Background(), "alpine:3.22", image.WithPullOptions(opts), image.WithPullHandler(func(r io.ReadCloser) error {
		_, err := io.Copy(buff, r)
		return err
	}))

	fmt.Println(err)
	fmt.Println(strings.Contains(buff.String(), "Pulling from library/alpine"))

}
Output:

<nil>
true
Example (WithPullOptions)
package main

import (
	"context"
	"fmt"

	dockerclient "github.com/moby/moby/client"
	v1 "github.com/opencontainers/image-spec/specs-go/v1"

	"github.com/docker/go-sdk/image"
)

func main() {
	opts := dockerclient.ImagePullOptions{Platforms: []v1.Platform{
		{
			OS:           "linux",
			Architecture: "amd64",
		},
	}}

	err := image.Pull(context.Background(), "alpine:3.22", image.WithPullOptions(opts))

	fmt.Println(err)

}
Output:

<nil>

func Remove

func Remove(ctx context.Context, image string, opts ...RemoveOption) (dockerclient.ImageRemoveResult, error)

Remove removes an image from the local repository.

func Save

func Save(ctx context.Context, output string, img string, opts ...SaveOption) error

Save saves an image to a file.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"path/filepath"

	"github.com/docker/go-sdk/image"
)

func main() {
	img := "redis:alpine"

	err := image.Pull(context.Background(), img)
	if err != nil {
		log.Println("error pulling image", err)
		return
	}

	tmpDir := os.TempDir()

	output := filepath.Join(tmpDir, "images.tar")
	err = image.Save(context.Background(), output, img)
	if err != nil {
		log.Println("error saving image", err)
		return
	}
	defer func() {
		err := os.Remove(output)
		if err != nil {
			log.Println("error removing image", err)
		}
	}()

	info, err := os.Stat(output)
	if err != nil {
		log.Println("error getting image info", err)
		return
	}

	fmt.Println(info.Size() > 0)

}
Output:

true

func Version

func Version() string

Version returns the version of the image package.

func WithCredentialsFromConfig

func WithCredentialsFromConfig(opts *pullOptions) error

WithCredentialsFromConfig configures pull to retrieve credentials from the CLI config

Types

type BuildOption

type BuildOption func(*buildOptions) error

BuildOption is a function that configures the build options.

func WithBuildClient

func WithBuildClient(buildClient client.SDKClient) BuildOption

WithBuildClient sets the build client used to build the image.

func WithBuildOptions

func WithBuildOptions(options dockerclient.ImageBuildOptions) BuildOption

WithBuildOptions sets the build options used to build the image. If set, the tag and context reader will be ignored.

type PullOption

type PullOption func(*pullOptions) error

PullOption is a function that configures the pull options.

func WithCredentialsFn

func WithCredentialsFn(credentialsFn func(string) (string, string, error)) PullOption

WithCredentialsFn sets the function to retrieve credentials for an image to be pulled

func WithPullClient

func WithPullClient(pullClient client.SDKClient) PullOption

WithPullClient sets the pull client used to pull the image.

func WithPullHandler

func WithPullHandler(pullHandler func(r io.ReadCloser) error) PullOption

WithPullHandler sets the pull handler function for the pull request. Do not close the reader in the function, as it's done by the Pull function.

func WithPullOptions

func WithPullOptions(imagePullOptions dockerclient.ImagePullOptions) PullOption

WithPullOptions sets the pull options used to pull the image.

type RemoveOption

type RemoveOption func(*removeOptions) error

RemoveOption is a function that configures the remove options.

func WithRemoveClient

func WithRemoveClient(removeClient client.SDKClient) RemoveOption

WithRemoveClient sets the remove client used to remove the image.

func WithRemoveOptions

func WithRemoveOptions(options dockerclient.ImageRemoveOptions) RemoveOption

WithRemoveOptions sets the remove options used to remove the image.

type SaveOption

type SaveOption func(*saveOptions) error

SaveOption is a function that configures the save options.

func WithPlatforms

func WithPlatforms(platforms ...ocispec.Platform) SaveOption

WithPlatforms sets the platforms to save the image from.

func WithSaveClient

func WithSaveClient(saveClient client.SDKClient) SaveOption

WithSaveClient sets the save client used to save the image.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL