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.0.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 or tcp://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. Pass True to enable it with default options, or pass a TLSConfig 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

class ConfigApiMixin
configs(filters=None)

List configs

Parameters:
  • filters (list. Available) – A map of filters to process on the configs

  • filtersnames

Returns (list): A list of configs

create_config(name, data, labels=None, templating=None)

Create a config

Parameters:
  • name (string) – Name of the config

  • data (bytes) – Config data to be stored

  • labels (dict) – A mapping of labels to assign to the config

  • templating (dict) – dictionary containing the name of the templating driver to be used expressed as { name: <templating_driver_name>}

Returns (dict): ID of the newly created config

inspect_config(id)

Retrieve config metadata

Parameters:

id (string) – Full ID of the config to inspect

Returns (dict): A dictionary of metadata

Raises:

docker.errors.NotFound – if no config with that ID exists

remove_config(id)

Remove a config

Parameters:

id (string) – Full ID of the config to remove

Returns (boolean): True if successful

Raises:

docker.errors.NotFound – if no config with that ID exists

Containers

class ContainerApiMixin
attach(container, stdout=True, stderr=True, stream=False, logs=False, demux=False)

Attach to a container.

The .logs() function is a wrapper around this method, which you can use instead if you want to fetch/stream container output without first retrieving the entire backlog.

Parameters:
  • container (str) – The container to attach to.

  • stdout (bool) – Include stdout.

  • stderr (bool) – Include stderr.

  • stream (bool) – Return container output progressively as an iterator of strings, rather than a single string.

  • logs (bool) – Include the container’s previous output.

  • demux (bool) – Keep stdout and stderr separate.

Returns:

By default, the container’s output as a single string (two if demux=True: one for stdout and one for stderr).

If stream=True, an iterator of output strings. If demux=True, two iterators are returned: one for stdout and one for stderr.

Raises:

docker.errors.APIError – If the server returns an error.

attach_socket(container, params=None, ws=False)

Like attach, but returns the underlying socket-like object for the HTTP request.

Parameters:
  • container (str) – The container to attach to.

  • params (dict) – Dictionary of request parameters (e.g. stdout, stderr, stream). For detachKeys, ~/.docker/config.json is used by default.

  • ws (bool) – Use websockets instead of raw HTTP.

Raises:

docker.errors.APIError – If the server returns an error.

commit(container, repository=None, tag=None, message=None, author=None, pause=True, changes=None, conf=None)

Commit a container to an image. Similar to the docker commit command.

Parameters:
  • container (str) – The image hash of the container

  • repository (str) – The repository to push the image to

  • tag (str) – The tag to push

  • message (str) – A commit message

  • author (str) – The name of the author

  • pause (bool) – Whether to pause the container before committing

  • changes (str) – Dockerfile instructions to apply while committing

  • conf (dict) – The configuration for the container. See the Engine API documentation for full details.

Raises:

docker.errors.APIError – If the server returns an error.

containers(quiet=False, all=False, trunc=False, latest=False, since=None, before=None, limit=-1, size=False, filters=None)

List containers. Similar to the docker ps command.

Parameters:
  • quiet (bool) – Only display numeric Ids

  • all (bool) – Show all containers. Only running containers are shown by default

  • trunc (bool) – Truncate output

  • latest (bool) – Show only the latest created container, include non-running ones.

  • since (str) – Show only containers created since Id or Name, include non-running ones

  • before (str) – Show only container created before Id or Name, include non-running ones

  • limit (int) – Show limit last created containers, include non-running ones

  • size (bool) – Display sizes

  • filters (dict) –

    Filters to be processed on the image list. Available filters:

    • exited (int): Only containers with specified exit code

    • status (str): One of restarting, running,

      paused, exited

    • label (str|list): format either "key", "key=value"

      or a list of such.

    • id (str): The id of the container.

    • name (str): The name of the container.

    • ancestor (str): Filter by container ancestor. Format of

      <image-name>[:tag], <image-id>, or <image@digest>.

    • before (str): Only containers created before a particular

      container. Give the container name or id.

    • since (str): Only containers created after a particular

      container. Give container name or id.

    A comprehensive list can be found in the documentation for docker ps.

Returns:

A list of dicts, one per container

Raises:

docker.errors.APIError – If the server returns an error.

create_container(image, command=None, hostname=None, user=None, detach=False, stdin_open=False, tty=False, ports=None, environment=None, volumes=None, network_disabled=False, name=None, entrypoint=None, working_dir=None, domainname=None, host_config=None, mac_address=None, labels=None, stop_signal=None, networking_config=None, healthcheck=None, stop_timeout=None, runtime=None, use_config_proxy=True, platform=None)

Creates a container. Parameters are similar to those for the docker run command except it doesn’t support the attach options (-a).

The arguments that are passed directly to this function are host-independent configuration options. Host-specific configuration is passed with the host_config argument. You’ll normally want to use this method in combination with the create_host_config() method to generate host_config.

Port bindings

Port binding is done in two parts: first, provide a list of ports to open inside the container with the ports parameter, then declare bindings with the host_config parameter. For example:

container_id = client.api.create_container(
    'busybox', 'ls', ports=[1111, 2222],
    host_config=client.api.create_host_config(port_bindings={
        1111: 4567,
        2222: None
    })
)

You can limit the host address on which the port will be exposed like such:

client.api.create_host_config(
    port_bindings={1111: ('127.0.0.1', 4567)}
)

Or without host port assignment:

client.api.create_host_config(port_bindings={1111: ('127.0.0.1',)})

If you wish to use UDP instead of TCP (default), you need to declare ports as such in both the config and host config:

container_id = client.api.create_container(
    'busybox', 'ls', ports=[(1111, 'udp'), 2222],
    host_config=client.api.create_host_config(port_bindings={
        '1111/udp': 4567, 2222: None
    })
)

To bind multiple host ports to a single container port, use the following syntax:

client.api.create_host_config(port_bindings={
    1111: [1234, 4567]
})

You can also bind multiple IPs to a single container port:

client.api.create_host_config(port_bindings={
    1111: [
        ('192.168.0.100', 1234),
        ('192.168.0.101', 1234)
    ]
})

Using volumes

Volume declaration is done in two parts. Provide a list of paths to use as mountpoints inside the container with the volumes parameter, and declare mappings from paths on the host in the host_config section.

container_id = client.api.create_container(
    'busybox', 'ls', volumes=['/mnt/vol1', '/mnt/vol2'],
    host_config=client.api.create_host_config(binds={
        '/home/user1/': {
            'bind': '/mnt/vol2',
            'mode': 'rw',
        },
        '/var/www': {
            'bind': '/mnt/vol1',
            'mode': 'ro',
        },
        '/autofs/user1': {
            'bind': '/mnt/vol3',
            'mode': 'rw',
            'propagation': 'shared'
        }
    })
)

You can alternatively specify binds as a list. This code is equivalent to the example above:

container_id = client.api.create_container(
    'busybox', 'ls', volumes=['/mnt/vol1', '/mnt/vol2', '/mnt/vol3'],
    host_config=client.api.create_host_config(binds=[
        '/home/user1/:/mnt/vol2',
        '/var/www:/mnt/vol1:ro',
        '/autofs/user1:/mnt/vol3:rw,shared',
    ])
)

Networking

You can specify networks to connect the container to by using the networking_config parameter. At the time of creation, you can only connect a container to a single networking, but you can create more connections by using connect_container_to_network().

For example:

networking_config = client.api.create_networking_config({
    'network1': client.api.create_endpoint_config(
        ipv4_address='172.28.0.124',
        aliases=['foo', 'bar'],
        links=['container2']
    )
})

ctnr = client.api.create_container(
    img, command, networking_config=networking_config
)
Parameters:
  • image (str) – The image to run

  • command (str or list) – The command to be run in the container

  • hostname (str) – Optional hostname for the container

  • user (str or int) – Username or UID

  • detach (bool) – Detached mode: run container in the background and return container ID

  • stdin_open (bool) – Keep STDIN open even if not attached

  • tty (bool) – Allocate a pseudo-TTY

  • ports (list of ints) – A list of port numbers

  • environment (dict or list) – A dictionary or a list of strings in the following format ["PASSWORD=xxx"] or {"PASSWORD": "xxx"}.

  • volumes (str or list) – List of paths inside the container to use as volumes.

  • network_disabled (bool) – Disable networking

  • name (str) – A name for the container

  • entrypoint (str or list) – An entrypoint

  • working_dir (str) – Path to the working directory

  • domainname (str) – The domain name to use for the container

  • host_config (dict) – A dictionary created with create_host_config().

  • mac_address (str) – The Mac Address to assign the container

  • labels (dict or list) – A dictionary of name-value labels (e.g. {"label1": "value1", "label2": "value2"}) or a list of names of labels to set with empty values (e.g. ["label1", "label2"])

  • stop_signal (str) – The stop signal to use to stop the container (e.g. SIGINT).

  • stop_timeout (int) – Timeout to stop the container, in seconds. Default: 10

  • networking_config (dict) – A networking configuration generated by create_networking_config().

  • runtime (str) – Runtime to use with this container.

  • healthcheck (dict) – Specify a test to perform to check that the container is healthy.

  • use_config_proxy (bool) – If True, and if the docker client configuration file (~/.docker/config.json by default) contains a proxy configuration, the corresponding environment variables will be set in the container being created.

  • platform (str) – Platform in the format os[/arch[/variant]].

Returns:

A dictionary with an image ‘Id’ key and a ‘Warnings’ key.

Raises:
  • docker.errors.ImageNotFound – If the specified image does not exist.

  • docker.errors.APIError – If the server returns an error.

create_container_config(*args, **kwargs)
create_container_from_config(config, name=None, platform=None)
create_endpoint_config(*args, **kwargs)

Create an endpoint config dictionary to be used with create_networking_config().

Parameters:
  • aliases (list) – A list of aliases for this endpoint. Names in that list can be used within the network to reach the container. Defaults to None.

  • links (dict) – Mapping of links for this endpoint using the {'container': 'alias'} format. The alias is optional. Containers declared in this dict will be linked to this container using the provided alias. Defaults to None.

  • ipv4_address (str) – The IP address of this container on the network, using the IPv4 protocol. Defaults to None.

  • ipv6_address (str) – The IP address of this container on the network, using the IPv6 protocol. Defaults to None.

  • link_local_ips (list) – A list of link-local (IPv4/IPv6) addresses.

  • driver_opt (dict) – A dictionary of options to provide to the network driver. Defaults to None.

Returns:

(dict) An endpoint config.

Example

>>> endpoint_config = client.api.create_endpoint_config(
    aliases=['web', 'app'],
    links={'app_db': 'db', 'another': None},
    ipv4_address='132.65.0.123'
)
create_host_config(*args, **kwargs)

Create a dictionary for the host_config argument to create_container().

Parameters:
  • auto_remove (bool) – enable auto-removal of the container on daemon side when the container’s process exits.

  • binds (dict) – Volumes to bind. See create_container() for more information.

  • blkio_weight_device – Block IO weight (relative device weight) in the form of: [{"Path": "device_path", "Weight": weight}].

  • blkio_weight – Block IO weight (relative weight), accepts a weight value between 10 and 1000.

  • cap_add (list of str) – Add kernel capabilities. For example, ["SYS_ADMIN", "MKNOD"].

  • cap_drop (list of str) – Drop kernel capabilities.

  • cpu_period (int) – The length of a CPU period in microseconds.

  • cpu_quota (int) – Microseconds of CPU time that the container can get in a CPU period.

  • cpu_shares (int) – CPU shares (relative weight).

  • cpuset_cpus (str) – CPUs in which to allow execution (0-3, 0,1).

  • cpuset_mems (str) – Memory nodes (MEMs) in which to allow execution (0-3, 0,1). Only effective on NUMA systems.

  • device_cgroup_rules (list) – A list of cgroup rules to apply to the container.

  • device_read_bps – Limit read rate (bytes per second) from a device in the form of: [{“Path”: “device_path”, “Rate”: rate}]

  • device_read_iops – Limit read rate (IO per second) from a device.

  • device_write_bps – Limit write rate (bytes per second) from a device.

  • device_write_iops – Limit write rate (IO per second) from a device.

  • devices (list) –

    Expose host devices to the container, as a list of strings in the form <path_on_host>:<path_in_container>:<cgroup_permissions>.

    For example, /dev/sda:/dev/xvda:rwm allows the container to have read-write access to the host’s /dev/sda via a node named /dev/xvda inside the container.

  • device_requests (list) – Expose host resources such as GPUs to the container, as a list of docker.types.DeviceRequest instances.

  • dns (list) – Set custom DNS servers.

  • dns_opt (list) – Additional options to be added to the container’s resolv.conf file

  • dns_search (list) – DNS search domains.

  • extra_hosts (dict) – Additional hostnames to resolve inside the container, as a mapping of hostname to IP address.

  • group_add (list) – List of additional group names and/or IDs that the container process will run as.

  • init (bool) – Run an init inside the container that forwards signals and reaps processes

  • ipc_mode (str) – Set the IPC mode for the container.

  • isolation (str) – Isolation technology to use. Default: None.

  • links (dict) – Mapping of links using the {'container': 'alias'} format. The alias is optional. Containers declared in this dict will be linked to the new container using the provided alias. Default: None.

  • log_config (LogConfig) – Logging configuration

  • lxc_conf (dict) – LXC config.

  • mem_limit (float or str) – Memory limit. Accepts float values (which represent the memory limit of the created container in bytes) or a string with a units identification char (100000b, 1000k, 128m, 1g). If a string is specified without a units character, bytes are assumed as an

  • mem_reservation (float or str) – Memory soft limit.

  • mem_swappiness (int) – Tune a container’s memory swappiness behavior. Accepts number between 0 and 100.

  • memswap_limit (str or int) – Maximum amount of memory + swap a container is allowed to consume.

  • mounts (list) – Specification for mounts to be added to the container. More powerful alternative to binds. Each item in the list is expected to be a docker.types.Mount object.

  • network_mode (str) –

    One of:

    • bridge Create a new network stack for the container on the bridge network.

    • none No networking for this container.

    • container:<name|id> Reuse another container’s network stack.

    • host Use the host network stack. This mode is incompatible with port_bindings.

  • oom_kill_disable (bool) – Whether to disable OOM killer.

  • oom_score_adj (int) – An integer value containing the score given to the container in order to tune OOM killer preferences.

  • pid_mode (str) – If set to host, use the host PID namespace inside the container.

  • pids_limit (int) – Tune a container’s pids limit. Set -1 for unlimited.

  • port_bindings (dict) – See create_container() for more information. Imcompatible with host in network_mode.

  • privileged (bool) – Give extended privileges to this container.

  • publish_all_ports (bool) – Publish all ports to the host.

  • read_only (bool) – Mount the container’s root filesystem as read only.

  • restart_policy (dict) –

    Restart the container when it exits. Configured as a dictionary with keys:

    • Name One of on-failure, or always.

    • MaximumRetryCount Number of times to restart the container on failure.

  • security_opt (list) – A list of string values to customize labels for MLS systems, such as SELinux.

  • shm_size (str or int) – Size of /dev/shm (e.g. 1G).

  • storage_opt (dict) – Storage driver options per container as a key-value mapping.

  • sysctls (dict) – Kernel parameters to set in the container.

  • tmpfs (dict) –

    Temporary filesystems to mount, as a dictionary mapping a path inside the container to options for that path.

    For example:

    {
        '/mnt/vol2': '',
        '/mnt/vol1': 'size=3G,uid=1000'
    }
    

  • ulimits (list) – Ulimits to set inside the container, as a list of docker.types.Ulimit instances.

  • userns_mode (str) – Sets the user namespace mode for the container when user namespace remapping option is enabled. Supported values are: host

  • uts_mode (str) – Sets the UTS namespace mode for the container. Supported values are: host

  • volumes_from (list) – List of container names or IDs to get volumes from.

  • runtime (str) – Runtime to use with this container.

Returns:

(dict) A dictionary which can be passed to the host_config argument to create_container().

Example

>>> client.api.create_host_config(
...     privileged=True,
...     cap_drop=['MKNOD'],
...     volumes_from=['nostalgic_newton'],
... )
{'CapDrop': ['MKNOD'], 'LxcConf': None, 'Privileged': True,
'VolumesFrom': ['nostalgic_newton'], 'PublishAllPorts': False}
create_networking_config(*args, **kwargs)

Create a networking config dictionary to be used as the networking_config parameter in create_container().

Parameters:

endpoints_config (dict) – A dictionary mapping network names to endpoint configurations generated by create_endpoint_config().

Returns:

(dict) A networking config.

Example

>>> client.api.create_network('network1')
>>> networking_config = client.api.create_networking_config({
    'network1': client.api.create_endpoint_config()
})
>>> container = client.api.create_container(
    img, command, networking_config=networking_config
)
diff(container)

Inspect changes on a container’s filesystem.

Parameters:

container (str) – The container to diff

Returns:

(list) A list of dictionaries containing the attributes Path

and Kind.

Raises:

docker.errors.APIError – If the server returns an error.

export(container, chunk_size=2097152)

Export the contents of a filesystem as a tar archive.

Parameters:
  • container (str) – The container to export

  • chunk_size (int) – The number of bytes returned by each iteration of the generator. If None, data will be streamed as it is received. Default: 2 MB

Returns:

The archived filesystem data stream

Return type:

(generator)

Raises:

docker.errors.APIError – If the server returns an error.

get_archive(container, path, chunk_size=2097152, encode_stream=False)

Retrieve a file or folder from a container in the form of a tar archive.

Parameters:
  • container (str) – The container where the file is located

  • path (str) – Path to the file or folder to retrieve

  • chunk_size (int) – The number of bytes returned by each iteration of the generator. If None, data will be streamed as it is received. Default: 2 MB

  • encode_stream (bool) – Determines if data should be encoded (gzip-compressed) during transmission. Default: False

Returns:

First element is a raw tar data stream. Second element is a dict containing stat information on the specified path.

Return type:

(tuple)

Raises:

docker.errors.APIError – If the server returns an error.

Example

>>> c = docker.APIClient()
>>> f = open('./sh_bin.tar', 'wb')
>>> bits, stat = c.api.get_archive(container, '/bin/sh')
>>> print(stat)
{'name': 'sh', 'size': 1075464, 'mode': 493,
 'mtime': '2018-10-01T15:37:48-07:00', 'linkTarget': ''}
>>> for chunk in bits:
...    f.write(chunk)
>>> f.close()
inspect_container(container)

Identical to the docker inspect command, but only for containers.

Parameters:

container (str) – The container to inspect

Returns:

Similar to the output of docker inspect, but as a single dict

Return type:

(dict)

Raises:

docker.errors.APIError – If the server returns an error.

kill(container, signal=None)

Kill a container or send a signal to a container.

Parameters:
  • container (str) – The container to kill

  • signal (str or int) – The signal to send. Defaults to SIGKILL

Raises:

docker.errors.APIError – If the server returns an error.

logs(container, stdout=True, stderr=True, stream=False, timestamps=False, tail='all', since=None, follow=None, until=None)

Get logs from a container. Similar to the docker logs command.

The stream parameter makes the logs function return a blocking generator you can iterate over to retrieve log output as it happens.

Parameters:
  • container (str) – The container to get logs from

  • stdout (bool) – Get STDOUT. Default True

  • stderr (bool) – Get STDERR. Default True

  • stream (bool) – Stream the response. Default False

  • timestamps (bool) – Show timestamps. Default False

  • tail (str or int) – Output specified number of lines at the end of logs. Either an integer of number of lines or the string all. Default all

  • since (datetime, int, or float) – Show logs since a given datetime, integer epoch (in seconds) or float (in fractional seconds)

  • follow (bool) – Follow log output. Default False

  • until (datetime, int, or float) – Show logs that occurred before the given datetime, integer epoch (in seconds), or float (in fractional seconds)

Returns:

(generator or str)

Raises:

docker.errors.APIError – If the server returns an error.

pause(container)

Pauses all processes within a container.

Parameters:

container (str) – The container to pause

Raises:

docker.errors.APIError – If the server returns an error.

port(container, private_port)

Lookup the public-facing port that is NAT-ed to private_port. Identical to the docker port command.

Parameters:
  • container (str) – The container to look up

  • private_port (int) – The private port to inspect

Returns:

The mapping for the host ports

Return type:

(list of dict)

Raises:

docker.errors.APIError – If the server returns an error.

Example

$ docker run -d -p 80:80 ubuntu:14.04 /bin/sleep 30
7174d6347063a83f412fad6124c99cffd25ffe1a0807eb4b7f9cec76ac8cb43b
>>> client.api.port('7174d6347063', 80)
[{'HostIp': '0.0.0.0', 'HostPort': '80'}]
prune_containers(filters=None)

Delete stopped containers

Parameters:

filters (dict) – Filters to process on the prune list.

Returns:

A dict containing a list of deleted container IDs and

the amount of disk space reclaimed in bytes.

Return type:

(dict)

Raises:

docker.errors.APIError – If the server returns an error.

put_archive(container, path, data)

Insert a file or folder in an existing container using a tar archive as source.

Parameters:
  • container (str) – The container where the file(s) will be extracted

  • path (str) – Path inside the container where the file(s) will be extracted. Must exist.

  • data (bytes or stream) – tar data to be extracted

Returns:

True if the call succeeds.

Return type:

(bool)

Raises:

docker.errors.APIError – If the server returns an error.

remove_container(container, v=False, link=False, force=False)

Remove a container. Similar to the docker rm command.

Parameters:
  • container (str) – The container to remove

  • v (bool) – Remove the volumes associated with the container

  • link (bool) – Remove the specified link and not the underlying container

  • force (bool) – Force the removal of a running container (uses SIGKILL)

Raises:

docker.errors.APIError – If the server returns an error.

rename(container, name)

Rename a container. Similar to the docker rename command.

Parameters:
  • container (str) – ID of the container to rename

  • name (str) – New name for the container

Raises:

docker.errors.APIError – If the server returns an error.

resize(container, height, width)

Resize the tty session.

Parameters:
  • container (str or dict) – The container to resize

  • height (int) – Height of tty session

  • width (int) – Width of tty session

Raises:

docker.errors.APIError – If the server returns an error.

restart(container, timeout=10)

Restart a container. Similar to the docker restart command.

Parameters:
  • container (str or dict) – The container to restart. If a dict, the Id key is used.

  • timeout (int) – Number of seconds to try to stop for before killing the container. Once killed it will then be restarted. Default is 10 seconds.

Raises:

docker.errors.APIError – If the server returns an error.

start(container, *args, **kwargs)

Start a container. Similar to the docker start command, but doesn’t support attach options.

Deprecation warning: Passing configuration options in start is no longer supported. Users are expected to provide host config options in the host_config parameter of create_container().

Parameters:

container (str) – The container to start

Raises:
  • docker.errors.APIError – If the server returns an error.

  • docker.errors.DeprecatedMethod – If any argument besides container are provided.

Example

>>> container = client.api.create_container(
...     image='busybox:latest',
...     command='/bin/sleep 30')
>>> client.api.start(container=container.get('Id'))
stats(container, decode=None, stream=True, one_shot=None)

Stream statistics for a specific container. Similar to the docker stats command.

Parameters:
  • container (str) – The container to stream statistics from

  • decode (bool) – If set to true, stream will be decoded into dicts on the fly. Only applicable if stream is True. False by default.

  • stream (bool) – If set to false, only the current stats will be returned instead of a stream. True by default.

  • one_shot (bool) – If set to true, Only get a single stat instead of waiting for 2 cycles. Must be used with stream=false. False by default.

Raises:

docker.errors.APIError – If the server returns an error.

stop(container, timeout=None)

Stops a container. Similar to the docker stop command.

Parameters:
  • container (str) – The container to stop

  • timeout (int) – Timeout in seconds to wait for the container to stop before sending a SIGKILL. If None, then the StopTimeout value of the container will be used. Default: None

Raises:

docker.errors.APIError – If the server returns an error.

top(container, ps_args=None)

Display the running processes of a container.

Parameters:
  • container (str) – The container to inspect

  • ps_args (str) – An optional arguments passed to ps (e.g. aux)

Returns:

The output of the top

Return type:

(str)

Raises:

docker.errors.APIError – If the server returns an error.

unpause(container)

Unpause all processes within a container.

Parameters:

container (str) – The container to unpause

update_container(container, blkio_weight=None, cpu_period=None, cpu_quota=None, cpu_shares=None, cpuset_cpus=None, cpuset_mems=None, mem_limit=None, mem_reservation=None, memswap_limit=None, kernel_memory=None, restart_policy=None)

Update resource configs of one or more containers.

Parameters:
  • container (str) – The container to inspect

  • blkio_weight (int) – Block IO (relative weight), between 10 and 1000

  • cpu_period (int) – Limit CPU CFS (Completely Fair Scheduler) period

  • cpu_quota (int) – Limit CPU CFS (Completely Fair Scheduler) quota

  • cpu_shares (int) – CPU shares (relative weight)

  • cpuset_cpus (str) – CPUs in which to allow execution

  • cpuset_mems (str) – MEMs in which to allow execution

  • mem_limit (float or str) – Memory limit

  • mem_reservation (float or str) – Memory soft limit

  • memswap_limit (int or str) – Total memory (memory + swap), -1 to disable swap

  • kernel_memory (int or str) – Kernel memory limit

  • restart_policy (dict) – Restart policy dictionary

Returns:

Dictionary containing a Warnings key.

Return type:

(dict)

Raises:

docker.errors.APIError – If the server returns an error.

wait(container, timeout=None, condition=None)

Block until a container stops, then return its exit code. Similar to the docker wait command.

Parameters:
  • container (str or dict) – The container to wait on. If a dict, the Id key is used.

  • timeout (int) – Request timeout

  • condition (str) – Wait until a container state reaches the given condition, either not-running (default), next-exit, or removed

Returns:

The API’s response as a Python dictionary, including

the container’s exit code under the StatusCode attribute.

Return type:

(dict)

Raises:
  • requests.exceptions.ReadTimeout – If the timeout is exceeded.

  • docker.errors.APIError – If the server returns an error.

Images

class ImageApiMixin
get_image(image, chunk_size=2097152)

Get a tarball of an image. Similar to the docker save command.

Parameters:
  • image (str) – Image name to get

  • chunk_size (int) – The number of bytes returned by each iteration of the generator. If None, data will be streamed as it is received. Default: 2 MB

Returns:

A stream of raw archive data.

Return type:

(generator)

Raises:

docker.errors.APIError – If the server returns an error.

Example

>>> image = client.api.get_image("busybox:latest")
>>> f = open('/tmp/busybox-latest.tar', 'wb')
>>> for chunk in image:
>>>   f.write(chunk)
>>> f.close()
history(image)

Show the history of an image.

Parameters:

image (str) – The image to show history for

Returns:

The history of the image

Return type:

(str)

Raises:

docker.errors.APIError – If the server returns an error.

images(name=None, quiet=False, all=False, filters=None)

List images. Similar to the docker images command.

Parameters:
  • name (str) – Only show images belonging to the repository name

  • quiet (bool) – Only return numeric IDs as a list.

  • all (bool) – Show intermediate image layers. By default, these are filtered out.

  • filters (dict) –

    Filters to be processed on the image list. Available filters: - dangling (bool) - label (str|list): format either "key", "key=value"

    or a list of such.

Returns:

A list if quiet=True, otherwise a dict.

Return type:

(dict or list)

Raises:

docker.errors.APIError – If the server returns an error.

import_image(src=None, repository=None, tag=None, image=None, changes=None, stream_src=False)

Import an image. Similar to the docker import command.

If src is a string or unicode string, it will first be treated as a path to a tarball on the local system. If there is an error reading from that file, src will be treated as a URL instead to fetch the image from. You can also pass an open file handle as src, in which case the data will be read from that file.

If src is unset but image is set, the image parameter will be taken as the name of an existing image to import from.

Parameters:
  • src (str or file) – Path to tarfile, URL, or file-like object

  • repository (str) – The repository to create

  • tag (str) – The tag to apply

  • image (str) – Use another image like the FROM Dockerfile parameter

import_image_from_data(data, repository=None, tag=None, changes=None)

Like import_image(), but allows importing in-memory bytes data.

Parameters:
  • data (bytes collection) – Bytes collection containing valid tar data

  • repository (str) – The repository to create

  • tag (str) – The tag to apply

import_image_from_file(filename, repository=None, tag=None, changes=None)

Like import_image(), but only supports importing from a tar file on disk.

Parameters:
  • filename (str) – Full path to a tar file.

  • repository (str) – The repository to create

  • tag (str) – The tag to apply

Raises:

IOError – File does not exist.

import_image_from_image(image, repository=None, tag=None, changes=None)

Like import_image(), but only supports importing from another image, like the FROM Dockerfile parameter.

Parameters:
  • image (str) – Image name to import from

  • repository (str) – The repository to create

  • tag (str) – The tag to apply

import_image_from_stream(stream, repository=None, tag=None, changes=None)
import_image_from_url(url, repository=None, tag=None, changes=None)

Like import_image(), but only supports importing from a URL.

Parameters:
  • url (str) – A URL pointing to a tar file.

  • repository (str) – The repository to create

  • tag (str) – The tag to apply

inspect_distribution(image, auth_config=None)

Get image digest and platform information by contacting the registry.

Parameters:
  • image (str) – The image name to inspect

  • auth_config (dict) – Override the credentials that are found in the config for this request. auth_config should contain the username and password keys to be valid.

Returns:

A dict containing distribution data

Return type:

(dict)

Raises:

docker.errors.APIError – If the server returns an error.

inspect_image(image)

Get detailed information about an image. Similar to the docker inspect command, but only for images.

Parameters:

image (str) – The image to inspect

Returns:

Similar to the output of docker inspect, but as a

Return type:

(dict)

single dict

Raises:

docker.errors.APIError – If the server returns an error.

load_image(data, quiet=None)

Load an image that was previously saved using get_image() (or docker save). Similar to docker load.

Parameters:
  • data (binary) – Image data to be loaded.

  • quiet (boolean) – Suppress progress details in response.

Returns:

Progress output as JSON objects. Only available for

API version >= 1.23

Return type:

(generator)

Raises:

docker.errors.APIError – If the server returns an error.

prune_images(filters=None)

Delete unused images

Parameters:

filters (dict) – Filters to process on the prune list. Available filters: - dangling (bool): When set to true (or 1), prune only unused and untagged images.

Returns:

A dict containing a list of deleted image IDs and

the amount of disk space reclaimed in bytes.

Return type:

(dict)

Raises:

docker.errors.APIError – If the server returns an error.

pull(repository, tag=None, stream=False, auth_config=None, decode=False, platform=None, all_tags=False)

Pulls an image. Similar to the docker pull command.

Parameters:
  • repository (str) – The repository to pull

  • tag (str) – The tag to pull. If tag is None or empty, it is set to latest.

  • stream (bool) – Stream the output as a generator. Make sure to consume the generator, otherwise pull might get cancelled.

  • auth_config (dict) – Override the credentials that are found in the config for this request. auth_config should contain the username and password keys to be valid.

  • decode (bool) – Decode the JSON data from the server into dicts. Only applies with stream=True

  • platform (str) – Platform in the format os[/arch[/variant]]

  • all_tags (bool) – Pull all image tags, the tag parameter is ignored.

Returns:

The output

Return type:

(generator or str)

Raises:

docker.errors.APIError – If the server returns an error.

Example

>>> resp = client.api.pull('busybox', stream=True, decode=True)
... for line in resp:
...     print(json.dumps(line, indent=4))
{
    "status": "Pulling image (latest) from busybox",
    "progressDetail": {},
    "id": "e72ac664f4f0"
}
{
    "status": "Pulling image (latest) from busybox, endpoint: ...",
    "progressDetail": {},
    "id": "e72ac664f4f0"
}
push(repository, tag=None, stream=False, auth_config=None, decode=False)

Push an image or a repository to the registry. Similar to the docker push command.

Parameters:
  • repository (str) – The repository to push to

  • tag (str) – An optional tag to push

  • stream (bool) – Stream the output as a blocking generator

  • auth_config (dict) – Override the credentials that are found in the config for this request. auth_config should contain the username and password keys to be valid.

  • decode (bool) – Decode the JSON data from the server into dicts. Only applies with stream=True

Returns:

The output from the server.

Return type:

(generator or str)

Raises:

docker.errors.APIError – If the server returns an error.

Example

>>> resp = client.api.push(
...     'yourname/app',
...     stream=True,
...     decode=True,
... )
... for line in resp:
...   print(line)
{'status': 'Pushing repository yourname/app (1 tags)'}
{'status': 'Pushing','progressDetail': {}, 'id': '511136ea3c5a'}
{'status': 'Image already pushed, skipping', 'progressDetail':{},
 'id': '511136ea3c5a'}
...
remove_image(image, force=False, noprune=False)

Remove an image. Similar to the docker rmi command.

Parameters:
  • image (str) – The image to remove

  • force (bool) – Force removal of the image

  • noprune (bool) – Do not delete untagged parents

search(term, limit=None)

Search for images on Docker Hub. Similar to the docker search command.

Parameters:
  • term (str) – A term to search for.

  • limit (int) – The maximum number of results to return.

Returns:

The response of the search.

Return type:

(list of dicts)

Raises:

docker.errors.APIError – If the server returns an error.

tag(image, repository, tag=None, force=False)

Tag an image into a repository. Similar to the docker tag command.

Parameters:
  • image (str) – The image to tag

  • repository (str) – The repository to set for the tag

  • tag (str) – The tag name

  • force (bool) – Force

Returns:

True if successful

Return type:

(bool)

Raises:

docker.errors.APIError – If the server returns an error.

Example

>>> client.api.tag('ubuntu', 'localhost:5000/ubuntu', 'latest',
               force=True)

Building images

class BuildApiMixin
build(path=None, tag=None, quiet=False, fileobj=None, nocache=False, rm=False, timeout=None, custom_context=False, encoding=None, pull=False, forcerm=False, dockerfile=None, container_limits=None, decode=False, buildargs=None, gzip=False, shmsize=None, labels=None, cache_from=None, target=None, network_mode=None, squash=None, extra_hosts=None, platform=None, isolation=None, use_config_proxy=True)

Similar to the docker build command. Either path or fileobj needs to be set. path can be a local path (to a directory containing a Dockerfile) or a remote URL. fileobj must be a readable file-like object to a Dockerfile.

If you have a tar file for the Docker build context (including a Dockerfile) already, pass a readable file-like object to fileobj and also pass custom_context=True. If the stream is compressed also, set encoding to the correct value (e.g gzip).

Example

>>> from io import BytesIO
>>> from docker import APIClient
>>> dockerfile = '''
... # Shared Volume
... FROM busybox:buildroot-2014.02
... VOLUME /data
... CMD ["/bin/sh"]
... '''
>>> f = BytesIO(dockerfile.encode('utf-8'))
>>> cli = APIClient(base_url='tcp://127.0.0.1:2375')
>>> response = [line for line in cli.build(
...     fileobj=f, rm=True, tag='yourname/volume'
... )]
>>> response
['{"stream":" ---\u003e a9eb17255234\n"}',
 '{"stream":"Step 1 : VOLUME /data\n"}',
 '{"stream":" ---\u003e Running in abdc1e6896c6\n"}',
 '{"stream":" ---\u003e 713bca62012e\n"}',
 '{"stream":"Removing intermediate container abdc1e6896c6\n"}',
 '{"stream":"Step 2 : CMD [\"/bin/sh\"]\n"}',
 '{"stream":" ---\u003e Running in dba30f2a1a7e\n"}',
 '{"stream":" ---\u003e 032b8b2855fc\n"}',
 '{"stream":"Removing intermediate container dba30f2a1a7e\n"}',
 '{"stream":"Successfully built 032b8b2855fc\n"}']
Parameters:
  • path (str) – Path to the directory containing the Dockerfile

  • fileobj – A file object to use as the Dockerfile. (Or a file-like object)

  • tag (str) – A tag to add to the final image

  • quiet (bool) – Whether to return the status

  • nocache (bool) – Don’t use the cache when set to True

  • rm (bool) – Remove intermediate containers. The docker build command now defaults to --rm=true, but we have kept the old default of False to preserve backward compatibility

  • timeout (int) – HTTP timeout

  • custom_context (bool) – Optional if using fileobj

  • encoding (str) – The encoding for a stream. Set to gzip for compressing

  • pull (bool) – Downloads any updates to the FROM image in Dockerfiles

  • forcerm (bool) – Always remove intermediate containers, even after unsuccessful builds

  • dockerfile (str) – path within the build context to the Dockerfile

  • gzip (bool) – If set to True, gzip compression/encoding is used

  • buildargs (dict) – A dictionary of build arguments

  • container_limits (dict) –

    A dictionary of limits applied to each container created by the build process. Valid keys:

    • memory (int): set memory limit for build

    • memswap (int): Total memory (memory + swap), -1 to disable

      swap

    • cpushares (int): CPU shares (relative weight)

    • cpusetcpus (str): CPUs in which to allow execution, e.g.,

      "0-3", "0,1"

  • decode (bool) – If set to True, the returned stream will be decoded into dicts on the fly. Default False

  • shmsize (int) – Size of /dev/shm in bytes. The size must be greater than 0. If omitted the system uses 64MB

  • labels (dict) – A dictionary of labels to set on the image

  • cache_from (list) – A list of images used for build cache resolution

  • target (str) – Name of the build-stage to build in a multi-stage Dockerfile

  • network_mode (str) – networking mode for the run commands during build

  • squash (bool) – Squash the resulting images layers into a single layer.

  • extra_hosts (dict) – Extra hosts to add to /etc/hosts in building containers, as a mapping of hostname to IP address.

  • platform (str) – Platform in the format os[/arch[/variant]]

  • isolation (str) – Isolation technology used during build. Default: None.

  • use_config_proxy (bool) – If True, and if the docker client configuration file (~/.docker/config.json by default) contains a proxy configuration, the corresponding environment variables will be set in the container being built.

Returns:

A generator for the build output.

Raises:
  • docker.errors.APIError – If the server returns an error.

  • TypeError – If neither path nor fileobj is specified.

prune_builds(filters=None, keep_storage=None, all=None)

Delete the builder cache

Parameters:
  • filters (dict) – Filters to process on the prune list. Needs Docker API v1.39+ Available filters: - dangling (bool): When set to true (or 1), prune only unused and untagged images. - until (str): Can be Unix timestamps, date formatted timestamps, or Go duration strings (e.g. 10m, 1h30m) computed relative to the daemon’s local time.

  • keep_storage (int) – Amount of disk space in bytes to keep for cache. Needs Docker API v1.39+

  • all (bool) – Remove all types of build cache. Needs Docker API v1.39+

Returns:

A dictionary containing information about the operation’s

result. The SpaceReclaimed key indicates the amount of bytes of disk space reclaimed.

Return type:

(dict)

Raises:

docker.errors.APIError – If the server returns an error.

Networks

class NetworkApiMixin
connect_container_to_network(container, net_id, ipv4_address=None, ipv6_address=None, aliases=None, links=None, link_local_ips=None, driver_opt=None, mac_address=None)

Connect a container to a network.

Parameters:
  • container (str) – container-id/name to be connected to the network

  • net_id (str) – network id

  • aliases (list) – A list of aliases for this endpoint. Names in that list can be used within the network to reach the container. Defaults to None.

  • links (list) – A list of links for this endpoint. Containers declared in this list will be linked to this container. Defaults to None.

  • ipv4_address (str) – The IP address of this container on the network, using the IPv4 protocol. Defaults to None.

  • ipv6_address (str) – The IP address of this container on the network, using the IPv6 protocol. Defaults to None.

  • link_local_ips (list) – A list of link-local (IPv4/IPv6) addresses.

  • mac_address (str) – The MAC address of this container on the network. Defaults to None.

create_network(name, driver=None, options=None, ipam=None, check_duplicate=None, internal=False, labels=None, enable_ipv6=False, attachable=None, scope=None, ingress=None)

Create a network. Similar to the docker network create.

Parameters:
  • name (str) – Name of the network

  • driver (str) – Name of the driver used to create the network

  • options (dict) – Driver options as a key-value dictionary

  • ipam (IPAMConfig) – Optional custom IP scheme for the network.

  • check_duplicate (bool) – Request daemon to check for networks with same name. Default: None.

  • internal (bool) – Restrict external access to the network. Default False.

  • labels (dict) – Map of labels to set on the network. Default None.

  • enable_ipv6 (bool) – Enable IPv6 on the network. Default False.

  • attachable (bool) – If enabled, and the network is in the global scope, non-service containers on worker nodes will be able to connect to the network.

  • scope (str) – Specify the network’s scope (local, global or swarm)

  • ingress (bool) – If set, create an ingress network which provides the routing-mesh in swarm mode.

Returns:

The created network reference object

Return type:

(dict)

Raises:

docker.errors.APIError – If the server returns an error.

Example

A network using the bridge driver:

>>> client.api.create_network("network1", driver="bridge")

You can also create more advanced networks with custom IPAM configurations. For example, setting the subnet to 192.168.52.0/24 and gateway address to 192.168.52.254.

>>> ipam_pool = docker.types.IPAMPool(
    subnet='192.168.52.0/24',
    gateway='192.168.52.254'
)
>>> ipam_config = docker.types.IPAMConfig(
    pool_configs=[ipam_pool]
)
>>> client.api.create_network("network1", driver="bridge",
                                 ipam=ipam_config)
disconnect_container_from_network(container, net_id, force=False)

Disconnect a container from a network.

Parameters:
  • container (str) – container ID or name to be disconnected from the network

  • net_id (str) – network ID

  • force (bool) – Force the container to disconnect from a network. Default: False

inspect_network(net_id, verbose=None, scope=None)

Get detailed information about a network.

Parameters:
  • net_id (str) – ID of network

  • verbose (bool) – Show the service details across the cluster in swarm mode.

  • scope (str) – Filter the network by scope (swarm, global or local).

networks(names=None, ids=None, filters=None)

List networks. Similar to the docker network ls command.

Parameters:
  • names (list) – List of names to filter by

  • ids (list) – List of ids to filter by

  • filters (dict) –

    Filters to be processed on the network list. Available filters: - driver=[<driver-name>] Matches a network’s driver. - label=[<key>], label=[<key>=<value>] or a list of

    such.

    • type=["custom"|"builtin"] Filters networks by type.

Returns:

List of network objects.

Return type:

(dict)

Raises:

docker.errors.APIError – If the server returns an error.

prune_networks(filters=None)

Delete unused networks

Parameters:

filters (dict) – Filters to process on the prune list.

Returns:

A dict containing a list of deleted network names and

the amount of disk space reclaimed in bytes.

Return type:

(dict)

Raises:

docker.errors.APIError – If the server returns an error.

remove_network(net_id)

Remove a network. Similar to the docker network rm command.

Parameters:

net_id (str) – The network’s id

Volumes

class VolumeApiMixin
create_volume(name=None, driver=None, driver_opts=None, labels=None)

Create and register a named volume

Parameters:
  • name (str) – Name of the volume

  • driver (str) – Name of the driver used to create the volume

  • driver_opts (dict) – Driver options as a key-value dictionary

  • labels (dict) – Labels to set on the volume

Returns:

The created volume reference object

Return type:

(dict)

Raises:

docker.errors.APIError – If the server returns an error.

Example

>>> volume = client.api.create_volume(
...     name='foobar',
...     driver='local',
...     driver_opts={'foo': 'bar', 'baz': 'false'},
...     labels={"key": "value"},
... )
... print(volume)
{u'Driver': u'local',
u'Labels': {u'key': u'value'},
u'Mountpoint': u'/var/lib/docker/volumes/foobar/_data',
u'Name': u'foobar',
u'Scope': u'local'}
inspect_volume(name)

Retrieve volume info by name.

Parameters:

name (str) – volume name

Returns:

Volume information dictionary

Return type:

(dict)

Raises:

docker.errors.APIError – If the server returns an error.

Example

>>> client.api.inspect_volume('foobar')
{u'Driver': u'local',
 u'Mountpoint': u'/var/lib/docker/volumes/foobar/_data',
 u'Name': u'foobar'}
prune_volumes(filters=None)

Delete unused volumes

Parameters:

filters (dict) – Filters to process on the prune list.

Returns:

A dict containing a list of deleted volume names and

the amount of disk space reclaimed in bytes.

Return type:

(dict)

Raises:

docker.errors.APIError – If the server returns an error.

remove_volume(name, force=False)

Remove a volume. Similar to the docker volume rm command.

Parameters:
  • name (str) – The volume’s name

  • force (bool) – Force removal of volumes that were already removed out of band by the volume driver plugin.

Raises:

docker.errors.APIError – If volume failed to remove.

volumes(filters=None)

List volumes currently registered by the docker daemon. Similar to the docker volume ls command.

Parameters:

filters (dict) – Server-side list filtering options.

Returns:

Dictionary with list of volume objects as value of the Volumes key.

Return type:

(dict)

Raises:

docker.errors.APIError – If the server returns an error.

Example

>>> client.api.volumes()
{u'Volumes': [{u'Driver': u'local',
   u'Mountpoint': u'/var/lib/docker/volumes/foobar/_data',
   u'Name': u'foobar'},
  {u'Driver': u'local',
   u'Mountpoint': u'/var/lib/docker/volumes/baz/_data',
   u'Name': u'baz'}]}

Executing commands in containers

class ExecApiMixin
exec_create(container, cmd, stdout=True, stderr=True, stdin=False, tty=False, privileged=False, user='', environment=None, workdir=None, detach_keys=None)

Sets up an exec instance in a running container.

Parameters:
  • container (str) – Target container where exec instance will be created

  • cmd (str or list) – Command to be executed

  • stdout (bool) – Attach to stdout. Default: True

  • stderr (bool) – Attach to stderr. Default: True

  • stdin (bool) – Attach to stdin. Default: False

  • tty (bool) – Allocate a pseudo-TTY. Default: False

  • privileged (bool) – Run as privileged.

  • user (str) – User to execute command as. Default: root

  • environment (dict or list) – A dictionary or a list of strings in the following format ["PASSWORD=xxx"] or {"PASSWORD": "xxx"}.

  • workdir (str) – Path to working directory for this exec session

  • detach_keys (str) – Override the key sequence for detaching a container. Format is a single character [a-Z] or ctrl-<value> where <value> is one of: a-z, @, ^, [, , or _. ~/.docker/config.json is used by default.

Returns:

A dictionary with an exec Id key.

Return type:

(dict)

Raises:

docker.errors.APIError – If the server returns an error.

exec_inspect(exec_id)

Return low-level information about an exec command.

Parameters:

exec_id (str) – ID of the exec instance

Returns:

Dictionary of values returned by the endpoint.

Return type:

(dict)

Raises:

docker.errors.APIError – If the server returns an error.

exec_resize(exec_id, height=None, width=None)

Resize the tty session used by the specified exec command.

Parameters:
  • exec_id (str) – ID of the exec instance

  • height (int) – Height of tty session

  • width (int) – Width of tty session

exec_start(exec_id, detach=False, tty=False, stream=False, socket=False, demux=False)

Start a previously set up exec instance.

Parameters:
  • exec_id (str) – ID of the exec instance

  • detach (bool) – If true, detach from the exec command. Default: False

  • tty (bool) – Allocate a pseudo-TTY. Default: False

  • stream (bool) – Return response data progressively as an iterator of strings, rather than a single string.

  • socket (bool) – Return the connection socket to allow custom read/write operations. Must be closed by the caller when done.

  • demux (bool) – Return stdout and stderr separately

Returns:

If stream=True, a generator yielding response chunks. If socket=True, a socket object for the connection. A string containing response data otherwise. If demux=True, a tuple with two elements of type byte: stdout and stderr.

Return type:

(generator or str or tuple)

Raises:

docker.errors.APIError – If the server returns an error.

Swarms

class SwarmApiMixin
create_swarm_spec(*args, **kwargs)

Create a docker.types.SwarmSpec instance that can be used as the swarm_spec argument in init_swarm().

Parameters:
  • task_history_retention_limit (int) – Maximum number of tasks history stored.

  • snapshot_interval (int) – Number of logs entries between snapshot.

  • keep_old_snapshots (int) – Number of snapshots to keep beyond the current snapshot.

  • log_entries_for_slow_followers (int) – Number of log entries to keep around to sync up slow followers after a snapshot is created.

  • heartbeat_tick (int) – Amount of ticks (in seconds) between each heartbeat.

  • election_tick (int) – Amount of ticks (in seconds) needed without a leader to trigger a new election.

  • dispatcher_heartbeat_period (int) – The delay for an agent to send a heartbeat to the dispatcher.

  • node_cert_expiry (int) – Automatic expiry for nodes certificates.

  • external_cas (list) – Configuration for forwarding signing requests to an external certificate authority. Use a list of docker.types.SwarmExternalCA.

  • name (string) – Swarm’s name

  • labels (dict) – User-defined key/value metadata.

  • signing_ca_cert (str) – The desired signing CA certificate for all swarm node TLS leaf certificates, in PEM format.

  • signing_ca_key (str) – The desired signing CA key for all swarm node TLS leaf certificates, in PEM format.

  • ca_force_rotate (int) – An integer whose purpose is to force swarm to generate a new signing CA certificate and key, if none have been specified.

  • autolock_managers (boolean) – If set, generate a key and use it to lock data stored on the managers.

  • log_driver (DriverConfig) – The default log driver to use for tasks created in the orchestrator.

Returns:

docker.types.SwarmSpec

Raises:

docker.errors.APIError – If the server returns an error.

Example

>>> spec = client.api.create_swarm_spec(
  snapshot_interval=5000, log_entries_for_slow_followers=1200
)
>>> client.api.init_swarm(
  advertise_addr='eth0', listen_addr='0.0.0.0:5000',
  force_new_cluster=False, swarm_spec=spec
)
get_unlock_key()

Get the unlock key for this Swarm manager.

Returns:

A dict containing an UnlockKey member

init_swarm(advertise_addr=None, listen_addr='0.0.0.0:2377', force_new_cluster=False, swarm_spec=None, default_addr_pool=None, subnet_size=None, data_path_addr=None, data_path_port=None)

Initialize a new Swarm using the current connected engine as the first node.

Parameters:
  • advertise_addr (string) – Externally reachable address advertised to other nodes. This can either be an address/port combination in the form 192.168.1.1:4567, or an interface followed by a port number, like eth0:4567. If the port number is omitted, the port number from the listen address is used. If advertise_addr is not specified, it will be automatically detected when possible. Default: None

  • listen_addr (string) – Listen address used for inter-manager communication, as well as determining the networking interface used for the VXLAN Tunnel Endpoint (VTEP). This can either be an address/port combination in the form 192.168.1.1:4567, or an interface followed by a port number, like eth0:4567. If the port number is omitted, the default swarm listening port is used. Default: ‘0.0.0.0:2377’

  • force_new_cluster (bool) – Force creating a new Swarm, even if already part of one. Default: False

  • swarm_spec (dict) – Configuration settings of the new Swarm. Use APIClient.create_swarm_spec to generate a valid configuration. Default: None

  • default_addr_pool (list of strings) – Default Address Pool specifies default subnet pools for global scope networks. Each pool should be specified as a CIDR block, like ‘10.0.0.0/8’. Default: None

  • subnet_size (int) – SubnetSize specifies the subnet size of the networks created from the default subnet pool. Default: None

  • data_path_addr (string) – Address or interface to use for data path traffic. For example, 192.168.1.1, or an interface, like eth0.

  • data_path_port (int) – Port number to use for data path traffic. Acceptable port range is 1024 to 49151. If set to None or 0, the default port 4789 will be used. Default: None

Returns:

The ID of the created node.

Return type:

(str)

Raises:

docker.errors.APIError – If the server returns an error.

inspect_node(node_id)

Retrieve low-level information about a swarm node

Parameters:

node_id (string) – ID of the node to be inspected.

Returns:

A dictionary containing data about this node.

Raises:

docker.errors.APIError – If the server returns an error.

inspect_swarm()

Retrieve low-level information about the current swarm.

Returns:

A dictionary containing data about the swarm.

Raises:

docker.errors.APIError – If the server returns an error.

join_swarm(remote_addrs, join_token, listen_addr='0.0.0.0:2377', advertise_addr=None, data_path_addr=None)

Make this Engine join a swarm that has already been created.

Parameters:
  • remote_addrs (list) – Addresses of one or more manager nodes already participating in the Swarm to join.

  • join_token (string) – Secret token for joining this Swarm.

  • listen_addr (string) – Listen address used for inter-manager communication if the node gets promoted to manager, as well as determining the networking interface used for the VXLAN Tunnel Endpoint (VTEP). Default: '0.0.0.0:2377

  • advertise_addr (string) – Externally reachable address advertised to other nodes. This can either be an address/port combination in the form 192.168.1.1:4567, or an interface followed by a port number, like eth0:4567. If the port number is omitted, the port number from the listen address is used. If AdvertiseAddr is not specified, it will be automatically detected when possible. Default: None

  • data_path_addr (string) – Address or interface to use for data path traffic. For example, 192.168.1.1, or an interface, like eth0.

Returns:

True if the request went through.

Raises:

docker.errors.APIError – If the server returns an error.

leave_swarm(force=False)

Leave a swarm.

Parameters:

force (bool) – Leave the swarm even if this node is a manager. Default: False

Returns:

True if the request went through.

Raises:

docker.errors.APIError – If the server returns an error.

nodes(filters=None)

List swarm nodes.

Parameters:

filters (dict) – Filters to process on the nodes list. Valid filters: id, name, membership and role. Default: None

Returns:

A list of dictionaries containing data about each swarm node.

Raises:

docker.errors.APIError – If the server returns an error.

remove_node(node_id, force=False)

Remove a node from the swarm.

Parameters:
  • node_id (string) – ID of the node to be removed.

  • force (bool) – Force remove an active node. Default: False

Raises:
  • docker.errors.NotFound – If the node referenced doesn’t exist in the swarm.

  • docker.errors.APIError – If the server returns an error.

Returns:

True if the request was successful.

unlock_swarm(key)

Unlock a locked swarm.

Parameters:

key (string) – The unlock key as provided by get_unlock_key()

Raises:
  • docker.errors.InvalidArgument – If the key argument is in an incompatible format

  • docker.errors.APIError – If the server returns an error.

Returns:

True if the request was successful.

Example

>>> key = client.api.get_unlock_key()
>>> client.unlock_swarm(key)
update_node(node_id, version, node_spec=None)

Update the node’s configuration

Parameters:
  • node_id (string) – ID of the node to be updated.

  • version (int) – The version number of the node object being updated. This is required to avoid conflicting writes.

  • node_spec (dict) – Configuration settings to update. Any values not provided will be removed. Default: None

Returns:

True if the request went through.

Raises:

docker.errors.APIError – If the server returns an error.

Example

>>> node_spec = {'Availability': 'active',
             'Name': 'node-name',
             'Role': 'manager',
             'Labels': {'foo': 'bar'}
            }
>>> client.api.update_node(node_id='24ifsmvkjbyhk', version=8,
    node_spec=node_spec)
update_swarm(version, swarm_spec=None, rotate_worker_token=False, rotate_manager_token=False, rotate_manager_unlock_key=False)

Update the Swarm’s configuration

Parameters:
  • version (int) – The version number of the swarm object being updated. This is required to avoid conflicting writes.

  • swarm_spec (dict) – Configuration settings to update. Use create_swarm_spec() to generate a valid configuration. Default: None.

  • rotate_worker_token (bool) – Rotate the worker join token. Default: False.

  • rotate_manager_token (bool) – Rotate the manager join token. Default: False.

  • rotate_manager_unlock_key (bool) – Rotate the manager unlock key. Default: False.

Returns:

True if the request went through.

Raises:

docker.errors.APIError – If the server returns an error.

Services

class ServiceApiMixin
create_service(task_template, name=None, labels=None, mode=None, update_config=None, networks=None, endpoint_config=None, endpoint_spec=None, rollback_config=None)

Create a service.

Parameters:
  • task_template (TaskTemplate) – Specification of the task to start as part of the new service.

  • name (string) – User-defined name for the service. Optional.

  • labels (dict) – A map of labels to associate with the service. Optional.

  • mode (ServiceMode) – Scheduling mode for the service (replicated or global). Defaults to replicated.

  • update_config (UpdateConfig) – Specification for the update strategy of the service. Default: None

  • rollback_config (RollbackConfig) – Specification for the rollback strategy of the service. Default: None

  • networks (list) – List of network names or IDs or NetworkAttachmentConfig to attach the service to. Default: None.

  • endpoint_spec (EndpointSpec) – Properties that can be configured to access and load balance a service. Default: None.

Returns:

A dictionary containing an ID key for the newly created service.

Raises:

docker.errors.APIError – If the server returns an error.

inspect_service(service, insert_defaults=None)

Return information about a service.

Parameters:
  • service (str) – Service name or ID.

  • insert_defaults (boolean) – If true, default values will be merged into the service inspect output.

Returns:

A dictionary of the server-side representation of the

service, including all relevant properties.

Return type:

(dict)

Raises:

docker.errors.APIError – If the server returns an error.

inspect_task(task)

Retrieve information about a task.

Parameters:

task (str) – Task ID

Returns:

Information about the task.

Return type:

(dict)

Raises:

docker.errors.APIError – If the server returns an error.

remove_service(service)

Stop and remove a service.

Parameters:

service (str) – Service name or ID

Returns:

True if successful.

Raises:

docker.errors.APIError – If the server returns an error.

service_logs(service, details=False, follow=False, stdout=False, stderr=False, since=0, timestamps=False, tail='all', is_tty=None)

Get log stream for a service. Note: This endpoint works only for services with the json-file or journald logging drivers.

Parameters:
  • service (str) – ID or name of the service

  • details (bool) – Show extra details provided to logs. Default: False

  • follow (bool) – Keep connection open to read logs as they are sent by the Engine. Default: False

  • stdout (bool) – Return logs from stdout. Default: False

  • stderr (bool) – Return logs from stderr. Default: False

  • since (int) – UNIX timestamp for the logs staring point. Default: 0

  • timestamps (bool) – Add timestamps to every log line.

  • tail (string or int) – Number of log lines to be returned, counting from the current end of the logs. Specify an integer or 'all' to output all log lines. Default: all

  • is_tty (bool) – Whether the service’s ContainerSpec enables the TTY option. If omitted, the method will query the Engine for the information, causing an additional roundtrip.

Returns (generator): Logs for the service.

services(filters=None, status=None)

List services.

Parameters:
  • filters (dict) – Filters to process on the nodes list. Valid filters: id, name , label and mode. Default: None.

  • status (bool) – Include the service task count of running and desired tasks. Default: None.

Returns:

A list of dictionaries containing data about each service.

Raises:

docker.errors.APIError – If the server returns an error.

tasks(filters=None)

Retrieve a list of tasks.

Parameters:

filters (dict) – A map of filters to process on the tasks list. Valid filters: id, name, service, node, label and desired-state.

Returns:

List of task dictionaries.

Return type:

(list)

Raises:

docker.errors.APIError – If the server returns an error.

update_service(service, version, task_template=None, name=None, labels=None, mode=None, update_config=None, networks=None, endpoint_config=None, endpoint_spec=None, fetch_current_spec=False, rollback_config=None)

Update a service.

Parameters:
  • service (string) – A service identifier (either its name or service ID).

  • version (int) – The version number of the service object being updated. This is required to avoid conflicting writes.

  • task_template (TaskTemplate) – Specification of the updated task to start as part of the service.

  • name (string) – New name for the service. Optional.

  • labels (dict) – A map of labels to associate with the service. Optional.

  • mode (ServiceMode) – Scheduling mode for the service (replicated or global). Defaults to replicated.

  • update_config (UpdateConfig) – Specification for the update strategy of the service. Default: None.

  • rollback_config (RollbackConfig) – Specification for the rollback strategy of the service. Default: None

  • networks (list) – List of network names or IDs or NetworkAttachmentConfig to attach the service to. Default: None.

  • endpoint_spec (EndpointSpec) – Properties that can be configured to access and load balance a service. Default: None.

  • fetch_current_spec (boolean) – Use the undefined settings from the current specification of the service. Default: False

Returns:

A dictionary containing a Warnings key.

Raises:

docker.errors.APIError – If the server returns an error.

Plugins

class PluginApiMixin
configure_plugin(name, options)

Configure a plugin.

Parameters:
  • name (string) – The name of the plugin. The :latest tag is optional, and is the default if omitted.

  • options (dict) – A key-value mapping of options

Returns:

True if successful

create_plugin(name, plugin_data_dir, gzip=False)

Create a new plugin.

Parameters:
  • name (string) – The name of the plugin. The :latest tag is optional, and is the default if omitted.

  • plugin_data_dir (string) – Path to the plugin data directory. Plugin data directory must contain the config.json manifest file and the rootfs directory.

  • gzip (bool) – Compress the context using gzip. Default: False

Returns:

True if successful

disable_plugin(name, force=False)

Disable an installed plugin.

Parameters:
  • name (string) – The name of the plugin. The :latest tag is optional, and is the default if omitted.

  • force (bool) – To enable the force query parameter.

Returns:

True if successful

enable_plugin(name, timeout=0)

Enable an installed plugin.

Parameters:
  • name (string) – The name of the plugin. The :latest tag is optional, and is the default if omitted.

  • timeout (int) – Operation timeout (in seconds). Default: 0

Returns:

True if successful

inspect_plugin(name)

Retrieve plugin metadata.

Parameters:

name (string) – The name of the plugin. The :latest tag is optional, and is the default if omitted.

Returns:

A dict containing plugin info

plugin_privileges(name)

Retrieve list of privileges to be granted to a plugin.

Parameters:

name (string) – Name of the remote plugin to examine. The :latest tag is optional, and is the default if omitted.

Returns:

A list of dictionaries representing the plugin’s permissions

plugins()

Retrieve a list of installed plugins.

Returns:

A list of dicts, one per plugin

pull_plugin(remote, privileges, name=None)

Pull and install a plugin. After the plugin is installed, it can be enabled using enable_plugin().

Parameters:
  • remote (string) – Remote reference for the plugin to install. The :latest tag is optional, and is the default if omitted.

  • privileges (list) – A list of privileges the user consents to grant to the plugin. Can be retrieved using plugin_privileges().

  • name (string) – Local name for the pulled plugin. The :latest tag is optional, and is the default if omitted.

Returns:

An iterable object streaming the decoded API logs

push_plugin(name)

Push a plugin to the registry.

Parameters:

name (string) – Name of the plugin to upload. The :latest tag is optional, and is the default if omitted.

Returns:

True if successful

remove_plugin(name, force=False)

Remove an installed plugin.

Parameters:
  • name (string) – Name of the plugin to remove. The :latest tag is optional, and is the default if omitted.

  • force (bool) – Disable the plugin before removing. This may result in issues if the plugin is in use by a container.

Returns:

True if successful

upgrade_plugin(name, remote, privileges)

Upgrade an installed plugin.

Parameters:
  • name (string) – Name of the plugin to upgrade. The :latest tag is optional and is the default if omitted.

  • remote (string) – Remote reference to upgrade to. The :latest tag is optional and is the default if omitted.

  • privileges (list) – A list of privileges the user consents to grant to the plugin. Can be retrieved using plugin_privileges().

Returns:

An iterable object streaming the decoded API logs

Secrets

class SecretApiMixin
create_secret(name, data, labels=None, driver=None)

Create a secret

Parameters:
  • name (string) – Name of the secret

  • data (bytes) – Secret data to be stored

  • labels (dict) – A mapping of labels to assign to the secret

  • driver (DriverConfig) – A custom driver configuration. If unspecified, the default internal driver will be used

Returns (dict): ID of the newly created secret

inspect_secret(id)

Retrieve secret metadata

Parameters:

id (string) – Full ID of the secret to inspect

Returns (dict): A dictionary of metadata

Raises:

docker.errors.NotFound – if no secret with that ID exists

remove_secret(id)

Remove a secret

Parameters:

id (string) – Full ID of the secret to remove

Returns (boolean): True if successful

Raises:

docker.errors.NotFound – if no secret with that ID exists

secrets(filters=None)

List secrets

Parameters:
  • filters (list. Available) – A map of filters to process on the secrets

  • filtersnames

Returns (list): A list of secrets

The Docker daemon

class DaemonApiMixin
df()

Get data usage information.

Returns:

A dictionary representing different resource categories and their respective data usage.

Return type:

(dict)

Raises:

docker.errors.APIError – If the server returns an error.

events(since=None, until=None, filters=None, decode=None)

Get real-time events from the server. Similar to the docker events command.

Parameters:
  • since (UTC datetime or int) – Get events from this point

  • until (UTC datetime or int) – Get events until this point

  • filters (dict) – Filter the events by event time, container or image

  • decode (bool) – If set to true, stream will be decoded into dicts on the fly. False by default.

Returns:

A docker.types.daemon.CancellableStream generator

Raises:

docker.errors.APIError – If the server returns an error.

Example

>>> for event in client.events(decode=True)
...   print(event)
{u'from': u'image/with:tag',
 u'id': u'container-id',
 u'status': u'start',
 u'time': 1423339459}
...

or

>>> events = client.events()
>>> for event in events:
...   print(event)
>>> # and cancel from another thread
>>> events.close()
info()

Display system-wide information. Identical to the docker info command.

Returns:

The info as a dict

Return type:

(dict)

Raises:

docker.errors.APIError – If the server returns an error.

login(username, password=None, email=None, registry=None, reauth=False, dockercfg_path=None)

Authenticate with a registry. Similar to the docker login command.

Parameters:
  • username (str) – The registry username

  • password (str) – The plaintext password

  • email (str) – The email for the registry account

  • registry (str) – URL to the registry. E.g. https://index.docker.io/v1/

  • reauth (bool) – Whether or not to refresh existing authentication on the Docker server.

  • dockercfg_path (str) – Use a custom path for the Docker config file (default $HOME/.docker/config.json if present, otherwise $HOME/.dockercfg)

Returns:

The response from the login request

Return type:

(dict)

Raises:

docker.errors.APIError – If the server returns an error.

ping()

Checks the server is responsive. An exception will be raised if it isn’t responding.

Returns:

(bool) The response from the server.

Raises:

docker.errors.APIError – If the server returns an error.

version(api_version=True)

Returns version information from the server. Similar to the docker version command.

Returns:

The server version information

Return type:

(dict)

Raises:

docker.errors.APIError – If the server returns an error.

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 the Mount class for details.

  • stop_grace_period (int) – Amount of time to wait for the container to terminate before forcefully killing it.

  • secrets (list) – List of SecretReference 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’s hosts file.

  • dns_config (DNSConfig) – Specification for DNS related configurations in resolver configuration file.

  • configs (list) – List of ConfigReference 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 a ContainerSpec 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 a ContainerSpec, for the driver_config in a volume Mount, or as the driver object in create_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 the vip 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 of IPAMConfig.

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 a ContainerSpec.

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 the bind type.

  • no_copy (bool) – False if the volume should be populated with the data from the target. Default: False. Only valid for the volume 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 constraints

  • preferences (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. See PlacementPreference 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, or any). 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 or rollback. 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 or stop-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 or global-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 or NetworkAttachmentConfig 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 as rollback 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 or stop-first are accepted.