首页 > 解决方案 > aiodocker async creation of the container

问题描述

I have been going through the aiodocker library.

And the documentation indicated that they watch the python-asyncio tag. So I wanted to ask about how to async my docker code, as I could not figure out from the documentation and the source code. Here is the code that I need to async (detach=True below won't work because sometimes the container exits with a non-zero status code. Having them asynchronous would help me with handling this better.):

import docker


def synchronous_request(url):
    client = docker.from_env()

    local_dir = '/home/ubuntu/git/docker-scraper/data'
    volumes = {local_dir: {'bind': '/download/', 'mode': 'rw'}}
    environment = {'URL': url}

    client.containers.run('wgettor:latest', auto_remove=True, volumes=volumes, environment=environment)

My attempt, with aiodocker is:

import aiodocker

async def make_historical_request(url):

    docker = await aiodocker.Docker()
    client = await aiodocker.DockerContainers(docker)

    local_dir = '/home/ubuntu/git/docker-scraper/data'
    volumes = {local_dir: {'bind': '/download/', 'mode': 'rw'}}
    environment = {'URL': url}

    await client.run(config={"auto_remove": "True",
                             "volumes": volumes,
                             "environment": environment}, name="wgettor:latest")

Would appreciate if you could show me how to do it properly.

Trying to achieve something like this (the below won't work concurrently):

import docker
import asyncio
from collections import namedtuple

URL = namedtuple('URL', 'val')

URLs = (
    URL('https://www.google.com'),
    URL('https://www.yahoo.com')
)

client = docker.from_env()
local_dir = '/home/ubuntu/git/docker-scraper/data-test'
volumes = {local_dir: {'bind': '/download/', 'mode': 'rw'}}


async def run_container(client, volumes, environment, *, pid):
    print("Starting the container on pid: {}".format(pid))
    return client.containers.run('wgettor:latest', auto_remove=True, detach=True,
                                 volumes=volumes, environment=environment)


async def make_historical_request(url, *, pid):
    print("Starting the retrieval of: {}, on pid: {}".format(url, pid))
    environment = {'URL': url}
    return await run_container(client, volumes, environment, pid=pid)


async def main():
    tasks = [asyncio.ensure_future(make_historical_request(url.val, pid=ix)) for ix, url in enumerate(URLs)]
    await asyncio.wait(tasks)


if __name__ == '__main__':
    asyncio.run(main())

With the help of Freund Alleind, I believe it should be something like this:

async def run_container(docker, url):

    config = {
        'Env': ["URL="+url],
        'HostConfig': {
            'Binds': local_dir + ":" + "/download/"
        }
    }

    try:
        await asyncio.sleep(random.random() * 0.001)
        container = await docker.containers.create_or_replace(
            config=config,
            name="wgettor:latest",
        )
        await container.start()
        await container.kill()
        return url
    except DockerError as err:
        print(f'Error starting wgettor:latest, container: {err}')

async def main():
    start = time.time()
    docker = Docker()
    futures = [run_container(docker, url) for url in URLs]
    # futures = [fetch_async(i) for i in range(1, MAX_CLIENTS + 1)]
    for i, future in enumerate(asyncio.as_completed(futures)):
        result = await future
        print('{} {}'.format(">>" * (i + 1), result))

    print("Process took: {:.2f} seconds".format(time.time() - start))

标签: python-3.xdockerpython-asyncio

解决方案


async def run_container(client, volumes, environment, *, pid):
    print('Starting the container on pid: {}'.format(pid))
    return client.containers.run(..)

This function definetly must do await.
(Update) Try something like this:

import aiodocker

async def run_container(docker, name, config):
    try:
        container = await docker.containers.create_or_replace(
            config=config,
            name=name,
        )
        await container.start()
        return container
    except DockerError as err:
        print(f'Error starting {name} container: {err}')

You should create docker as

from aiodocker import Docker
docker = Docker()
config = {}
loop.run_until_complete(run_container(docker, ..., config)

After some research of Engine API I can say, that if you want to mount some volume, you can use such config:

config = {
            'Image': 'imagename',
            'HostConfig': {'Binds':['/local_path:/container_path']},
        }

推荐阅读