Transport Layer & HTTP Communication
Motivation
This section outlines how the Docker SDK for Python (docker-py) communicates with the Docker Engine using HTTP requests and responses.
Transport Layer
The docker.transport
module defines the core functionality for sending and receiving HTTP requests to the Docker Engine.
Key Components:
- Connection: Represents a connection to the Docker Engine.
- Request: Represents an HTTP request sent to the Docker Engine.
- Response: Represents an HTTP response received from the Docker Engine.
Connection Types:
The docker.transport
module supports two connection types:
- TCP: Establishes a TCP connection to the Docker Engine.
- UNIX Socket: Connects to the Docker Engine via a Unix socket.
Code Examples:
# Example: Connect to Docker Engine via TCP
from docker import DockerClient
client = DockerClient(base_url='tcp://127.0.0.1:2375')
# Example: Connect to Docker Engine via Unix socket
from docker import DockerClient
client = DockerClient(base_url='unix://var/run/docker.sock')
Source: docker/transport/unix.py docker/transport/tcp.py
HTTP Communication
The docker.api
module defines the HTTP endpoints and methods used to interact with the Docker Engine.
Key Concepts:
- API Endpoints: Represent specific resources available in the Docker Engine.
- HTTP Methods: Define the actions to perform on these resources.
- JSON Serialization/Deserialization: Used to encode and decode data in the HTTP requests and responses.
Code Examples:
# Example: List containers
from docker import DockerClient
client = DockerClient()
containers = client.containers.list()
# Example: Run a container
from docker import DockerClient
client = DockerClient()
container = client.containers.run('ubuntu', detach=True)
# Example: Stop a container
from docker import DockerClient
client = DockerClient()
client.containers.get('container_id').stop()
Source: docker/api/container.py docker/api/client.py
Error Handling
The docker.errors
module provides a set of exceptions for handling errors during communication with the Docker Engine.
Code Examples:
# Example: Handling API errors
from docker import DockerClient
from docker.errors import APIError
client = DockerClient()
try:
container = client.containers.run('invalid_image', detach=True)
except APIError as e:
print(f'Error running container: {e}')
Source: docker/errors.py
Conclusion
This section provides a basic overview of the transport layer and HTTP communication used by the Docker SDK for Python. By understanding these concepts, developers can effectively interact with the Docker Engine and leverage the full capabilities of the SDK.