docker / docker-py

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

Fail to assign staticip along with portmapping to container using docker-py #2355

Open gururajsrk opened 5 years ago

gururajsrk commented 5 years ago

Hi,

I have issue and could not find solution regarding this Use case: Trying to assign a static ip from a network to a container and same ip has to be used for portmapping to host network I am able to achieve this from binary but not from docker.py library

      docker run -it --name container --net radio --ip 172.21.0.20  -p 192.168.0.13:5554:5554/udp  imagename

in code I am creating container

              key=("%s/%s" % (self.port,self.protocol))
              cportmapping = { key  : (self.ip, self.port)}   # {  '5554/udp' : (192.168.0.13,5554)}
              argd['ports']=self.cportmapping
              argd['network'] = self.cnetwork  (network = radio)
              container=self.client.containers.create(self.cimagename,detach=True,**argd)
              network.connect(containerid,ipv4_address=self.networkstaticip) (networkstaticip =172.21.0.21)

Even though i have provided a static ip, it wont use this static called using connect(). It only assigns random ip provided from network radio pool. Can someone help me on this

shin- commented 5 years ago

You can either:

  1. Pass the networking configuration in your container creation call.
  2. Disconnect, then reconnect the network with the proper configuration.

Number 2 will obviously cause a short network blip. To do number 1, you'll have to circumvent the high-level implementation which currently doesn't give you that flexibility (it's something we need to fix).

nconf = self.client.api.create_networking_config({
    'radio': self.client.api.create_endpoint_config(
        ipv4_address='172.21.0.21',
    )
})
container_id = self.client.api.create_container(
  self.cimagename, detach=True, networking_config=nconf,
  **self.client.containers._create_container_args(argd)
)
container = self.client.containers.get(container_id)
# no need to call network.connect anymore

Check out the APIClient.create_container docs for more info.

gururajsrk commented 5 years ago

Hi,

**self.client.containers._create_container_args(argd) is failing with AttributeError: 'ContainerCollection' object has no attribute '_create_container_args'

Any how network.disconnect() method worked. After this I am able to call connect() and it worked.

shin- commented 5 years ago

My bad, it isn't actually a method of client.containers, but a function in docker.models.containers.