docker / docker-py

A Python library for the Docker Engine API
https://docker-py.readthedocs.io/
Apache License 2.0
6.85k stars 1.67k forks source link

Document way to create a container with a network with links. #2324

Open cglewis opened 5 years ago

cglewis commented 5 years ago

I'm currently unable to find any documentation on a way to create and start a container that is connected to a specific network (not the default bridge) and uses links without first creating the container on the default bridge, then connecting the container to the network with the links necessary and then disconnecting it from the default bridge. I'd like to be able to create a container and attach it directly to the specified network with links without ever attaching it or removing it from the default bridge.

Here's an example of what I'm doing:

docker network create foo
docker run -it --name=alpine --network=foo alpine

>>> import docker
>>> c = docker.from_env()
>>> c.containers.run('bfirsh/reticulate-splines', detach=True)
>>> c.networks.list()
>>> foo = c.networks.list(names=['foo'])
>>> foo[0].connect('inspiring_montalcini', links=[('alpine', 'alpine')])
>>> bridge = c.networks.list(names=['bridge'])
>>> bridge[0].disconnect('inspiring_montalcini')

Which works, but ideally I'd like to be able to specify the network with links in the containers.run command so the container doesn't first have to exist on the wrong network (default bridge) and then later get removed from it.

shin- commented 5 years ago

We have a short explanation of this in the docs for create_container, though I'll admit it's a bit buried. And at a glance, it seems the functionality is also missing from the high-level API, so we'll need to fix that. In the meantime, you'll want to do the following:

import docker

c = docker.from_env()
networking_config = c.api.create_networking_config({
    'foo': c.api.create_endpoint_config(
        links=[('alpine', 'alpine')]
    )
})

container_id = c.api.create_container(
  'bfirsh/reticulate-splines', 
  detach=True, 
  networking_config=networking_config
)
container = c.containers.get(container_id)
container.start()