context

package module
v0.1.0-alpha012 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: 11 Imported by: 1

README

Docker Contexts

This package provides a simple API to interact with Docker contexts.

Installation

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

Usage

Current Context

It returns the current Docker context name.

current, err := context.Current()
if err != nil {
    log.Fatalf("failed to get current docker context: %v", err)
}

fmt.Printf("current docker context: %s", current)
Current Docker Host

It returns the Docker host that the current context is configured to use.

dockerHost, err := context.CurrentDockerHost()
if err != nil {
    log.Fatalf("failed to get current docker host: %v", err)
}
fmt.Printf("current docker host: %s", dockerHost)
Docker Host From Context

It returns the Docker host that the given context is configured to use.

dockerHost, err := context.DockerHostFromContext("desktop-linux")
if err != nil {
    log.Printf("error getting docker host from context: %s", err)
    return
}

fmt.Printf("docker host from context: %s", dockerHost)
Inspect Context

It returns the description of the given context.

description, err := context.Inspect("context1")
if err != nil {
    log.Printf("failed to inspect context: %v", err)
    return
}

fmt.Printf("description: %s", description)

If the context is not found, it returns an ErrDockerContextNotFound error.

List Contexts

It returns the list of contexts available in the Docker configuration.

contexts, err := context.List()
if err != nil {
    log.Printf("failed to list contexts: %v", err)
    return
}

fmt.Printf("contexts: %v", contexts)
Add Context

It adds a new context to the Docker configuration, identified by a name. It's possible to pass options to customize the context definition.

ctx, err := context.New("my-context")
if err != nil {
    log.Printf("failed to add context: %v", err)
    return
}

fmt.Printf("context added: %s", ctx.Name)
Available Options

The following options are available to customize the context definition:

  • WithHost(host string) CreateContextOption sets the host for the context.
  • WithDescription(description string) CreateContextOption sets the description for the context.
  • WithAdditionalFields(fields map[string]any) CreateContextOption sets the additional fields for the context.
  • WithSkipTLSVerify() CreateContextOption sets the skipTLSVerify flag to true.
  • AsCurrent() CreateContextOption sets the context as the current context, saving the current context to the Docker configuration.
Delete Context

It deletes a context from the Docker configuration.

ctx, err := context.New("my-context")
if err != nil {
    log.Printf("error adding context: %s", err)
    return
}

if err := ctx.Delete(); err != nil {
    log.Printf("failed to delete context: %v", err)
    return
}

fmt.Printf("context deleted: %s", ctx.Name)

Documentation

Index

Examples

Constants

View Source
const (
	// DefaultContextName is the name reserved for the default context (config & env based)
	DefaultContextName = "default"

	// EnvOverrideContext is the name of the environment variable that can be
	// used to override the context to use. If set, it overrides the context
	// that's set in the CLI's configuration file, but takes no effect if the
	// "DOCKER_HOST" env-var is set (which takes precedence.
	EnvOverrideContext = "DOCKER_CONTEXT"

	// EnvOverrideHost is the name of the environment variable that can be used
	// to override the default host to connect to (DefaultDockerHost).
	//
	// This env-var is read by FromEnv and WithHostFromEnv and when set to a
	// non-empty value, takes precedence over the default host (which is platform
	// specific), or any host already set.
	EnvOverrideHost = "DOCKER_HOST"
)

Variables

View Source
var (
	// DefaultDockerHost is the default host to connect to the Docker socket.
	// The actual value is platform-specific and defined in host_unix.go and host_windows.go.
	DefaultDockerHost = ""

	// DefaultSchema is the default schema to use for the Docker host.
	// The actual value is platform-specific and defined in host_unix.go and host_windows.go.
	DefaultSchema = ""

	// TCPSchema is the schema to use for TCP connections.
	TCPSchema = "tcp://"
)
View Source
var (
	// ErrDockerHostNotSet is returned when the Docker host is not set in the Docker context.
	ErrDockerHostNotSet = errors.New("docker host not set in Docker context")

	// ErrDockerContextNotFound is returned when the Docker context is not found.
	ErrDockerContextNotFound = errors.New("docker context not found")
)
View Source
var (
	ErrRootlessDockerNotFoundXDGRuntimeDir = errors.New("docker.sock not found in $XDG_RUNTIME_DIR")
	ErrXDGRuntimeDirNotSet                 = errors.New("$XDG_RUNTIME_DIR is not set")
	ErrInvalidSchema                       = errors.New("URL schema is not " + DefaultSchema + " or tcp")
)

Functions

func Current

func Current() (string, error)

Current returns the current context name, based on environment variables and the cli configuration file. It does not validate if the given context exists or if it's valid.

If the current context is not found, it returns the default context name.

Example
package main

import (
	"fmt"

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

func main() {
	ctx, err := context.Current()
	fmt.Println(err)
	fmt.Println(ctx != "")

}
Output:

<nil>
true

func CurrentDockerHost

func CurrentDockerHost() (string, error)

CurrentDockerHost returns the Docker host from the current Docker context. For that, it traverses the directory structure of the Docker configuration directory, looking for the current context and its Docker endpoint.

If the Rootless Docker socket is found, using the XDG_RUNTIME_DIR environment variable, it returns the path to the socket.

If the current context is the default context, it returns the value of the DOCKER_HOST environment variable.

It validates that the Docker host is a valid URL and that the schema is either unix, npipe (on Windows) or tcp.

Example
package main

import (
	"fmt"

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

func main() {
	host, err := context.CurrentDockerHost()
	fmt.Println(err)
	fmt.Println(host != "")

}
Output:

<nil>
true

func DockerHostFromContext

func DockerHostFromContext(ctxName string) (string, error)

DockerHostFromContext returns the Docker host from the given context.

Example
package main

import (
	"fmt"
	"log"

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

func main() {
	host, err := context.DockerHostFromContext("desktop-linux")
	if err != nil {
		log.Printf("error getting docker host from context: %s", err)
		return
	}

	fmt.Println(host)

	// Intentionally not printing the output, as the context could not exist in the CI environment
}

func List

func List() ([]string, error)

List returns the list of contexts available in the Docker configuration.

Example
package main

import (
	"fmt"
	"log"

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

func main() {
	contexts, err := context.List()
	if err != nil {
		log.Printf("error listing contexts: %s", err)
		return
	}

	fmt.Println(contexts)

	// Intentionally not printing the output, as the contexts could not exist in the CI environment
}

func SetupTestDockerContexts

func SetupTestDockerContexts(tb testing.TB, currentContextIndex int, contextsCount int)

SetupTestDockerContexts creates a temporary directory structure for testing the Docker context functions. It creates the following structure, where $i is the index of the context, starting from 1: - $HOME/.docker

  • config.json
  • contexts
  • meta
  • context$i
  • meta.json

The config.json file contains the current context, and the meta.json files contain the metadata for each context. It generates the specified number of contexts, setting the current context to the one specified by currentContextIndex. The docker host for each context is "tcp://127.0.0.1:$i". Finally it always adds a context with an empty host, to validate the behavior when the host is not set, and a context with a custom endpoint, to validate the behavior when the endpoint is not the default "docker". This empty context can be used setting the currentContextIndex to a number greater than contextsCount.

func Version

func Version() string

Version returns the version of the context package.

Types

type Context

type Context struct {
	// Name is the name of the context
	Name string `json:"Name,omitempty"`

	// Metadata is the metadata stored for a context
	Metadata *Metadata `json:"Metadata,omitempty"`

	// Endpoints is the list of endpoints for the context
	Endpoints map[string]*endpoint `json:"Endpoints,omitempty"`
	// contains filtered or unexported fields
}

Context represents a Docker context

func Inspect

func Inspect(ctxName string) (Context, error)

Inspect returns the given context. It returns an error if the context is not found or if the docker endpoint is not set.

Example
package main

import (
	"fmt"
	"log"

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

func main() {
	ctx, err := context.Inspect("docker-cloud")
	if err != nil {
		log.Printf("error inspecting context: %s", err)
		return
	}

	fmt.Println(ctx.Metadata.Description)
	fmt.Println(ctx.Metadata.Field("otel"))
	fmt.Println(ctx.Metadata.Fields())

	// Intentionally not printing the output, as the context could not exist in the CI environment
}

func New

func New(name string, opts ...CreateContextOption) (*Context, error)

New creates a new context.

If the context already exists, it returns an error.

If the AsCurrent option is passed, it updates the Docker config file, setting the current context to the new context.

Example
package main

import (
	"fmt"
	"log"

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

func main() {
	ctx, err := context.New("my-context")
	if err != nil {
		log.Printf("error adding context: %s", err)
		return
	}
	defer func() {
		if err := ctx.Delete(); err != nil {
			log.Printf("error deleting context: %s", err)
		}
	}()

	fmt.Println(ctx.Name)

}
Output:

my-context
Example (AsCurrent)
package main

import (
	"fmt"
	"log"

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

func main() {
	ctx, err := context.New("my-context", context.AsCurrent(), context.WithHost("tcp://127.0.0.1:2375"))
	if err != nil {
		log.Printf("error adding context: %s", err)
		return
	}
	defer func() {
		if err := ctx.Delete(); err != nil {
			log.Printf("error deleting context: %s", err)
		}
	}()

	fmt.Println(ctx.Name)

	current, err := context.Current()
	if err != nil {
		log.Printf("error getting current context: %s", err)
		return
	}
	fmt.Println(current)

	host, err := context.CurrentDockerHost()
	if err != nil {
		log.Printf("error getting current docker host: %s", err)
		return
	}

	fmt.Println(host)

}
Output:

my-context
my-context
tcp://127.0.0.1:2375

func (*Context) Delete

func (ctx *Context) Delete() error

Delete deletes a context. The context must exist: it must have been created with New or inspected with Inspect. If the context is the default context, the current context will be reset to the default context.

type CreateContextOption

type CreateContextOption func(*contextOptions) error

CreateContextOption is a function that can be used to create a context.

func AsCurrent

func AsCurrent() CreateContextOption

AsCurrent sets the context as the current context.

func WithAdditionalFields

func WithAdditionalFields(fields map[string]any) CreateContextOption

WithAdditionalFields sets the additional fields for the context.

func WithDescription

func WithDescription(description string) CreateContextOption

WithDescription sets the description for the context.

func WithHost

func WithHost(host string) CreateContextOption

WithHost sets the host for the context.

func WithSkipTLSVerify

func WithSkipTLSVerify() CreateContextOption

WithSkipTLSVerify sets the skipTLSVerify flag to true.

type Metadata

type Metadata struct {
	// Description is the description of the context
	Description string `json:"Description,omitempty"`
	// contains filtered or unexported fields
}

Metadata represents the metadata stored for a context

func (*Metadata) Field

func (dc *Metadata) Field(key string) (any, bool)

Field returns the value of an additional field

func (*Metadata) Fields

func (dc *Metadata) Fields() map[string]any

Fields returns a copy of all additional fields

func (*Metadata) MarshalJSON

func (dc *Metadata) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshaling for dockerContext

func (*Metadata) SetField

func (dc *Metadata) SetField(key string, value any)

SetField sets the value of an additional field

func (*Metadata) UnmarshalJSON

func (dc *Metadata) UnmarshalJSON(data []byte) error

UnmarshalJSON implements custom JSON unmarshaling for dockerContext

Jump to

Keyboard shortcuts

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