簡體   English   中英

使用docker python API鏈接容器

[英]link containers with the docker python API

我想使用docker python API( pip install docker-py )創建一個容器並將其鏈接到我用docker-compose創建的現有容器。

使用命令行很容易:

docker run --link EXISTING_CONTAINER:LINK_NAME mycontainer:mytag

但是使用docker API我就陷入了困境。 我認為我必須使用docker.Client().create_container()方法,它采用docker.Client().create_container() - 參數links= (我強烈認為文檔非常不完整......)。

我試着閱讀docker-compose代碼,這似乎使用了links=參數,但我無法弄清楚如何。

我最初的嘗試不起作用:

client_obj.create_container(..., links=(('EXISTING_CONTAINER', 'LINK_NAME'),))

...這就是我認為docker-compose代碼正在做的事情。

有人可以幫幫我嗎?

https://github.com/docker/docker-py

Docker Remote API的Python庫。 它執行docker命令所做的一切,但是從Python內部運行容器,管理它們,拉/推圖像等。

create_container

Creates a container that can then be .start() ed. 
Parameters are similar to those for the docker run 
command except it doesn't support the attach options (-a).

create_container源代碼

def create_container(self, image, command=None, hostname=None, user=None,
                     detach=False, stdin_open=False, tty=False,
                     mem_limit=None, ports=None, environment=None,
                     dns=None, volumes=None, volumes_from=None,
                     network_disabled=False, name=None, entrypoint=None,
                     cpu_shares=None, working_dir=None, domainname=None,
                     memswap_limit=None, cpuset=None, host_config=None,
                     mac_address=None, labels=None, volume_driver=None,
                     stop_signal=None, networking_config=None):

但我在啟動功能中找到了links

def start(self, container, binds=None, port_bindings=None, lxc_conf=None,
          publish_all_ports=None, links=None, privileged=None,
          dns=None, dns_search=None, volumes_from=None, network_mode=None,
          restart_policy=None, cap_add=None, cap_drop=None, devices=None,
          extra_hosts=None, read_only=None, pid_mode=None, ipc_mode=None,
          security_opt=None, ulimits=None):

所以我認為你應該:

from docker import Client
>>> cli = Client(base_url='tcp://127.0.0.1:2375')
>>> container = cli.create_container(
...     image='busybox:latest',
...     command='/bin/sleep 30')
>>> response = cli.start(container=container.get('Id'),links=[('EXISTING_CONTAINER', 'LINK_NAME')])

工作實例(DO)

我在DO上使用CoreOS:

  1. 運行docker容器並從主機安裝在/var/run/docker.sock
  2. 安裝工具
  3. 運行測試容器EXISTING_CONTAINER
  4. 運行python示例

命令集:

docker run -it -v /var/run/docker.sock:/var/run/docker.sock ubuntu:12.04 bash
apt-get update;apt-get install python-pip -y;pip install docker-py
docker run -d --name EXISTING_CONTAINER busybox   sh -c "while true; do sleep 1;done"

Python示例

from docker import Client
cli = Client(base_url='unix://var/run/docker.sock', version='auto')
container = cli.create_container(
image='busybox:latest',
command='/bin/sleep 30')
response = cli.start(container=container.get('Id'),links=(('EXISTING_CONTAINER', 'LINK_NAME'))

主持人的結果:

wp-coreos-512mb-ams2-01 ~ # docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
2f58e661579d        busybox             "sh -c 'while true; d"   23 seconds ago      Up 22 seconds                           EXISTING_CONTAINER
6f08dd3f5017        busybox:latest      "/bin/sleep 30"          9 minutes ago       Up 5 seconds                            condescending_brown

是的,docker-py的網絡文檔嚴重缺乏 - 維護者同意( https://github.com/docker/docker-py/issues/982獲取全局別名示例)。

請注意,Valeriy上面的回答將創建一個遺留鏈接,如果您使用非默認網絡(如docker-compose創建的網絡),可能會(在我的情況下)導致問題。

在任何情況下,將參數添加Client.start貶值

可以在unitttest中找到新的方法: https//github.com/docker/docker-py/blob/master/tests/integration/network_test.py#L190-213

@requires_api_version('1.22')
def test_create_with_links(self):
    net_name, net_id = self.create_network()

    container = self.create_and_start(
        host_config=self.client.create_host_config(network_mode=net_name),
        networking_config=self.client.create_networking_config({
            net_name: self.client.create_endpoint_config(
                links=[('docker-py-test-upstream', 'bar')],
            ),
        }),
    )

    container_data = self.client.inspect_container(container)
    self.assertEqual(
        container_data['NetworkSettings']['Networks'][net_name]['Links'],
        ['docker-py-test-upstream:bar'])

    self.create_and_start(
        name='docker-py-test-upstream',
        host_config=self.client.create_host_config(network_mode=net_name),
    )

    self.execute(container, ['nslookup', 'bar'])

Valeriy的例子如下:

Python示例

from docker import Client
cli = Client(base_url='unix://var/run/docker.sock', version='auto')

# Note: 'bridge' is the default network
net_config = cli.create_networking_config(
        {'bridge': self.docker_client.create_endpoint_config(
            links=[('EXISTING_CONTAINER', 'LINK_NAME')]
        )}
    )

container = cli.create_container(
  image='busybox:latest',
  command='/bin/sleep 30',
  network_configuration=net_config 
)
response = cli.start(container=container.get('Id'))

我沒有測試過這個特定的代碼,但這是我能夠將新容器連接到現有容器的方式,而現有的容器是通過組成網絡“project_default”創建的。

您可能還想查看此鏈接以獲取更多信息和背景信息。

以下是目前的工作方式。

links=[('postgres-modeldb', 'modeldb'),('postgres-userdb', 'userdb'),('redis-workerdb', 'workerdb')]

host_config = client.create_host_config(
    links=links
)

networking_config = client.create_networking_config({
    'my-net': client.create_endpoint_config(
        links=links
    )
})

container = client.create_container(
    image='josepainumkal/vwadaptor:jose_toolUI',
    name=container_name,
    host_config=host_config,
    networking_config = networking_config
) 

response = client.start(container=container.get('Id'))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM