### start Source: https://github.com/docker/docker-py/blob/main/docs/containers.md Starts a container. ```APIDOC ## start(**kwargs) ### Description Start this container. Similar to the `docker start` command, but doesn’t support attach options. ### Raises **docker.errors.APIError** – If the server returns an error. ``` -------------------------------- ### Create and Start a Container Source: https://github.com/docker/docker-py/blob/main/docs/api.md Demonstrates how to create a new container from an image and then start it. This is a fundamental operation for running services. ```python >>> container = client.api.create_container( ... image='busybox:latest', ... command='/bin/sleep 30') >>> client.api.start(container=container.get('Id')) ``` -------------------------------- ### Temporary Filesystem Configuration Example Source: https://github.com/docker/docker-py/blob/main/docs/api.md Example of how to define temporary filesystems to mount within a container. Options like size and ownership can be specified. ```python { '/mnt/vol2': '', '/mnt/vol1': 'size=3G,uid=1000' } ``` -------------------------------- ### Start Container Source: https://github.com/docker/docker-py/blob/main/docs/api.md Starts a container. Note that passing configuration options directly to `start` is deprecated. Host configuration should be provided during container creation. ```python client.api.start(container='my_container') ``` -------------------------------- ### start Source: https://github.com/docker/docker-py/blob/main/docs/api.md Starts a container, similar to the `docker start` command. Does not support attach options and deprecated for passing configuration options. ```APIDOC ## start ### Description 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()`. ### Method POST ### Endpoint /containers/{container}/start ### Parameters #### Path 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. ``` -------------------------------- ### Install Development Version Source: https://github.com/docker/docker-py/blob/main/CONTRIBUTING.md Install the development version of the project and its dependencies within a virtual environment. ```bash python setup.py develop ``` -------------------------------- ### exec_start Source: https://github.com/docker/docker-py/blob/main/docs/api.md Starts a previously set up exec instance and returns the output or a stream of output. ```APIDOC ## exec_start ### Description Start a previously set up exec instance. ### Method exec_start ### Parameters #### Path Parameters - **exec_id** (str) - Required - ID of the exec instance #### Query Parameters - **detach** (bool) - Optional - If true, detach from the exec command. Default: False - **tty** (bool) - Optional - Allocate a pseudo-TTY. Default: False - **stream** (bool) - Optional - Return response data progressively as an iterator of strings, rather than a single string. - **socket** (bool) - Optional - Return the connection socket to allow custom read/write operations. Must be closed by the caller when done. - **demux** (bool) - Optional - 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. ### Raises - **docker.errors.APIError** – If the server returns an error. ``` -------------------------------- ### enable_plugin Source: https://github.com/docker/docker-py/blob/main/docs/api.md Enable an installed plugin. ```APIDOC ## enable_plugin(name, timeout=0) ### Description Enable an installed plugin. ### Parameters #### Path Parameters - **name** (string) - Required - The name of the plugin. The `:latest` tag is optional, and is the default if omitted. #### Query Parameters - **timeout** (int) - Optional - Operation timeout (in seconds). Default: 0 ### Returns `True` if successful ``` -------------------------------- ### Create Endpoint Configuration Source: https://github.com/docker/docker-py/blob/main/docs/api.md Example of creating an endpoint configuration with aliases, links, and IP address. ```python >>> endpoint_config = client.api.create_endpoint_config( aliases=['web', 'app'], links={'app_db': 'db', 'another': None}, ipv4_address='132.65.0.123' ) ``` -------------------------------- ### Example: Using Client Certificates Source: https://github.com/docker/docker-py/blob/main/docs/tls.md Illustrates how to configure `TLSConfig` with client certificates for mutual TLS authentication. ```APIDOC ```python tls_config = docker.tls.TLSConfig( client_cert=('/path/to/client-cert.pem', '/path/to/client-key.pem') ) client = docker.DockerClient(base_url='', tls=tls_config) ``` ``` -------------------------------- ### Create Container with Networking Configuration Source: https://github.com/docker/docker-py/blob/main/docs/api.md This example shows how to create a container and connect it to a specific network with a static IPv4 address, aliases, and links to other containers. ```python 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 ) ``` -------------------------------- ### Get Container Archive Source: https://github.com/docker/docker-py/blob/main/docs/containers.md Retrieve a file or folder from a container as a tar archive. This example shows how to get the /bin/sh executable, print its stat information, and write the archive content to a local file. ```python >>> f = open('./sh_bin.tar', 'wb') >>> bits, stat = container.get_archive('/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() ``` -------------------------------- ### Example: Using CA Certificate Source: https://github.com/docker/docker-py/blob/main/docs/tls.md Shows how to configure `TLSConfig` with a CA certificate to verify the Docker server's identity. ```APIDOC ```python tls_config = docker.tls.TLSConfig(ca_cert='/path/to/ca.pem', verify=True) client = docker.DockerClient(base_url='', tls=tls_config) ``` ``` -------------------------------- ### plugins Source: https://github.com/docker/docker-py/blob/main/docs/api.md Retrieve a list of all installed plugins. ```APIDOC ## plugins() ### Description Retrieve a list of installed plugins. ### Returns A list of dicts, one per plugin ``` -------------------------------- ### Install Docker SDK for Python Source: https://github.com/docker/docker-py/blob/main/README.md Install the latest stable version of the Docker SDK for Python using pip. Older versions required a separate package for TLS support, but this is no longer necessary. ```bash pip install docker ``` -------------------------------- ### Create Container with Volume Mounts Source: https://github.com/docker/docker-py/blob/main/docs/api.md Creates a container and mounts volumes from the host. This example shows read-write and read-only mounts, as well as propagation settings. ```python 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' } }) ) ``` -------------------------------- ### Get Environment Information Source: https://github.com/docker/docker-py/blob/main/CONTRIBUTING.md Run this command to gather SDK version, Python version, and Docker version for issue reporting. ```bash pip freeze | grep docker && python --version && docker version ``` -------------------------------- ### Create Container with Port Bindings Source: https://github.com/docker/docker-py/blob/main/docs/api.md Creates a new container from a specified image. This example demonstrates how to expose container ports and bind them to host ports, including UDP and multiple bindings. ```python container_id = client.api.create_container( 'busybox', 'ls', ports=[1111, 2222], host_config=client.api.create_host_config(port_bindings={ 1111: 4567, 2222: None }) ) ``` -------------------------------- ### Run a container and get its output Source: https://github.com/docker/docker-py/blob/main/docs/containers.md This snippet demonstrates how to run a Docker container with a specified image and command, and then retrieve its standard output. ```APIDOC ## client.containers.run ### Description Runs a Docker container with the specified image and command, and returns its output. ### Method client.containers.run(image, command, **kwargs) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **image** (*str*) – The image to run. * **command** (*str* *or* *list*) – The command to run in the container. * **auto_remove** (*bool*) – enable auto-removal of the container on daemon side when the container’s process exits. * **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. * **cgroup_parent** (*str*) – Override the default parent cgroup. * **cgroupns** (*str*) – Override the default cgroup namespace mode for the container. One of: `private` or `host`. * **cpu_count** (*int*) – Number of usable CPUs (Windows only). * **cpu_percent** (*int*) – Usable percentage of the available CPUs (Windows only). * **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_rt_period** (*int*) – Limit CPU real-time period in microseconds. * **cpu_rt_runtime** (*int*) – Limit CPU real-time runtime in microseconds. * **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. * **detach** (*bool*) – Run container in the background and return a `Container` object. * **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 `::`. * **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. * **domainname** (*str* *or* *list*) – Set custom DNS search domains. * **entrypoint** (*str* *or* *list*) – The entrypoint for the container. * **environment** (*dict* *or* *list*) – Environment variables to set inside the container. * **extra_hosts** (*dict*) – Additional hostnames to resolve inside the container. * **group_add** (*list*) – List of additional group names and/or IDs that the container process will run as. * **healthcheck** (*dict*) – Specify a test to perform to check that the container is healthy. ### Request Example ```python import docker client = docker.from_env() client.containers.run('alpine', 'echo hello world') ``` ### Response #### Success Response (200) Returns the container output as bytes. #### Response Example ``` b'hello world\n' ``` ``` -------------------------------- ### Run a container and get its output Source: https://github.com/docker/docker-py/blob/main/docs/containers.md Use this snippet to run a container and immediately capture its standard output. Ensure the Docker daemon is accessible. ```python import docker client = docker.from_env() client.containers.run('alpine', 'echo hello world') ``` -------------------------------- ### create Source: https://github.com/docker/docker-py/blob/main/docs/containers.md Creates a Docker container without starting it. This method accepts arguments similar to the `run()` method, excluding `stdout`, `stderr`, and `remove`. ```APIDOC ## create(image, command=None, **kwargs) ### Description Create a container without starting it. Similar to `docker create`. Takes the same arguments as [`run()`](#docker.models.containers.ContainerCollection.run), except for `stdout`, `stderr`, and `remove`. ### Returns A [`Container`](#docker.models.containers.Container) object. ### Raises * **docker.errors.ImageNotFound** – If the specified image does not exist. * **docker.errors.APIError** – If the server returns an error. ``` -------------------------------- ### Initialize APIClient and Get Version Source: https://github.com/docker/docker-py/blob/main/docs/api.md Instantiate the APIClient with a Unix socket and retrieve the Docker Engine version. Ensure the Docker daemon is accessible via the specified socket. ```python import docker client = docker.APIClient(base_url='unix://var/run/docker.sock') client.version() ``` -------------------------------- ### Get Docker Version Information Source: https://github.com/docker/docker-py/blob/main/docs/client.md Fetch version information from the Docker server. This mirrors the 'docker version' command. ```python # client.version() is called here, but no example is provided in the source. ``` -------------------------------- ### Tag Image Source: https://github.com/docker/docker-py/blob/main/docs/api.md Example of tagging an image to a specific repository and tag, with an option to force the operation. This is equivalent to the `docker tag` command. ```python >>> client.api.tag('ubuntu', 'localhost:5000/ubuntu', 'latest', force=True) ``` -------------------------------- ### Run Ubuntu Container Source: https://github.com/docker/docker-py/blob/main/docs/api.md Starts an Ubuntu container in detached mode, mapping port 80 to 80, and keeps it running for 30 seconds. This is a common way to quickly spin up a test environment. ```bash $ docker run -d -p 80:80 ubuntu:14.04 /bin/sleep 30 7174d6347063a83f412fad6124c99cffd25ffe1a0807eb4b7f9cec76ac8cb43b ``` -------------------------------- ### Build Documentation Source: https://github.com/docker/docker-py/blob/main/CONTRIBUTING.md Build the project's documentation locally. ```bash $ make docs $ open _build/index.html ``` -------------------------------- ### remove_plugin Source: https://github.com/docker/docker-py/blob/main/docs/api.md Remove an installed plugin. ```APIDOC ## remove_plugin(name, force=False) ### Description Remove an installed plugin. ### Parameters #### Path Parameters - **name** (string) - Required - Name of the plugin to remove. The `:latest` tag is optional, and is the default if omitted. #### Query Parameters - **force** (bool) - Optional - Disable the plugin before removing. This may result in issues if the plugin is in use by a container. ### Returns `True` if successful ``` -------------------------------- ### disable_plugin Source: https://github.com/docker/docker-py/blob/main/docs/api.md Disable an installed plugin. ```APIDOC ## disable_plugin(name, force=False) ### Description Disable an installed plugin. ### Parameters #### Path Parameters - **name** (string) - Required - The name of the plugin. The `:latest` tag is optional, and is the default if omitted. #### Query Parameters - **force** (bool) - Optional - To enable the force query parameter. ### Returns `True` if successful ``` -------------------------------- ### pull_plugin Source: https://github.com/docker/docker-py/blob/main/docs/api.md Pull and install a plugin from a remote reference. ```APIDOC ## pull_plugin(remote, privileges, name=None) ### Description Pull and install a plugin. After the plugin is installed, it can be enabled using `enable_plugin()`. ### Parameters #### Path Parameters - **remote** (string) - Required - Remote reference for the plugin to install. The `:latest` tag is optional, and is the default if omitted. - **privileges** (list) - Required - A list of privileges the user consents to grant to the plugin. Can be retrieved using `plugin_privileges()`. #### Query Parameters - **name** (string) - Optional - 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 ``` -------------------------------- ### upgrade_plugin Source: https://github.com/docker/docker-py/blob/main/docs/api.md Upgrade an installed plugin to a new remote reference. ```APIDOC ## upgrade_plugin(name, remote, privileges) ### Description Upgrade an installed plugin. ### Parameters #### Path Parameters - **name** (string) - Required - Name of the plugin to upgrade. The `:latest` tag is optional and is the default if omitted. - **remote** (string) - Required - Remote reference to upgrade to. The `:latest` tag is optional and is the default if omitted. - **privileges** (list) - Required - 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 ``` -------------------------------- ### Create Ulimit and Host Config Source: https://github.com/docker/docker-py/blob/main/docs/api.md Demonstrates how to create a Ulimit object and use it to configure host settings for a container. This is useful for setting resource limits like the maximum number of processes. ```python >>> 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}] ``` -------------------------------- ### get Source: https://github.com/docker/docker-py/blob/main/docs/containers.md Retrieves a Docker container using its name or ID. ```APIDOC ## get(id_or_name) ### Description Get a container by name or ID. ### Parameters #### Path Parameters - **id_or_name** (str) - Required - Container name or ID. ### Returns A [`Container`](#docker.models.containers.Container) object. ### Raises * **docker.errors.NotFound** – If the container does not exist. * **docker.errors.APIError** – If the server returns an error. ``` -------------------------------- ### Get Volume Source: https://github.com/docker/docker-py/blob/main/docs/volumes.md Retrieves a specific volume by its ID or name. ```APIDOC ## GET /volumes/{id} ### Description Get a volume. ### Method GET ### Endpoint /volumes/{id} ### Parameters #### Path Parameters - **volume_id** (str) - Required - Volume name or ID. ### Response #### Success Response (200) - **Volume** ([`Volume`](#docker.models.volumes.Volume)) - The volume. #### Response Example (Volume object representation) ### Errors - **docker.errors.NotFound**: If the volume does not exist. - **docker.errors.APIError**: If the server returns an error. ``` -------------------------------- ### Create Network with IPAM Config Source: https://github.com/docker/docker-py/blob/main/docs/api.md Demonstrates creating a Docker network with a custom IPAM configuration. Ensure the IPAM driver is correctly specified. ```python >>> ipam_config = docker.types.IPAMConfig(driver='default') >>> network = client.create_network('network1', ipam=ipam_config) ``` -------------------------------- ### Get Network Source: https://github.com/docker/docker-py/blob/main/docs/networks.md Retrieves a specific Docker network by its ID. ```APIDOC ## get(network_id, *args, **kwargs) ### Description Get a network by its ID. ### Parameters #### Path Parameters - **network_id** (str) - Required - The ID of the network. #### Query Parameters - **verbose** (bool) - Optional - Retrieve the service details across the cluster in swarm mode. - **scope** (str) - Optional - Filter the network by scope (`swarm`, `global` or `local`). ### Returns - ([`Network`](#docker.models.networks.Network)) - The network. ### Raises - **docker.errors.NotFound** - If the network does not exist. - **docker.errors.APIError** - If the server returns an error. ``` -------------------------------- ### Creating a client with from_env() Source: https://github.com/docker/docker-py/blob/main/docs/client.md Instantiate a client by calling from_env(). This function configures the client using environment variables, mirroring the behavior of the Docker command-line client. ```APIDOC ## from_env() ### Description Return a client configured from environment variables. The environment variables used are the same as those used by the Docker command-line client. ### Parameters * **version** (*str*) – The version of the API to use. Set to `auto` to automatically detect the server’s version. Default: `auto` * **timeout** (*int*) – Default timeout for API calls, in seconds. * **max_pool_size** (*int*) – The maximum number of connections to save in the pool. * **environment** (*dict*) – The environment to read environment variables from. Default: the value of `os.environ` * **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. ### Example ```pycon >>> import docker >>> client = docker.from_env() ``` ``` -------------------------------- ### Get a Node Source: https://github.com/docker/docker-py/blob/main/docs/nodes.md Retrieves a specific node from the swarm using its ID or name. ```APIDOC ## GET /nodes/{id_or_name} ### Description Get a specific node from the swarm. ### Method GET ### Endpoint `/nodes/{id_or_name}` ### Parameters #### Path Parameters - **id_or_name** (string) - Required - The ID or name of the node to retrieve. ### Response #### Success Response (200) - **Node** (object) - A Node object representing the retrieved node. ``` -------------------------------- ### TLSConfig Initialization Source: https://github.com/docker/docker-py/blob/main/docs/tls.md Demonstrates how to create a `TLSConfig` object for connecting to Docker with TLS, including options for CA certificates and client authentication. ```APIDOC ## TLSConfig TLS configuration. ### Parameters: * **client_cert** (*tuple* *of* *str*) – Path to client cert, path to client key. * **ca_cert** (*str*) – Path to CA cert file. * **verify** (*bool* *or* *str*) – This can be a bool or a path to a CA cert file to verify against. If `True`, verify using ca_cert; if `False` or not specified, do not verify. ``` -------------------------------- ### login() Source: https://github.com/docker/docker-py/blob/main/docs/client.md Authenticate with a registry. This method is similar to the `docker login` command. ```APIDOC ## login() ### Description Authenticate with a registry. Similar to the `docker login` command. ### Parameters #### Path Parameters - **username** (str) - Required - The registry username - **password** (str) - Required - The plaintext password - **email** (str) - Required - The email for the registry account - **registry** (str) - Optional - URL to the registry. E.g. `https://index.docker.io/v1/` - **reauth** (bool) - Optional - Whether or not to refresh existing authentication on the Docker server. - **dockercfg_path** (str) - Optional - 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. ``` -------------------------------- ### Get Config Source: https://github.com/docker/docker-py/blob/main/docs/configs.md Retrieves a specific configuration by its ID. This is analogous to `docker config inspect`. ```APIDOC ## get ### Description Get a config. ### Method `client.configs.get(config_id)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **config_id** (str) – Required – Config ID. ### Response #### Success Response (200) * **Config object** - The retrieved config object. #### Response Example ```python config = client.configs.get('config_id_123') print(config.attrs) ``` ### Raises * **docker.errors.NotFound** – If the config does not exist. * **docker.errors.APIError** – If the server returns an error. ``` -------------------------------- ### prune Source: https://github.com/docker/docker-py/blob/main/docs/images.md Deletes unused images. You can filter which images to prune, for example, only dangling and untagged images. ```APIDOC ## prune ### Description Delete unused images ### Parameters #### Query Parameters - **filters** (dict) - Optional - 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) ``` -------------------------------- ### exec_create Source: https://github.com/docker/docker-py/blob/main/docs/api.md Sets up an exec instance in a running container. This method prepares the execution environment for a command without immediately running it. ```APIDOC ## exec_create ### Description Sets up an exec instance in a running container. ### Method exec_create ### Parameters #### Path Parameters - **container** (str) - Required - Target container where exec instance will be created - **cmd** (str or list) - Required - Command to be executed #### Query Parameters - **stdout** (bool) - Optional - Attach to stdout. Default: `True` - **stderr** (bool) - Optional - Attach to stderr. Default: `True` - **stdin** (bool) - Optional - Attach to stdin. Default: `False` - **tty** (bool) - Optional - Allocate a pseudo-TTY. Default: False - **privileged** (bool) - Optional - Run as privileged. - **user** (str) - Optional - User to execute command as. Default: root - **environment** (dict or list) - Optional - A dictionary or a list of strings in the following format `["PASSWORD=xxx"]` or `{"PASSWORD": "xxx"}`. - **workdir** (str) - Optional - Path to working directory for this exec session - **detach_keys** (str) - Optional - Override the key sequence for detaching a container. Format is a single character [a-Z] or ctrl- where is one of: a-z, @, ^, [, , or \_. ### Returns - **Id** (str) - The ID of the created exec instance. ### Raises - **docker.errors.APIError** – If the server returns an error. ``` -------------------------------- ### Get Docker Container Logs Source: https://github.com/docker/docker-py/blob/main/README.md Retrieve the logs from a Docker container. The logs are returned as a string. ```python container.logs() ``` -------------------------------- ### Configure Container Logging Source: https://github.com/docker/docker-py/blob/main/docs/api.md Illustrates setting up a JSON file log driver for a container with specific configuration options like max-size and labels. This requires creating a LogConfig object and passing it to create_host_config. ```python >>> 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'} } ``` -------------------------------- ### Clone Project and Run Tests Source: https://github.com/docker/docker-py/blob/main/CONTRIBUTING.md Clone the Docker SDK for Python repository and execute the test suite. ```bash $ git clone git://github.com/docker/docker-py.git $ cd docker-py $ make test ``` -------------------------------- ### Get a Specific Docker Container Source: https://github.com/docker/docker-py/blob/main/README.md Retrieve a specific Docker container by its ID. Returns a Container object. ```python container = client.containers.get('45e6d2de7c54') ``` -------------------------------- ### Create Container with Volume Binds Source: https://github.com/docker/docker-py/blob/main/docs/api.md This snippet demonstrates how to create a container and specify multiple volume binds, including read-only and read-write/shared options. ```python 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', ]) ) ``` -------------------------------- ### Push an image to a registry with streaming output Source: https://github.com/docker/docker-py/blob/main/docs/images.md This snippet demonstrates how to push an image to a registry, with options to stream the output and decode JSON responses. It's useful for monitoring the push progress. Ensure 'stream' and 'decode' are set appropriately for your needs. ```python >>> 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'} ... ``` -------------------------------- ### Get Docker System Information Source: https://github.com/docker/docker-py/blob/main/docs/client.md Retrieve system-wide information from the Docker daemon. This is equivalent to running the 'docker info' command. ```python # client.info() is called here, but no example is provided in the source. ``` -------------------------------- ### info() Source: https://github.com/docker/docker-py/blob/main/docs/client.md Display system-wide information. This method is identical in functionality to the `docker info` command. ```APIDOC ## info() ### Description 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. ``` -------------------------------- ### Get a Service Source: https://github.com/docker/docker-py/blob/main/docs/services.md Retrieves details for a specific Docker service using its ID. Optionally merges default values into the response. ```APIDOC ## GET /services/{service_id} ### Description Get a service by its ID. If `insert_defaults` is true, default values will be merged into the output. ### Method GET ### Endpoint `/services/{service_id}` ### Parameters #### Path Parameters - **service_id** (str) - Required - The ID of the service. #### Query Parameters - **insert_defaults** (boolean) - Optional - If true, default values will be merged into the output. ### Response #### Success Response (200) - **Service** (object) - The service object. ### Errors - **docker.errors.NotFound**: If the service does not exist. - **docker.errors.APIError**: If the server returns an error. - **docker.errors.InvalidVersion**: If an argument is not supported with the current API version. ``` -------------------------------- ### Create Docker Client and Run Container Source: https://github.com/docker/docker-py/blob/main/docs/user_guides/multiplex.md Initializes the Docker client and runs a container in detached mode. This is a prerequisite for executing commands. ```python client = docker.from_env() container = client.containers.run( 'bfirsh/reticulate-splines', detach=True) ``` -------------------------------- ### Configure Temporary Filesystems Source: https://github.com/docker/docker-py/blob/main/docs/containers.md Mount temporary filesystems within the container at specified paths. Options for size, UID, and other attributes can be provided. ```python { '/mnt/vol2': '', '/mnt/vol1': 'size=3G,uid=1000' } ``` -------------------------------- ### Create a network with custom IPAM configuration Source: https://github.com/docker/docker-py/blob/main/docs/networks.md Create a network with specific subnet and gateway settings using IPAM configurations. This allows for more control over the network's IP addressing. ```python 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.networks.create( "network1", driver="bridge", ipam=ipam_config ) ``` -------------------------------- ### Inspect a Docker Swarm Service Source: https://github.com/docker/docker-py/blob/main/docs/user_guides/swarm_services.md Get detailed configuration for a specific service using `APIClient.inspect_service`. The service can be identified by its ID or name. ```python client.inspect_service(service='my_service_name') ``` -------------------------------- ### Create Host Configuration Source: https://github.com/docker/docker-py/blob/main/docs/api.md Use this function to create a dictionary suitable for the `host_config` argument in `create_container()`. It allows setting various container host-level configurations. ```python >>> 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} ``` -------------------------------- ### Instantiate Docker Client Manually Source: https://github.com/docker/docker-py/blob/main/docs/client.md Create a Docker client by manually specifying the connection details, such as the base URL for the Docker server. ```python import docker client = docker.DockerClient(base_url='unix://var/run/docker.sock') ``` -------------------------------- ### Create Docker Network and Container Source: https://github.com/docker/docker-py/blob/main/docs/api.md Demonstrates creating a new Docker network and then a container attached to that network. This is useful for setting up isolated environments for applications. ```python >>> 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 ) ``` -------------------------------- ### List Docker Swarm Services Source: https://github.com/docker/docker-py/blob/main/docs/user_guides/swarm_services.md Retrieve a list of all existing services using the `APIClient.services` method. Filters can be applied, for example, by service name. ```python client.services(filters={'name': 'mysql'}) ``` -------------------------------- ### Create a basic bridge network Source: https://github.com/docker/docker-py/blob/main/docs/networks.md Use this to create a simple network with the bridge driver. Ensure the network name is unique. ```python client.networks.create("network1", driver="bridge") ``` -------------------------------- ### Swarm.init() Source: https://github.com/docker/docker-py/blob/main/docs/swarm.md Initializes a new Docker Swarm on the current Docker Engine. This method allows configuration of various swarm parameters. ```APIDOC ## Swarm.init() ### Description Initialize a new swarm on this Engine. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **advertise_addr** (str) - Optional - 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 not specified, it will be automatically detected when possible. * **listen_addr** (str) - Optional - 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) - Optional - Force creating a new Swarm, even if already part of one. Default: False * **default_addr_pool** (list of str) - Optional - 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) - Optional - SubnetSize specifies the subnet size of the networks created from the default subnet pool. Default: None * **data_path_addr** (string) - Optional - Address or interface to use for data path traffic. For example, 192.168.1.1, or an interface, like eth0. * **data_path_port** (int) - Optional - 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 * **task_history_retention_limit** (int) - Optional - Maximum number of tasks history stored. * **snapshot_interval** (int) - Optional - Number of logs entries between snapshot. * **keep_old_snapshots** (int) - Optional - Number of snapshots to keep beyond the current snapshot. * **log_entries_for_slow_followers** (int) - Optional - Number of log entries to keep around to sync up slow followers after a snapshot is created. * **heartbeat_tick** (int) - Optional - Amount of ticks (in seconds) between each heartbeat. * **election_tick** (int) - Optional - Amount of ticks (in seconds) needed without a leader to trigger a new election. * **dispatcher_heartbeat_period** (int) - Optional - The delay for an agent to send a heartbeat to the dispatcher. * **node_cert_expiry** (int) - Optional - Automatic expiry for nodes certificates. * **external_ca** (dict) - Optional - Configuration for forwarding signing requests to an external certificate authority. Use `docker.types.SwarmExternalCA`. * **name** (string) - Optional - Swarm’s name * **labels** (dict) - Optional - User-defined key/value metadata. * **signing_ca_cert** (str) - Optional - The desired signing CA certificate for all swarm node TLS leaf certificates, in PEM format. * **signing_ca_key** (str) - Optional - The desired signing CA key for all swarm node TLS leaf certificates, in PEM format. * **ca_force_rotate** (int) - Optional - 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) - Optional - If set, generate a key and use it to lock data stored on the managers. * **log_driver** (DriverConfig) - Optional - The default log driver to use for tasks created in the orchestrator. ### Request Example ```python client.swarm.init( advertise_addr='eth0', listen_addr='0.0.0.0:5000', force_new_cluster=False, default_addr_pool=['10.20.0.0/16], subnet_size=24, snapshot_interval=5000, log_entries_for_slow_followers=1200 ) ``` ### Returns The ID of the created node. ### Return type (str) ### Raises **docker.errors.APIError** – If the server returns an error. ``` -------------------------------- ### Check Docker Server Responsiveness Source: https://github.com/docker/docker-py/blob/main/docs/client.md Verify if the Docker server is responding. An exception is raised if the server is not reachable. ```python # client.ping() is called here, but no example is provided in the source. ``` -------------------------------- ### create_plugin Source: https://github.com/docker/docker-py/blob/main/docs/api.md Create a new plugin from a directory. ```APIDOC ## create_plugin(name, plugin_data_dir, gzip=False) ### Description Create a new plugin. ### Parameters #### Path Parameters - **name** (string) - Required - The name of the plugin. The `:latest` tag is optional, and is the default if omitted. - **plugin_data_dir** (string) - Required - Path to the plugin data directory. Plugin data directory must contain the `config.json` manifest file and the `rootfs` directory. #### Query Parameters - **gzip** (bool) - Optional - Compress the context using gzip. Default: False ### Returns `True` if successful ``` -------------------------------- ### Get Image Tarball Source: https://github.com/docker/docker-py/blob/main/docs/api.md Retrieves a tarball of a specified image, similar to the `docker save` command. The data is streamed in chunks and written to a local file. ```python >>> image = client.api.get_image("busybox:latest") >>> f = open('/tmp/busybox-latest.tar', 'wb') >>> for chunk in image: >>> f.write(chunk) >>> f.close() ``` -------------------------------- ### Run a container in detached mode and get logs Source: https://github.com/docker/docker-py/blob/main/docs/containers.md Run a container in the background and retrieve its logs later. This is useful for long-running processes. The `detach=True` argument is key here. ```python container = client.containers.run('bfirsh/reticulate-splines', detach=True) container.logs() ``` -------------------------------- ### create_container Source: https://github.com/docker/docker-py/blob/main/docs/api.md Creates a container. Parameters are similar to `docker run` but without attach options. Requires host-specific configuration to be passed via `host_config`. ```APIDOC ## create_container ### Description 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. ### Method POST ### Endpoint /containers/create ### Parameters #### Path Parameters - **image** (str) - Required - The image to use for the container. #### Request Body - **command** (str) - Optional - The command to run in the container. - **hostname** (str) - Optional - The hostname to use for the container. - **user** (str) - Optional - The user to run the command as. - **detach** (bool) - Optional - Whether to run the container in detached mode. - **stdin_open** (bool) - Optional - Whether to keep stdin open even if not attached. - **tty** (bool) - Optional - Whether to allocate a pseudo-TTY. - **ports** (list) - Optional - A list of ports to open inside the container. - **environment** (dict) - Optional - A dictionary of environment variables to set in the container. - **volumes** (list) - Optional - A list of paths to use as mountpoints inside the container. - **network_disabled** (bool) - Optional - Whether to disable networking for the container. - **name** (str) - Optional - The name to assign to the container. - **entrypoint** (str) - Optional - The entrypoint for the container. - **working_dir** (str) - Optional - The working directory for the container. - **domainname** (str) - Optional - The domain name for the container. - **host_config** (dict) - Optional - Host-specific configuration for the container (e.g., port bindings, volume mounts). - **mac_address** (str) - Optional - The MAC address for the container. - **labels** (dict) - Optional - A dictionary of labels to assign to the container. - **stop_signal** (str) - Optional - The signal to send to stop the container. - **networking_config** (dict) - Optional - Networking configuration for the container. - **healthcheck** (dict) - Optional - Healthcheck configuration for the container. - **stop_timeout** (int) - Optional - The number of seconds to wait for the container to stop before killing it. - **runtime** (str) - Optional - The runtime to use for the container. - **use_config_proxy** (bool) - Optional - Whether to use the Docker client's proxy configuration. - **platform** (str) - Optional - The platform to use for the container. ### Request Example ```json { "image": "busybox", "command": "ls", "ports": [1111, 2222], "host_config": { "port_bindings": { "1111": 4567, "2222": null } } } ``` ### Response #### Success Response (200) - **container_id** (str) - The ID of the created container. #### Error Response - **docker.errors.APIError** – If the server returns an error. ``` -------------------------------- ### ContainerCollection.run Source: https://github.com/docker/docker-py/blob/main/docs/containers.md Runs a Docker container. By default, it waits for the container to complete and returns its logs. If `detach` is set to `True`, it starts the container and returns a `Container` object immediately. ```APIDOC ## ContainerCollection.run ### Description Runs a container. By default, it will wait for the container to finish and return its logs, similar to `docker run`. If the `detach` argument is `True`, it will start the container and immediately return a [`Container`](#docker.models.containers.Container) object, similar to `docker run -d`. ### Method `ContainerCollection.run("image", command=None, **kwargs)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Example of running a container and getting logs container = client.containers.run("ubuntu", "echo hello world") print(container) # Example of running a container in detached mode detached_container = client.containers.run("ubuntu", "sleep infinity", detach=True) print(detached_container.id) ``` ### Response #### Success Response (200) - **Logs**: If `detach` is `False`, returns the logs of the container as bytes. - **Container object**: If `detach` is `True`, returns a `Container` object. #### Response Example ```json # Example response for non-detached run "hello world\n" # Example response for detached run (Container object representation) { "id": "", "name": "", "image": "", "status": "running" } ``` ```