aiodocker: AsyncIO bindings for docker.io¶
A simple Docker HTTP API wrapper written with asyncio and aiohttp.
Installation¶
pip install aiodocker
Examples¶
import asyncio
import aiodocker
async def list_things():
docker = aiodocker.Docker()
print('== Images ==')
for image in (await docker.images.list()):
tags = image['RepoTags'][0] if image['RepoTags'] else ''
print(image['Id'], tags)
print('== Containers ==')
for container in (await docker.containers.list()):
print(f" {container._id}")
await docker.close()
async def run_container():
docker = aiodocker.Docker()
print('== Running a hello-world container ==')
container = await docker.containers.create_or_replace(
config={
'Cmd': ['/bin/ash', '-c', 'echo "hello world"'],
'Image': 'alpine:latest',
},
name='testing',
)
await container.start()
logs = await container.log(stdout=True)
print(''.join(logs))
await container.delete(force=True)
await docker.close()
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(list_things())
loop.run_until_complete(run_container())
loop.close()
Source code¶
The project is hosted on GitHub: https://github.com/aio-libs/aiodocker
Please feel free to file an issue on the bug tracker if you have found a bug or have some suggestion in order to improve the library.
Communication channels¶
aio-libs google group: https://groups.google.com/forum/#!forum/aio-libs
Feel free to post your questions and ideas here.
Gitter Chat https://gitter.im/aio-libs/Lobby
We support Stack Overflow. Please add python-asyncio tag to your question there.
Contribution¶
Please follow the Contribution Guide.
Author and License¶
The aiodocker
package is written by Andrew Svetlov.
It’s Apache 2 licensed and freely available.
Client¶
Reference¶
Docker¶
Configs¶
Create a config¶
import asyncio
import aiodocker
docker = aiodocker.Docker()
async def create_config():
config = await docker.configs.create(
name="my_config",
data="This is my config data"
)
await docker.close()
return config
async def create_service(TaskTemplate):
service = await docker.services.create(
task_template=TaskTemplate,
name="my_service"
)
await docker.close()
if __name__ == '__main__':
loop = asyncio.get_event_loop()
my_config = loop.run_until_complete(create_config())
TaskTemplate = {
"ContainerSpec": {
"Image": "redis",
"Configs": [
{
"File": {
"Name": my_config["Spec"]["Name"],
"UID": "0",
"GID": "0",
"Mode": 292
},
"ConfigID": my_config["ID"],
"ConfigName": my_config["Spec"]["Name"],
}
],
},
}
loop.run_until_complete(create_service(TaskTemplate))
loop.close()
Reference¶
DockerConfigs¶
- class aiodocker.configs.DockerConfigs(docker)[source]¶
- coroutine create(self, name, data, *, b64=False, labels=None, templating=None)[source]¶
Create a config
- Parameters
- Return type
- Returns
a dict with info of the created config
- coroutine list(self, *, filters=None)[source]¶
Return a list of configs
- Available filters:
id=<config id> label=<key> or label=<key>=value name=<config name> names=<config name>
- coroutine update(self, config_id, version, *, name=None, data=None, b64=False, labels=None, templating=None)[source]¶
Update a config.
Containers¶
Create a container¶
import asyncio
import aiodocker
docker = aiodocker.Docker()
config = {
"Cmd": ["/bin/ls"],
"Image": "alpine:latest",
"AttachStdin": False,
"AttachStdout": False,
"AttachStderr": False,
"Tty": False,
"OpenStdin": False,
}
async def create_container():
container = await docker.containers.create(config=config)
print(container)
await docker.close()
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(create_container())
loop.close()
Reference¶
DockerContainers¶
- class aiodocker.docker.DockerContainers(docker)[source]¶
-
- coroutine run(self, config, *, auth=None, name=None)[source]¶
Create and start a container.
If container.start() will raise an error the exception will contain a container_id attribute with the id of the container.
Use auth for specifying credentials for pulling absent image from a private registry.
DockerContainer¶
- class aiodocker.docker.DockerContainer(docker, **kwargs)[source]¶
- attach(*, stdout=False, stderr=False, stdin=False, detach_keys=None, logs=False)[source]¶
- Return type
Stream
- coroutine commit(self, *, repository=None, tag=None, message=None, author=None, changes=None, config=None, pause=True)[source]¶
Commit a container to an image. Similar to the
docker commit
command.
Images¶
Reference¶
DockerImages¶
- class aiodocker.images.DockerImages(docker)[source]¶
- build(*, remote: str = 'None', fileobj: BinaryIO = 'None', path_dockerfile: str = 'None', tag: str = 'None', quiet: bool = 'False', nocache: bool = 'False', buildargs: Mapping = 'None', pull: bool = 'False', rm: bool = 'True', forcerm: bool = 'False', labels: Mapping = 'None', stream: typing_extensions.Literal[False] = 'False', encoding: str = 'None') → Dict[str, Any][source]¶
- build(*, remote: str = 'None', fileobj: BinaryIO = 'None', path_dockerfile: str = 'None', tag: str = 'None', quiet: bool = 'False', nocache: bool = 'False', buildargs: Mapping = 'None', pull: bool = 'False', rm: bool = 'True', forcerm: bool = 'False', labels: Mapping = 'None', stream: typing_extensions.Literal[True], encoding: str = 'None') → AsyncIterator[Dict[str, Any]]
Build an image given a remote Dockerfile or a file object with a Dockerfile inside
- Parameters
path_dockerfile (
Optional
[str
]) – path within the build context to the Dockerfileremote (
Optional
[str
]) – a Git repository URI or HTTP/HTTPS context URIquiet (
bool
) – suppress verbose build outputnocache (
bool
) – do not use the cache when building the imagerm (
bool
) – remove intermediate containers after a successful buildpull (
bool
) – downloads any updates to the FROM image in Dockerfilesencoding (
Optional
[str
]) – set Content-Encoding for the file object your sendforcerm (
bool
) – always remove intermediate containers, even upon failurelabels (
Optional
[Mapping
]) – arbitrary key/value labels to set on the imagefileobj (
Optional
[BinaryIO
]) – a tar archive compressed or not
- Return type
- coroutine delete(self, name, *, force=False, noprune=False)[source]¶
Remove an image along with any untagged parent images that were referenced by that image
- export_image(name)[source]¶
Get a tarball of an image by name or id.
- Parameters
name (
str
) – name/id of the image to be exported- Returns
Streamreader of tarball image
- import_image(data, stream=False)[source]¶
Import tarball of image to docker.
- Parameters
data – tarball data of image to be imported
- Returns
Tarball of the image
- pull(from_image: str, *, auth: Optional[Union[MutableMapping, str, bytes]] = 'None', tag: str = 'None', repo: str = 'None', stream: typing_extensions.Literal[False] = 'False') → Dict[str, Any][source]¶
- pull(from_image: str, *, auth: Optional[Union[MutableMapping, str, bytes]] = 'None', tag: str = 'None', repo: str = 'None', stream: typing_extensions.Literal[True]) → AsyncIterator[Dict[str, Any]]
Similar to docker pull, pull an image locally
- Parameters
fromImage – name of the image to pull
repo (
Optional
[str
]) – repository name given to an image when it is importedtag (
Optional
[str
]) – if empty when pulling an image all tags for the given image to be pulledauth (
Union
[MutableMapping
,str
,bytes
,None
]) – special {‘auth’: base64} pull private repo
- Return type
- push(name: str, *, auth: Union[MutableMapping, str, bytes] = 'None', tag: str = 'None', stream: typing_extensions.Literal[False] = 'False') → Dict[str, Any][source]¶
- push(name: str, *, auth: Union[MutableMapping, str, bytes] = 'None', tag: str = 'None', stream: typing_extensions.Literal[True]) → AsyncIterator[Dict[str, Any]]
- Return type
Secrets¶
Create a secret¶
import asyncio
import aiodocker
docker = aiodocker.Docker()
async def create_secret():
secret = await docker.secrets.create(
name="my_secret",
data="you can not read that terrible secret"
)
await docker.close()
return secret
async def create_service(TaskTemplate):
service = await docker.services.create(
task_template=TaskTemplate,
name="my_service"
)
await docker.close()
if __name__ == '__main__':
loop = asyncio.get_event_loop()
my_secret = loop.run_until_complete(create_secret())
TaskTemplate = {
"ContainerSpec": {
"Image": "redis",
"Secrets": [
{
"File": {
"Name": my_secret["Spec"]["Name"],
"UID": "0",
"GID": "0",
"Mode": 292
},
"SecretID": my_secret["ID"],
"SecretName": my_secret["Spec"]["Name"]
}
],
},
}
loop.run_until_complete(create_service(TaskTemplate))
loop.close()
Reference¶
DockerSecrets¶
- class aiodocker.secrets.DockerSecrets(docker)[source]¶
- coroutine create(self, name, data, *, b64=False, labels=None, driver=None, templating=None)[source]¶
Create a secret
- Parameters
name (
str
) – name of the secretdata (
str
) – data to store as secretb64 (
bool
) – True if data is already Base64-url-safe-encodeddriver (
Optional
[Mapping
]) – Driver represents a driver (network, logging, secrets).templating (
Optional
[Mapping
]) – Driver represents a driver (network, logging, secrets).
- Return type
- Returns
a dict with info of the created secret
- coroutine list(self, *, filters=None)[source]¶
Return a list of secrets
- Available filters:
id=<secret id> label=<key> or label=<key>=value name=<secret name> names=<secret name>
- coroutine update(self, secret_id, version, *, name=None, data=None, b64=False, labels=None, driver=None, templating=None)[source]¶
Update a secret.
- Parameters
- Return type
- Returns
True if successful.
Services¶
Create a service¶
import asyncio
import aiodocker
docker = aiodocker.Docker()
TaskTemplate = {
"ContainerSpec": {
"Image": "redis",
},
}
async def create_service():
service = await docker.services.create(
task_template=TaskTemplate,
name="my_service"
)
await docker.close()
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(create_service())
loop.close()
Reference¶
DockerServices¶
- class aiodocker.services.DockerServices(docker)[source]¶
- coroutine create(self, task_template, *, name=None, labels=None, mode=None, update_config=None, rollback_config=None, networks=None, endpoint_spec=None, auth=None, registry=None)[source]¶
Create a service
- Parameters
task_template (
Mapping
[str
,Any
]) – user modifiable task configurationupdate_config (
Optional
[Mapping
]) – update strategy of the servicerollback_config (
Optional
[Mapping
]) – rollback strategy of the servicenetworks (
Optional
[List
]) – array of network names/IDs to attach the service toauth (
Union
[MutableMapping
,str
,bytes
,None
]) – authentication information, can be a string, dict or bytesregistry (
Optional
[str
]) – used when auth is specified, it provides domain/IP of the registry without a protocol
- Return type
- Returns
a dict with info of the created service
- coroutine list(self, *, filters=None)[source]¶
Return a list of services
- Available filters:
id=<service id> label=<service label> mode=[“replicated”|”global”] name=<service name>
- logs(service_id, *, details=False, follow=False, stdout=False, stderr=False, since=0, timestamps=False, is_tty=False, tail='all')[source]¶
Retrieve logs of the given service
- Parameters
details (
bool
) – show service context and extra details provided to logsfollow (
bool
) – return the logs as a stream.stdout (
bool
) – return logs from stdoutstderr (
bool
) – return logs from stderrsince (
int
) – return logs since this time, as a UNIX timestamptimestamps (
bool
) – add timestamps to every log lineis_tty (
bool
) – the service has a pseudo-TTY allocatedtail (
str
) – only return this number of log lines from the end of the logs, specify as an integer or all to output all log lines.
- Return type
Union
[str
,AsyncIterator
[str
]]
Swarm¶
Reference¶
DockerSwarm¶
- class aiodocker.swarm.DockerSwarm(docker)[source]¶
- coroutine init(self, *, advertise_addr=None, listen_addr='0.0.0.0:2377', force_new_cluster=False, swarm_spec=None)[source]¶
Initialize a new swarm.
- Parameters
ListenAddr – listen address used for inter-manager communication
AdvertiseAddr – address advertised to other nodes.
ForceNewCluster – Force creation of a new swarm.
SwarmSpec – User modifiable swarm configuration.
- Return type
- Returns
id of the swarm node
- coroutine join(self, *, remote_addrs, listen_addr='0.0.0.0:2377', join_token, advertise_addr=None, data_path_addr=None)[source]¶
Join a swarm.
- Parameters
listen_addr (
str
) – Used for inter-manager communicationadvertise_addr (
Optional
[str
]) – Externally reachable address advertised to other nodes.data_path_addr (
Optional
[str
]) – Address or interface to use for data path traffic.remote_addrs (
Iterable
[str
]) – Addresses of manager nodes already participating in the swarm.join_token (
str
) – Secret token for joining this swarm.
- Return type
Volumes¶
Reference¶
DockerVolumes¶
DockerVolume¶
Tasks¶
Reference¶
DockerTasks¶
- class aiodocker.tasks.DockerTasks(docker)[source]¶