Categorygithub.com/fsouza/go-dockerclient
modulepackage
1.12.1
Repository: https://github.com/fsouza/go-dockerclient.git
Documentation: pkg.go.dev

# README

go-dockerclient

Build Status GoDoc

This package presents a client for the Docker remote API. It also provides support for the extensions in the Swarm API.

This package also provides support for docker's network API, which is a simple passthrough to the libnetwork remote API.

For more details, check the remote API documentation.

Difference between go-dockerclient and the official SDK

Link for the official SDK: https://docs.docker.com/develop/sdk/

go-dockerclient was created before Docker had an official Go SDK and is still maintained and active because it's still used out there. New features in the Docker API do not get automatically implemented here: it's based on demand, if someone wants it, they can file an issue or a PR and the feature may get implemented/merged.

For new projects, using the official SDK is probably more appropriate as go-dockerclient lags behind the official SDK.

Example

package main

import (
	"fmt"

	docker "github.com/fsouza/go-dockerclient"
)

func main() {
	client, err := docker.NewClientFromEnv()
	if err != nil {
		panic(err)
	}
	imgs, err := client.ListImages(docker.ListImagesOptions{All: false})
	if err != nil {
		panic(err)
	}
	for _, img := range imgs {
		fmt.Println("ID: ", img.ID)
		fmt.Println("RepoTags: ", img.RepoTags)
		fmt.Println("Created: ", img.Created)
		fmt.Println("Size: ", img.Size)
		fmt.Println("VirtualSize: ", img.VirtualSize)
		fmt.Println("ParentId: ", img.ParentID)
	}
}

Using with TLS

In order to instantiate the client for a TLS-enabled daemon, you should use NewTLSClient, passing the endpoint and path for key and certificates as parameters.

package main

import (
	"fmt"

	docker "github.com/fsouza/go-dockerclient"
)

func main() {
	const endpoint = "tcp://[ip]:[port]"
	path := os.Getenv("DOCKER_CERT_PATH")
	ca := fmt.Sprintf("%s/ca.pem", path)
	cert := fmt.Sprintf("%s/cert.pem", path)
	key := fmt.Sprintf("%s/key.pem", path)
	client, _ := docker.NewTLSClient(endpoint, cert, key, ca)
	// use client
}

If using docker-machine, or another application that exports environment variables DOCKER_HOST, DOCKER_TLS_VERIFY, DOCKER_CERT_PATH, DOCKER_API_VERSION, you can use NewClientFromEnv.

package main

import (
	"fmt"

	docker "github.com/fsouza/go-dockerclient"
)

func main() {
	client, err := docker.NewClientFromEnv()
	if err != nil {
		// handle err
	}
	// use client
}

See the documentation for more details.

Developing

All development commands can be seen in the Makefile.

Committed code must pass:

Running make test will run all checks, as well as install any required dependencies.

# Packages

Package testing provides a fake implementation of the Docker API, useful for testing purpose.

# Functions

AlwaysRestart returns a restart policy that tells the Docker daemon to always restart the container.
NeverRestart returns a restart policy that tells the Docker daemon to never restart the container on failures.
NewAPIVersion returns an instance of APIVersion for the given string.
NewAuthConfigurations returns AuthConfigurations from a JSON encoded string in the same format as the .dockercfg file.
NewAuthConfigurationsFromCredsHelpers returns AuthConfigurations from installed credentials helpers.
NewAuthConfigurationsFromDockerCfg returns AuthConfigurations from system config files.
NewAuthConfigurationsFromFile returns AuthConfigurations from a path containing JSON in the same format as the .dockercfg file.
NewClient returns a Client instance ready for communication with the given server endpoint.
NewClientFromEnv returns a Client instance ready for communication created from Docker's default logic for the environment variables DOCKER_HOST, DOCKER_TLS_VERIFY, DOCKER_CERT_PATH, and DOCKER_API_VERSION.
NewTLSClient returns a Client instance ready for TLS communications with the givens server endpoint, key and certificates .
NewTLSClientFromBytes returns a Client instance ready for TLS communications with the givens server endpoint, key and certificates (passed inline to the function as opposed to being read from a local file).
NewVersionedClient returns a Client instance ready for communication with the given server endpoint, using a specific remote API version.
NewVersionedClientFromEnv returns a Client instance ready for TLS communications created from Docker's default logic for the environment variables DOCKER_HOST, DOCKER_TLS_VERIFY, and DOCKER_CERT_PATH, and using a specific remote API version.
NewVersionedTLSClient returns a Client instance ready for TLS communications with the givens server endpoint, key and certificates, using a specific remote API version.
NewVersionedTLSClientFromBytes returns a Client instance ready for TLS communications with the givens server endpoint, key and certificates (passed inline to the function as opposed to being read from a local file), using a specific remote API version.
NewVersionnedTLSClient is like NewVersionedClient, but with ann extra n.
ParseRepositoryTag gets the name of the repository and returns it splitted in two parts: the repository and the tag.
RestartOnFailure returns a restart policy that tells the Docker daemon to restart the container on failures, trying at most maxRetry times.
RestartUnlessStopped returns a restart policy that tells the Docker daemon to always restart the container except when user has manually stopped the container.

# Constants

ChangeAdd is the ChangeType for additions to a container.
ChangeDelete is the ChangeType for deletions from a container.
ChangeModify is the ChangeType for container modifications.
These values represent all signals available on Linux, where containers will be running.
These values represent all signals available on Linux, where containers will be running.
These values represent all signals available on Linux, where containers will be running.
These values represent all signals available on Linux, where containers will be running.
These values represent all signals available on Linux, where containers will be running.
These values represent all signals available on Linux, where containers will be running.
These values represent all signals available on Linux, where containers will be running.
These values represent all signals available on Linux, where containers will be running.
These values represent all signals available on Linux, where containers will be running.
These values represent all signals available on Linux, where containers will be running.
These values represent all signals available on Linux, where containers will be running.
These values represent all signals available on Linux, where containers will be running.
These values represent all signals available on Linux, where containers will be running.
These values represent all signals available on Linux, where containers will be running.
These values represent all signals available on Linux, where containers will be running.
These values represent all signals available on Linux, where containers will be running.
These values represent all signals available on Linux, where containers will be running.
These values represent all signals available on Linux, where containers will be running.
These values represent all signals available on Linux, where containers will be running.
These values represent all signals available on Linux, where containers will be running.
These values represent all signals available on Linux, where containers will be running.
These values represent all signals available on Linux, where containers will be running.
These values represent all signals available on Linux, where containers will be running.
These values represent all signals available on Linux, where containers will be running.
These values represent all signals available on Linux, where containers will be running.
These values represent all signals available on Linux, where containers will be running.
These values represent all signals available on Linux, where containers will be running.
These values represent all signals available on Linux, where containers will be running.
These values represent all signals available on Linux, where containers will be running.
These values represent all signals available on Linux, where containers will be running.
These values represent all signals available on Linux, where containers will be running.
These values represent all signals available on Linux, where containers will be running.
These values represent all signals available on Linux, where containers will be running.
These values represent all signals available on Linux, where containers will be running.
These values represent all signals available on Linux, where containers will be running.

# Variables

EOFEvent is sent when the event listener receives an EOF error.
ErrCannotParseDockercfg is the error returned by NewAuthConfigurations when the dockercfg cannot be parsed.
ErrConnectionRefused is returned when the client cannot connect to the given endpoint.
ErrContainerAlreadyExists is the error returned by CreateContainer when the container already exists.
ErrInactivityTimeout is returned when a streamable call has been inactive for some time.
ErrInvalidEndpoint is returned when the endpoint is not a valid HTTP URL.
ErrListenerAlreadyExists is the error returned when the listerner already exists.
ErrMissingOutputStream is the error returned when no output stream is provided to some calls, like BuildImage.
ErrMissingRepo is the error returned when the remote repository is missing.
ErrMultipleContexts is the error returned when both a ContextDir and InputStream are provided in BuildImageOptions.
ErrMustSpecifyNames is the error returned when the Names field on ExportImagesOptions is nil or empty.
ErrNetworkAlreadyExists is the error returned by CreateNetwork when the network already exists.
ErrNodeAlreadyInSwarm is the error returned by InitSwarm and JoinSwarm when the node is already part of a Swarm.
ErrNodeNotInSwarm is the error returned by LeaveSwarm and UpdateSwarm when the node is not part of a Swarm.
ErrNoListeners is the error returned when no listeners are available to receive an event.
ErrNoSuchImage is the error returned when the image does not exist.
ErrNoSuchVolume is the error returned when the volume does not exist.
ErrTLSNotSupported is the error returned when the client does not support TLS (this applies to the Windows named pipe client).
ErrVolumeInUse is the error returned when the volume requested to be removed is still in use.

# Structs

APIActor represents an actor that accomplishes something for an event.
APIContainers represents each container in the list returned by ListContainers.
APIEvents represents events coming from the Docker API The fields in the Docker API changed in API version 1.22, and events for more than images and containers are now fired off.
APIImages represent an image returned in the ListImages call.
APIImageSearch reflect the result of a search on the Docker Hub.
APIMount represents a mount point for a container.
APIPort is a type that represents a port mapping returned by the Docker API.
AttachToContainerOptions is the set of options that can be used when attaching to a container.
AuthConfiguration represents authentication options to use in the PushImage method.
AuthConfigurations represents authentication options to use for the PushImage method accommodating the new X-Registry-Config header.
AuthStatus returns the authentication status for Docker API versions >= 1.23.
BindOptions contains optional configuration for the bind type.
BlkioStatsEntry is a stats entry for blkio_stats.
BlockLimit represents a read/write limit in IOPS or Bandwidth for a device inside of a container.
BlockWeight represents a relative device weight for an individual device inside of a container.
BuildArg represents arguments that can be passed to the image when building it from a Dockerfile.
BuildImageOptions present the set of informations available for building an image from a tarfile with a Dockerfile in it.
Change represents a change in a container.
Client is the basic type of this package.
CommitContainerOptions aggregates parameters to the CommitContainer method.
Config is the list of configuration options used when creating a container.
ConfigurePluginOptions specify parameters to the ConfigurePlugin See https://goo.gl/C4t7Tz for more details.
Container is the type encompasing everything about a container - its config, hostconfig, etc.
ContainerAlreadyRunning is the error returned when a given container is already running.
ContainerNetwork represents the networking settings of a container per network.
ContainerNotRunning is the error returned when a given container is not running.
CopyFromContainerOptions contains the set of options used for copying files from a container.
CPUStats is a stats entry for cpu stats.
CreateConfigOptions specify parameters to the CreateConfig function.
CreateContainerOptions specify parameters to the CreateContainer function.
CreateExecOptions specify parameters to the CreateExecContainer function.
CreateNetworkOptions specify parameters to the CreateNetwork function and (for now) is the expected body of the "create network" http request message See https://goo.gl/6GugX3 for more details.
CreatePluginOptions specify parameters to the CreatePlugin function.
CreateSecretOptions specify parameters to the CreateSecret function.
CreateServiceOptions specify parameters to the CreateService function.
CreateVolumeOptions specify parameters to the CreateVolume function.
Device represents a device mapping between the Docker host and the container.
DeviceRequest represents a request for device that's sent to device drivers.
DisablePluginOptions specify parameters to the DisablePlugin function.
DiskUsage holds information about what docker is using disk space on.
DiskUsageOptions only contains a context for canceling.
DockerInfo contains information about the Docker server See https://goo.gl/bHUoz9 for more details.
DownloadFromContainerOptions is the set of options that can be used when downloading resources from a container.
EnablePluginOptions specify parameters to the EnablePlugin function.
Endpoint contains network resources allocated and used for a container in a network See https://goo.gl/6GugX3 for more details.
EndpointConfig stores network endpoint details See https://goo.gl/RV7BJU for more details.
EndpointIPAMConfig represents IPAM configurations for an endpoint See https://goo.gl/RV7BJU for more details.
Error represents failures in the API.
EventsOptions to filter events See https://docs.docker.com/engine/api/v1.41/#operation/SystemEvents for more details.
Exec is the type representing a `docker exec` instance and containing the instance ID.
ExecInspect is a type with details about a exec instance, including the exit code if the command has finished running.
ExecProcessConfig is a type describing the command associated to a Exec instance.
ExportContainerOptions is the set of parameters to the ExportContainer method.
ExportImageOptions represent the options for ExportImage Docker API call.
ExportImagesOptions represent the options for ExportImages Docker API call See https://goo.gl/N9XlDn for more details.
GetPluginPrivilegesOptions specify parameters to the GetPluginPrivilegesWithOptions function.
GraphDriver contains information about the GraphDriver used by the container.
Health represents the health of a container.
HealthCheck represents one check of health.
HealthConfig holds configuration settings for the HEALTHCHECK feature It has been added in the version 1.24 of the Docker API, available since Docker 1.12.
HostConfig contains the container options related to starting a container on a given host.
HostMount represents a mount point in the container in HostConfig.
Image is the type representing a docker image and its various properties.
ImageHistory represent a layer in an image's history returned by the ImageHistory call.
ImagePre012 serves the same purpose as the Image type except that it is for earlier versions of the Docker API (pre-012 to be specific).
ImageSummary represents data about what images are currently known to docker More Info Here https://dockr.ly/2PNzQyO.
ImportImageOptions present the set of informations available for importing an image from a source file or the stdin.
IndexInfo contains information about a registry.
InitSwarmOptions specify parameters to the InitSwarm function.
InspectContainerOptions specifies parameters for InspectContainerWithOptions.
InstallPluginOptions specify parameters to the InstallPlugins function.
IPAMConfig represents IPAM configurations See https://goo.gl/T8kRVH for more details.
IPAMOptions controls IP Address Management when creating a network See https://goo.gl/T8kRVH for more details.
JoinSwarmOptions specify parameters to the JoinSwarm function.
KeyValuePair is a type for generic key/value pairs as used in the Lxc configuration.
KillContainerOptions represents the set of options that can be used in a call to KillContainer.
LeaveSwarmOptions specify parameters to the LeaveSwarm function.
ListConfigsOptions specify parameters to the ListConfigs function.
ListContainersOptions specify parameters to the ListContainers function.
ListFilteredPluginsOptions specify parameters to the ListFilteredPlugins function.
ListImagesOptions specify parameters to the ListImages function.
ListNodesOptions specify parameters to the ListNodes function.
ListSecretsOptions specify parameters to the ListSecrets function.
ListServicesOptions specify parameters to the ListServices function.
ListTasksOptions specify parameters to the ListTasks function.
ListVolumesOptions specify parameters to the ListVolumes function.
LoadImageOptions represents the options for LoadImage Docker API Call See https://goo.gl/rEsBV3 for more details.
LogConfig defines the log driver type and the configuration for it.
LogsOptions represents the set of options used when getting logs from a container.
LogsServiceOptions represents the set of options used when getting logs from a service.
Mount represents a mount point in the container.
Network represents a network.
NetworkConfigFrom is used in network creation for specifying the source of a network configuration.
NetworkConnectionOptions specify parameters to the ConnectNetwork and DisconnectNetwork function.
NetworkingConfig represents the container's networking configuration for each of its interfaces Carries the networking configs specified in the `docker run` and `docker network connect` commands.
NetworkList encapsulates a map of networks, as returned by the Docker API in ListContainers.
NetworkSettings contains network-related information about a container.
NetworkStats is a stats entry for network stats.
NoSuchConfig is the error returned when a given config does not exist.
NoSuchContainer is the error returned when a given container does not exist.
NoSuchExec is the error returned when a given exec instance does not exist.
NoSuchNetwork is the error returned when a given network does not exist.
NoSuchNetworkOrContainer is the error returned when a given network or container does not exist.
NoSuchNode is the error returned when a given node does not exist.
NoSuchPlugin is the error returned when a given plugin does not exist.
NoSuchSecret is the error returned when a given secret does not exist.
NoSuchService is the error returned when a given service does not exist.
NoSuchTask is the error returned when a given task does not exist.
PluginArgs stores plugin arguments.
PluginConfig stores plugin config.
PluginDetail specify results from the ListPlugins function.
PluginEnv stores plugin environment.
PluginInterface stores plugin interface.
PluginLinux stores plugin linux setting.
PluginLinuxDevices stores plugin linux device setting.
PluginNetwork stores plugin network type.
PluginPrivilege represents a privilege for a plugin.
PluginSettings stores plugin settings.
PluginsInfo is a struct with the plugins registered with the docker daemon for more information, see: https://goo.gl/bHUoz9.
PluginUser stores plugin user.
PortBinding represents the host/container port mapping as returned in the `docker inspect` json.
PruneContainersOptions specify parameters to the PruneContainers function.
PruneContainersResults specify results from the PruneContainers function.
PruneImagesOptions specify parameters to the PruneImages function.
PruneImagesResults specify results from the PruneImages function.
PruneNetworksOptions specify parameters to the PruneNetworks function.
PruneNetworksResults specify results from the PruneNetworks function.
PruneVolumesOptions specify parameters to the PruneVolumes function.
PruneVolumesResults specify results from the PruneVolumes function.
PullImageOptions present the set of options available for pulling an image from a registry.
PushImageOptions represents options to use in the PushImage method.
PushPluginOptions specify parameters to PushPlugin function.
RemoveConfigOptions encapsulates options to remove a config.
RemoveContainerOptions encapsulates options to remove a container.
RemoveImageOptions present the set of options available for removing an image from a registry.
RemoveNodeOptions specify parameters to the RemoveNode function.
RemovePluginOptions specify parameters to the RemovePlugin function.
RemoveSecretOptions encapsulates options to remove a secret.
RemoveServiceOptions encapsulates options to remove a service.
RemoveVolumeOptions specify parameters to the RemoveVolumeWithOptions function.
RenameContainerOptions specify parameters to the RenameContainer function.
RestartPolicy represents the policy for automatically restarting a container.
RootFS represents the underlying layers used by an image.
Runtime describes an OCI runtime for more information, see: https://dockr.ly/2NKM8qq.
ServiceConfig stores daemon registry services configuration.
StartExecOptions specify parameters to the StartExecContainer function.
State represents the state of a container.
Stats represents container statistics, returned by /containers/<id>/stats.
StatsOptions specify parameters to the Stats function.
SwarmNode containers information about which Swarm node the container is on.
TagImageOptions present the set of options to tag an image.
TempfsOptions contains optional configuration for the tempfs type.
TopResult represents the list of processes running in a container, as returned by /containers/<id>/top.
ULimit defines system-wide resource limitations This can help a lot in system administration, e.g.
UpdateConfigOptions specify parameters to the UpdateConfig function.
UpdateContainerOptions specify parameters to the UpdateContainer function.
UpdateNodeOptions specify parameters to the NodeUpdate function.
UpdateSecretOptions specify parameters to the UpdateSecret function.
UpdateServiceOptions specify parameters to the UpdateService function.
UpdateSwarmOptions specify parameters to the UpdateSwarm function.
UploadToContainerOptions is the set of options that can be used when uploading an archive into a container.
Volume represents a volume.
VolumeDriverConfig holds a map of volume driver specific options.
VolumeOptions contains optional configuration for the volume type.
VolumeUsageData represents usage data from the docker system api More Info Here https://dockr.ly/2PNzQyO.

# Interfaces

CloseWaiter is an interface with methods for closing the underlying resource and then waiting for it to finish processing.
Dialer is an interface that allows network connections to be dialed (net.Dialer fulfills this interface) and named pipes (a shim using winio.DialPipe).

# Type aliases

APIVersion is an internal representation of a version of the Remote API.
AuthConfigurations119 is used to serialize a set of AuthConfigurations for Docker API >= 1.19.
BuilderVersion represents either the BuildKit or V1 ("classic") builder.
ChangeType is a type for constants indicating the type of change in a container.
Env represents a list of key-pair represented in the form KEY=VALUE.
NetIPNet is the net.IPNet type, which can be marshalled and unmarshalled to JSON.
NetworkFilterOpts is an aggregation of key=value that Docker uses to filter networks.
Port represents the port number and the protocol, in the form <number>/<protocol>.
PortMapping represents a deprecated field in the `docker inspect` output, and its value as found in NetworkSettings should always be nil.
Signal represents a signal that can be send to the container on KillContainer call.