Low-level API¶
The main object-orientated API is built on top of APIClient
. Each method on APIClient
maps one-to-one with a REST API endpoint, and returns the response that the API responds with.
It’s possible to use APIClient
directly. Some basic things (e.g. running a container) consist of several API calls and are complex to do with the low-level API, but it’s useful if you need extra flexibility and power.
- class APIClient(base_url=None, version=None, timeout=60, tls=False, user_agent='docker-sdk-python/7.1.0', num_pools=None, credstore_env=None, use_ssh_client=False, max_pool_size=10)¶
A low-level client for the Docker Engine API.
Example
>>> import docker >>> client = docker.APIClient(base_url='unix://var/run/docker.sock') >>> client.version() {u'ApiVersion': u'1.33', u'Arch': u'amd64', u'BuildTime': u'2017-11-19T18:46:37.000000000+00:00', u'GitCommit': u'f4ffd2511c', u'GoVersion': u'go1.9.2', u'KernelVersion': u'4.14.3-1-ARCH', u'MinAPIVersion': u'1.12', u'Os': u'linux', u'Version': u'17.10.0-ce'}
- Parameters:
base_url (str) – URL to the Docker server. For example,
unix:///var/run/docker.sock
ortcp://127.0.0.1:1234
.version (str) – The version of the API to use. Set to
auto
to automatically detect the server’s version. Default:1.35
timeout (int) – Default timeout for API calls, in seconds.
tls (bool or
TLSConfig
) – Enable TLS. PassTrue
to enable it with default options, or pass aTLSConfig
object to use custom configuration.user_agent (str) – Set a custom user agent for requests to the server.
credstore_env (dict) – Override environment variables when calling the credential store process.
use_ssh_client (bool) – If set to True, an ssh connection is made via shelling out to the ssh client. Ensure the ssh client is installed and configured on the host.
max_pool_size (int) – The maximum number of connections to save in the pool.
Configs¶
Containers¶
Images¶
Building images¶
Networks¶
Volumes¶
Executing commands in containers¶
Swarms¶
Services¶
Plugins¶
Secrets¶
The Docker daemon¶
Configuration types¶
- class ConfigReference(config_id, config_name, filename=None, uid=None, gid=None, mode=292)¶
Config reference to be used as part of a
ContainerSpec
. Describes how a config is made accessible inside the service’s containers.- Parameters:
config_id (string) – Config’s ID
config_name (string) – Config’s name as defined at its creation.
filename (string) – Name of the file containing the config. Defaults to the config’s name if not specified.
uid (string) – UID of the config file’s owner. Default: 0
gid (string) – GID of the config file’s group. Default: 0
mode (int) – File access mode inside the container. Default: 0o444
- class ContainerSpec(image, command=None, args=None, hostname=None, env=None, workdir=None, user=None, labels=None, mounts=None, stop_grace_period=None, secrets=None, tty=None, groups=None, open_stdin=None, read_only=None, stop_signal=None, healthcheck=None, hosts=None, dns_config=None, configs=None, privileges=None, isolation=None, init=None, cap_add=None, cap_drop=None, sysctls=None)¶
Describes the behavior of containers that are part of a task, and is used when declaring a
TaskTemplate
.- Parameters:
image (string) – The image name to use for the container.
command (string or list) – The command to be run in the image.
args (
list
) – Arguments to the command.hostname (string) – The hostname to set on the container.
env (dict) – Environment variables.
workdir (string) – The working directory for commands to run in.
user (string) – The user inside the container.
labels (dict) – A map of labels to associate with the service.
mounts (
list
) – A list of specifications for mounts to be added to containers created as part of the service. See theMount
class for details.stop_grace_period (int) – Amount of time to wait for the container to terminate before forcefully killing it.
secrets (
list
) – List ofSecretReference
to be made available inside the containers.tty (boolean) – Whether a pseudo-TTY should be allocated.
groups (
list
) – A list of additional groups that the container process will run as.open_stdin (boolean) – Open
stdin
read_only (boolean) – Mount the container’s root filesystem as read only.
stop_signal (string) – Set signal to stop the service’s containers
healthcheck (Healthcheck) – Healthcheck configuration for this service.
hosts (
dict
) – A set of host to IP mappings to add to the container’shosts
file.dns_config (DNSConfig) – Specification for DNS related configurations in resolver configuration file.
configs (
list
) – List ofConfigReference
that will be exposed to the service.privileges (Privileges) – Security options for the service’s containers.
isolation (string) – Isolation technology used by the service’s containers. Only used for Windows containers.
init (boolean) – Run an init inside the container that forwards signals and reaps processes.
cap_add (
list
) – A list of kernel capabilities to add to the default set for the container.cap_drop (
list
) – A list of kernel capabilities to drop from the default set for the container.sysctls (
dict
) – A dict of sysctl values to add to the container
- class DNSConfig(nameservers=None, search=None, options=None)¶
Specification for DNS related configurations in resolver configuration file (
resolv.conf
). Part of aContainerSpec
definition.- Parameters:
nameservers (
list
) – The IP addresses of the name servers.search (
list
) – A search list for host-name lookup.options (
list
) – A list of internal resolver variables to be modified (e.g.,debug
,ndots:3
, etc.).
- class DriverConfig(name, options=None)¶
Indicates which driver to use, as well as its configuration. Can be used as
log_driver
in aContainerSpec
, for the driver_config in a volumeMount
, or as the driver object increate_secret()
.- Parameters:
name (string) – Name of the driver to use.
options (dict) – Driver-specific options. Default:
None
.
- class EndpointSpec(mode=None, ports=None)¶
Describes properties to access and load-balance a service.
- Parameters:
mode (string) – The mode of resolution to use for internal load balancing between tasks (
'vip'
or'dnsrr'
). Defaults to'vip'
if not provided.ports (dict) – Exposed ports that this service is accessible on from the outside, in the form of
{ published_port: target_port }
or{ published_port: <port_config_tuple> }
. Port config tuple format is(target_port [, protocol [, publish_mode]])
. Ports can only be provided if thevip
resolution mode is used.
- class Healthcheck(**kwargs)¶
Defines a healthcheck configuration for a container or service.
- Parameters:
test (
list
or str) –Test to perform to determine container health. Possible values:
Empty list: Inherit healthcheck from parent image
["NONE"]
: Disable healthcheck["CMD", args...]
: exec arguments directly.["CMD-SHELL", command]
: Run command in the system’s default shell.
If a string is provided, it will be used as a
CMD-SHELL
command.interval (int) – The time to wait between checks in nanoseconds. It should be 0 or at least 1000000 (1 ms).
timeout (int) – The time to wait before considering the check to have hung. It should be 0 or at least 1000000 (1 ms).
retries (int) – The number of consecutive failures needed to consider a container as unhealthy.
start_period (int) – Start period for the container to initialize before starting health-retries countdown in nanoseconds. It should be 0 or at least 1000000 (1 ms).
- class IPAMConfig(driver='default', pool_configs=None, options=None)¶
Create an IPAM (IP Address Management) config dictionary to be used with
create_network()
.- Parameters:
driver (str) – The IPAM driver to use. Defaults to
default
.pool_configs (
list
) – A list of pool configurations (IPAMPool
). Defaults to empty list.options (dict) – Driver options as a key-value dictionary. Defaults to None.
Example
>>> ipam_config = docker.types.IPAMConfig(driver='default') >>> network = client.create_network('network1', ipam=ipam_config)
- class IPAMPool(subnet=None, iprange=None, gateway=None, aux_addresses=None)¶
Create an IPAM pool config dictionary to be added to the
pool_configs
parameter ofIPAMConfig
.- Parameters:
subnet (str) – Custom subnet for this IPAM pool using the CIDR notation. Defaults to
None
.iprange (str) – Custom IP range for endpoints in this IPAM pool using the CIDR notation. Defaults to
None
.gateway (str) – Custom IP address for the pool’s gateway.
aux_addresses (dict) – A dictionary of
key -> ip_address
relationships specifying auxiliary addresses that need to be allocated by the IPAM driver.
Example
>>> ipam_pool = docker.types.IPAMPool( subnet='124.42.0.0/16', iprange='124.42.0.0/24', gateway='124.42.0.254', aux_addresses={ 'reserved1': '124.42.1.1' } ) >>> ipam_config = docker.types.IPAMConfig( pool_configs=[ipam_pool])
- class LogConfig(**kwargs)¶
Configure logging for a container, when provided as an argument to
create_host_config()
. You may refer to the official logging driver documentation for more information.- Parameters:
type (str) – Indicate which log driver to use. A set of valid drivers is provided as part of the
LogConfig.types
enum. Other values may be accepted depending on the engine version and available logging plugins.config (dict) – A driver-dependent configuration dictionary. Please refer to the driver’s documentation for a list of valid config keys.
Example
>>> from docker.types import LogConfig >>> lc = LogConfig(type=LogConfig.types.JSON, config={ ... 'max-size': '1g', ... 'labels': 'production_status,geo' ... }) >>> hc = client.create_host_config(log_config=lc) >>> container = client.create_container('busybox', 'true', ... host_config=hc) >>> client.inspect_container(container)['HostConfig']['LogConfig'] { 'Type': 'json-file', 'Config': {'labels': 'production_status,geo', 'max-size': '1g'} }
- class Mount(target, source, type='volume', read_only=False, consistency=None, propagation=None, no_copy=False, labels=None, driver_config=None, tmpfs_size=None, tmpfs_mode=None)¶
Describes a mounted folder’s configuration inside a container. A list of
Mount
would be used as part of aContainerSpec
.- Parameters:
target (string) – Container path.
source (string) – Mount source (e.g. a volume name or a host path).
type (string) – The mount type (
bind
/volume
/tmpfs
/npipe
). Default:volume
.read_only (bool) – Whether the mount should be read-only.
consistency (string) – The consistency requirement for the mount. One of
default` –
consistent –
cached –
delegated. –
propagation (string) – A propagation mode with the value
[r]private
,[r]shared
, or[r]slave
. Only valid for thebind
type.no_copy (bool) – False if the volume should be populated with the data from the target. Default:
False
. Only valid for thevolume
type.labels (dict) – User-defined name and labels for the volume. Only valid for the
volume
type.driver_config (DriverConfig) – Volume driver configuration. Only valid for the
volume
type.tmpfs_size (int or string) – The size for the tmpfs mount in bytes.
tmpfs_mode (int) – The permission mode for the tmpfs mount.
- class NetworkAttachmentConfig(target, aliases=None, options=None)¶
Network attachment options for a service.
- Parameters:
target (str) – The target network for attachment. Can be a network name or ID.
aliases (
list
) – A list of discoverable alternate names for the service.options (
dict
) – Driver attachment options for the network target.
- class Placement(constraints=None, preferences=None, platforms=None, maxreplicas=None)¶
Placement constraints to be used as part of a
TaskTemplate
- Parameters:
constraints (
list
of str) – A list of constraintspreferences (
list
of tuple) – Preferences provide a way to make the scheduler aware of factors such as topology. They are provided in order from highest to lowest precedence and are expressed as(strategy, descriptor)
tuples. SeePlacementPreference
for details.maxreplicas (int) – Maximum number of replicas per node
platforms (
list
of tuple) – A list of platforms expressed as(arch, os)
tuples
- class PlacementPreference(strategy, descriptor)¶
Placement preference to be used as an element in the list of preferences for
Placement
objects.- Parameters:
strategy (string) – The placement strategy to implement. Currently, the only supported strategy is
spread
.descriptor (string) – A label descriptor. For the spread strategy, the scheduler will try to spread tasks evenly over groups of nodes identified by this label.
- class Privileges(credentialspec_file=None, credentialspec_registry=None, selinux_disable=None, selinux_user=None, selinux_role=None, selinux_type=None, selinux_level=None)¶
Security options for a service’s containers. Part of a
ContainerSpec
definition.- Parameters:
credentialspec_file (str) – Load credential spec from this file. The file is read by the daemon, and must be present in the CredentialSpecs subdirectory in the docker data directory, which defaults to
C:\ProgramData\Docker\
on Windows. Can not be combined with credentialspec_registry.credentialspec_registry (str) – Load credential spec from this value in the Windows registry. The specified registry value must be located in:
HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion \Virtualization\Containers\CredentialSpecs
. Can not be combined with credentialspec_file.selinux_disable (boolean) – Disable SELinux
selinux_user (string) – SELinux user label
selinux_role (string) – SELinux role label
selinux_type (string) – SELinux type label
selinux_level (string) – SELinux level label
- class Resources(cpu_limit=None, mem_limit=None, cpu_reservation=None, mem_reservation=None, generic_resources=None)¶
Configures resource allocation for containers when made part of a
ContainerSpec
.- Parameters:
cpu_limit (int) – CPU limit in units of 10^9 CPU shares.
mem_limit (int) – Memory limit in Bytes.
cpu_reservation (int) – CPU reservation in units of 10^9 CPU shares.
mem_reservation (int) – Memory reservation in Bytes.
generic_resources (dict or
list
) – Node level generic resources, for example a GPU, using the following format:{ resource_name: resource_value }
. Alternatively, a list of of resource specifications as defined by the Engine API.
- class RestartPolicy(condition='none', delay=0, max_attempts=0, window=0)¶
Used when creating a
ContainerSpec
, dictates whether a container should restart after stopping or failing.- Parameters:
condition (string) – Condition for restart (
none
,on-failure
, orany
). Default: none.delay (int) – Delay between restart attempts. Default: 0
max_attempts (int) – Maximum attempts to restart a given container before giving up. Default value is 0, which is ignored.
window (int) – Time window used to evaluate the restart policy. Default value is 0, which is unbounded.
- class RollbackConfig(parallelism=0, delay=None, failure_action='continue', monitor=None, max_failure_ratio=None, order=None)¶
Used to specify the way container rollbacks should be performed by a service
- Parameters:
parallelism (int) – Maximum number of tasks to be rolled back in one iteration (0 means unlimited parallelism). Default: 0
delay (int) – Amount of time between rollbacks, in nanoseconds.
failure_action (string) – Action to take if a rolled back task fails to run, or stops running during the rollback. Acceptable values are
continue
,pause
orrollback
. Default:continue
monitor (int) – Amount of time to monitor each rolled back task for failures, in nanoseconds.
max_failure_ratio (float) – The fraction of tasks that may fail during a rollback before the failure action is invoked, specified as a floating point number between 0 and 1. Default: 0
order (string) – Specifies the order of operations when rolling out a rolled back task. Either
start-first
orstop-first
are accepted.
- class SecretReference(secret_id, secret_name, filename=None, uid=None, gid=None, mode=292)¶
Secret reference to be used as part of a
ContainerSpec
. Describes how a secret is made accessible inside the service’s containers.- Parameters:
secret_id (string) – Secret’s ID
secret_name (string) – Secret’s name as defined at its creation.
filename (string) – Name of the file containing the secret. Defaults to the secret’s name if not specified.
uid (string) – UID of the secret file’s owner. Default: 0
gid (string) – GID of the secret file’s group. Default: 0
mode (int) – File access mode inside the container. Default: 0o444
- class ServiceMode(mode, replicas=None, concurrency=None)¶
Indicate whether a service or a job should be deployed as a replicated or global service, and associated parameters
- Parameters:
mode (string) – Can be either
replicated
,global
,replicated-job
orglobal-job
replicas (int) – Number of replicas. For replicated services only.
concurrency (int) – Number of concurrent jobs. For replicated job services only.
- class SwarmExternalCA(url, protocol=None, options=None, ca_cert=None)¶
Configuration for forwarding signing requests to an external certificate authority.
- Parameters:
url (string) – URL where certificate signing requests should be sent.
protocol (string) – Protocol for communication with the external CA.
options (dict) – An object with key/value pairs that are interpreted as protocol-specific options for the external CA driver.
ca_cert (string) – The root CA certificate (in PEM format) this external CA uses to issue TLS certificates (assumed to be to the current swarm root CA certificate if not provided).
- class SwarmSpec(*args, **kwargs)¶
Describe a Swarm’s configuration and options. Use
create_swarm_spec()
to instantiate.
- class TaskTemplate(container_spec, resources=None, restart_policy=None, placement=None, log_driver=None, networks=None, force_update=None)¶
Describe the task specification to be used when creating or updating a service.
- Parameters:
container_spec (ContainerSpec) – Container settings for containers started as part of this task.
log_driver (DriverConfig) – Log configuration for containers created as part of the service.
resources (Resources) – Resource requirements which apply to each individual container created as part of the service.
restart_policy (RestartPolicy) – Specification for the restart policy which applies to containers created as part of this service.
placement (Placement) – Placement instructions for the scheduler. If a list is passed instead, it is assumed to be a list of constraints as part of a
Placement
object.networks (
list
) – List of network names or IDs orNetworkAttachmentConfig
to attach the service to.force_update (int) – A counter that triggers an update even if no relevant parameters have been changed.
- class Ulimit(**kwargs)¶
Create a ulimit declaration to be used with
create_host_config()
.- Parameters:
name (str) – Which ulimit will this apply to. The valid names can be found in ‘/etc/security/limits.conf’ on a gnu/linux system.
soft (int) – The soft limit for this ulimit. Optional.
hard (int) – The hard limit for this ulimit. Optional.
Example
>>> nproc_limit = docker.types.Ulimit(name='nproc', soft=1024) >>> hc = client.create_host_config(ulimits=[nproc_limit]) >>> container = client.create_container( 'busybox', 'true', host_config=hc ) >>> client.inspect_container(container)['HostConfig']['Ulimits'] [{'Name': 'nproc', 'Hard': 0, 'Soft': 1024}]
- class UpdateConfig(parallelism=0, delay=None, failure_action='continue', monitor=None, max_failure_ratio=None, order=None)¶
Used to specify the way container updates should be performed by a service.
- Parameters:
parallelism (int) – Maximum number of tasks to be updated in one iteration (0 means unlimited parallelism). Default: 0.
delay (int) – Amount of time between updates, in nanoseconds.
failure_action (string) – Action to take if an updated task fails to run, or stops running during the update. Acceptable values are
continue
,pause
, as well asrollback
since API v1.28. Default:continue
monitor (int) – Amount of time to monitor each updated task for failures, in nanoseconds.
max_failure_ratio (float) – The fraction of tasks that may fail during an update before the failure action is invoked, specified as a floating point number between 0 and 1. Default: 0
order (string) – Specifies the order of operations when rolling out an updated task. Either
start-first
orstop-first
are accepted.