Coder Social home page Coder Social logo

docker / docker-py Goto Github PK

View Code? Open in Web Editor NEW
6.7K 194.0 1.7K 5.01 MB

A Python library for the Docker Engine API

Home Page: https://docker-py.readthedocs.io/

License: Apache License 2.0

Python 99.29% Makefile 0.46% Shell 0.11% Dockerfile 0.14%
python docker docker-engine-api python-library docker-swarm

docker-py's Introduction

Docker SDK for Python

Build Status

A Python library for the Docker Engine API. It lets you do anything the docker command does, but from within Python apps โ€“ run containers, manage containers, manage Swarms, etc.

Installation

The latest stable version is available on PyPI. Install with pip:

pip install docker

Older versions (< 6.0) required installing docker[tls] for SSL/TLS support. This is no longer necessary and is a no-op, but is supported for backwards compatibility.

Usage

Connect to Docker using the default socket or the configuration in your environment:

import docker
client = docker.from_env()

You can run containers:

>>> client.containers.run("ubuntu:latest", "echo hello world")
'hello world\n'

You can run containers in the background:

>>> client.containers.run("bfirsh/reticulate-splines", detach=True)
<Container '45e6d2de7c54'>

You can manage containers:

>>> client.containers.list()
[<Container '45e6d2de7c54'>, <Container 'db18e4f20eaa'>, ...]

>>> container = client.containers.get('45e6d2de7c54')

>>> container.attrs['Config']['Image']
"bfirsh/reticulate-splines"

>>> container.logs()
"Reticulating spline 1...\n"

>>> container.stop()

You can stream logs:

>>> for line in container.logs(stream=True):
...   print(line.strip())
Reticulating spline 2...
Reticulating spline 3...
...

You can manage images:

>>> client.images.pull('nginx')
<Image 'nginx'>

>>> client.images.list()
[<Image 'ubuntu'>, <Image 'nginx'>, ...]

Read the full documentation to see everything you can do.

docker-py's People

Contributors

aanand avatar aiordache avatar akx avatar bfirsh avatar chris-crone avatar denibertovic avatar dependabot[bot] avatar dnephin avatar feliperuhland avatar funkyfuture avatar hannseman avatar ibuildthecloud avatar little-dude avatar milas avatar mnowster avatar mpetazzoni avatar nir0s avatar phensley avatar ricobl avatar riedel avatar rumpl avatar rycus86 avatar shin- avatar skazza94 avatar tarnfeld avatar terminalmage avatar thajeztah avatar tomastomecek avatar ulyssessouza avatar yukw777 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

docker-py's Issues

WorkingDir not yet implemented

Not entirely sure - but it seems to me that the WorkingDir flag is not yet implemented? Did I miss something? Let me know if this is the case - I can write a fix and submit it.

Port does not work with 0.6.5

I just upgraded to docker-py==0.2.2 and docker 0.6.5. Also, I'm using the API version 1.4.

port was working fine for me but after upgrading it does not seem to work anymore.

Here is the error I am getting:

    return self.docker_client.port(container, self.ide_private_port)
  File "/home/ulises/.virtualenvs/dev/local/lib/python2.7/site-packages/docker/client.py", line 381, in port
    if s_port in json_['NetworkSettings']['PortMapping']['Udp']:
TypeError: 'NoneType' object has no attribute '__getitem__'

I'm using EXPOSE 8787 in my Dockerfile and I'm expecting it to map to random port in the host. This is json_'s value:

{u'SysInitPath': u'/usr/bin/docker', u'HostsPath': u'/var/lib/docker/containers/654a73a6fd22b6b534534a3c4919b49f406cfd216d5fe5079c66e69534046278/hosts', u'Created': u'2013-10-31T14:11:56.317615965-04:00', u'Image': u'8f4a20d3fe1ff24a58acf7c89506a65712f22a53df24547c25310e6228e11312', u'Args': [u'start_rstudio.sh'], u'VolumesRW': {}, u'State': {u'Ghost': False, u'Pid': 9459, u'Running': True, u'FinishedAt': u'0001-01-01T00:00:00Z', u'StartedAt': u'2013-10-31T14:11:56.363551522-04:00', u'ExitCode': 0}, u'ResolvConfPath': u'/var/lib/docker/containers/654a73a6fd22b6b534534a3c4919b49f406cfd216d5fe5079c66e69534046278/resolv.conf', u'Volumes': {}, u'Path': u'/bin/bash', u'HostnamePath': u'/var/lib/docker/containers/654a73a6fd22b6b534534a3c4919b49f406cfd216d5fe5079c66e69534046278/hostname', u'Config': {u'Env': [u'HOME=/', u'PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'], u'Hostname': u'654a73a6fd22', u'Dns': None, u'Entrypoint': [u'/bin/bash', u'start_rstudio.sh'], u'PortSpecs': None, u'Memory': 0, u'Privileged': False, u'OpenStdin': False, u'User': u'', u'AttachStderr': True, u'AttachStdout': True, u'NetworkDisabled': False, u'StdinOnce': False, u'Cmd': [], u'WorkingDir': u'', u'AttachStdin': False, u'Volumes': None, u'MemorySwap': 0, u'VolumesFrom': u'', u'Tty': False, u'CpuShares': 0, u'Domainname': u'', u'Image': u'8f4a20d3fe1f', u'ExposedPorts': {u'8787/tcp': {}}}, u'ID': u'654a73a6fd22b6b534534a3c4919b49f406cfd216d5fe5079c66e69534046278', u'NetworkSettings': {u'Bridge': u'docker0', u'PortMapping': None, u'Gateway': u'172.17.42.1', u'IPPrefixLen': 16, u'IPAddress': u'172.17.0.19', u'Ports': {u'8787/tcp': None}}, u'Name': u'/green_whale4'}

Note: I'm not using sudo since I've added my account to the docker group

Here is what docker ps returns for the container, notice the PORTS column

ID                  IMAGE                                         COMMAND                CREATED             STATUS              PORTS               NAMES
627ed729affe        name-527292a9637aba40d68bd75f:latest   /bin/bash start_rstu   19 seconds ago      Up 18 seconds       8787/tcp            orange_pig6         

How can I expose that 8787 port?

PS: Thank you very much for this wonderful project. It's been a lot of fun (and useful) working with docker and this API. Thanks!

Can't create and bind mounts

Debugging the go client I've found out the combination it uses to bind mounts in the container to the host.

Here is the command of the docker command-line client:

docker run -b "/host/path:/mnt" image-name ls /mnt

The container must be created with volumes:

container = client.create_container(image_id, command, volumes={'/mnt': {}})

And started binding the volume to the host. Here is a sample code to allow posting json when starting the container (the current implementation of the start method can't do this):

url = client._url("/containers/{0}/start".format(id_do_container))
res = client.post_json(url, {"Binds": ['/host/path:/mnt']}, headers={"Content-Type":"application/json"})

Here is the start api documentation:
http://docs.docker.io/en/latest/api/docker_remote_api_v1.3/#start-a-container

Couldn't find any documentation of the complete procedure for binding a mount.

commit requires Id while stop requires the whole container dictionary

I noticed that stop requires the whole deal:

{u'Command': u'/bin/bash start_rstudio.sh',
 u'Created': 1383311724,
 u'Id': u'f6209d7f6fa3e1d6feba7e94d9e5af4897a55af8e184152c3d655760c410c172',
 u'Image': u'our-repodatarobot/our-image:latest',
 u'Ports': u'49200->8896',
 u'SizeRootFs': 0,
 u'SizeRw': 0,
 u'Status': u'Up 2 minutes'}

While commit requires only the container Id.

Should we update the docs? or better yet, standardize their arguments?

Chunked responses in build aren't properly handled

Happens consistently with the hipache dockerfile. Unsure if something has changed in the latest version of docker or if the problems has been overlooked in docker-py.

  2013-07-24 23:49:20,472 ERROR IncompleteRead(9636 bytes read)
  Traceback (most recent call last):
    File "/home/shin/work/docker/contrib/brew/brew/brew.py", line 77, in build_library
      img = build_repo(url, ref, buildfile, tag, namespace, push)
    File "/home/shin/work/docker/contrib/brew/brew/brew.py", line 97, in build_repo
      img_id, logs = client.build(path=dst_folder)
    File "/usr/local/lib/python2.7/dist-packages/docker/client.py", line 148, in build
      headers=headers))
    File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 377, in post
      return self.request('POST', url, data=data, **kwargs)
    File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 335, in request
      resp = self.send(prep, **send_kwargs)
    File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 438, in send
      r = adapter.send(request, **kwargs)
    File "/usr/local/lib/python2.7/dist-packages/requests/adapters.py", line 340, in send
      r.content
    File "/usr/local/lib/python2.7/dist-packages/requests/models.py", line 594, in content
      self._content = bytes().join(self.iter_content(CONTENT_CHUNK_SIZE)) or bytes()
    File "/usr/local/lib/python2.7/dist-packages/requests/models.py", line 541, in generate
      chunk = self.raw.read(chunk_size, decode_content=True)
    File "/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/response.py", line 171, in read
      data = self._fp.read(amt)
    File "/usr/lib/python2.7/httplib.py", line 543, in read
      return self._read_chunked(amt)
    File "/usr/lib/python2.7/httplib.py", line 597, in _read_chunked
      raise IncompleteRead(''.join(value))
  IncompleteRead: IncompleteRead(9636 bytes read)

Support docker cli style syntax

With 0.6.5 a number of changes were introduced to the remote api.

Amongst other things 'create' and 'port' now need to receive a struct for creating a mappable volume, port respectively.

It looks something like the following... I understand why the api is like this, but in python this is just hard to understand, read and write.

["/volume": {}]
and
'{"PortBindings": { "22/tcp": [{ "HostPort": "11022" }]} }'

If we would make the syntax docker-py understands similar to the cli it will be much easier to write.

# create:
volumes=["/volume1", "/volume2"] 
ports = ["22", "80", "123"]

# start:
volumes=["/volume1:/target/volume1", /volume2:/target/volume2"]
ports = ["127.0.0.1:2200:22","80", "127.0.0.1:6001:123/udp"] 

If we agree on that this is desirable, I might give a throw at it this weekend. But others are also free to pick it up.

Getting invalid docker format on line "D"

Works fine with docker build.

Here's the dockerfile in question

from keeb/blog

ADD . /website
RUN apt-get install -y python-setuptools
RUN easy_install pip
RUN pip install -r /website/requirements.txt

CMD ["python", "website/app.py"]

My guess is that it's the CMD portion.

Provide a Mock implementation

Any usage of docker-py requires unit testing. The latter requires a Fake client that does not require a docker daemon to be running. Providing a mock implementation will avoid every single user to re-implement its own mock.

This is a nice to have.

data parameter of import_image

Currently, there's data parameter in import_image:

def import_image(self, src, data=None, repository=None, tag=None)

but seems like it's not used as it gets assigned right away:

try:
        # XXX: this is ways not optimal but the only way
        # for now to import tarballs through the API
        fic = open(src)
        data = fic.read()
        fic.close()
        src = "-"
except IOError:
        # file does not exists or not a file (URL)
        data = None

and it's not even in the documentation. Should this 'data' parameter be removed?

Provide more useful Ports data in Client.containers() output

When calling Client.containers() the return value for Ports is a string that looks like:

u'Ports': u'5000->5000, 6000->6000'

For programmatic consumption, the value would be much more useful as a sequence of (public_port, private_port) tuples, like:

u'Ports': ((5000, 5000), (6000, 6000))

Thoughts?

Upgrading to requests 2.0.1

I know 1.2.3 was released only half a year ago, looking at the change log, 2.0.1 seems to include many important changes. Any plan to upgrade to requests 2.0.1?

Push(stream=True) does not work anymore.

$ cat test.py 
import docker

c = docker.Client()
for line in c.push("test_image", stream=True):
    print line
$ sudo venv/bin/python test.py 
Traceback (most recent call last):
  File "test.py", line 4, in <module>
    for line in c.push("test_image", stream=True):
  File "/home/{username}/docker-py/docker/client.py", line 230, in _stream_helper
    size = int(socket.readline(), 16)
IOError: [Errno 11] Resource temporarily unavailable

I suspect #117 or #123 broke this. Seems like it's a blocking vs nonblocking socket issue.

Failure to import requests.packages.urllib3.connectionpool

With requests 1.2.3 (the version which gets installed), this happens.

Workaround: use requests 1.2.0.

$ pip install --user docker-py
Downloading/unpacking docker-py
  Downloading docker-py-0.1.5.tar.gz
  Running setup.py egg_info for package docker-py

Requirement already satisfied (use --upgrade to upgrade): requests in /usr/lib/python2.7/dist-packages (from docker-py)
Requirement already satisfied (use --upgrade to upgrade): six in /usr/lib/python2.7/dist-packages (from docker-py)
Installing collected packages: docker-py
  Running setup.py install for docker-py

Successfully installed docker-py
Cleaning up...
pwaller@fractal:~$ ipython
imporPython 2.7.5+ (default, Jun  5 2013, 10:40:07) 
Type "copyright", "credits" or "license" for more information.

IPython 1.1.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import docker
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-1-3ac1c348f58a> in <module>()
----> 1 import docker

/home/pwaller/.local/lib/python2.7/site-packages/docker/__init__.py in <module>()
----> 1 from .client import Client

/home/pwaller/.local/lib/python2.7/site-packages/docker/client.py in <module>()
     15 from requests.exceptions import HTTPError
     16 from requests.adapters import HTTPAdapter
---> 17 from requests.packages.urllib3.connectionpool import HTTPConnectionPool
     18 
     19 if six.PY3:

ImportError: No module named packages.urllib3.connectionpool

In [2]: 

Support for links

Hi. I'm about to start work on adding support for links to docker-py, but wanted to check that you're not already working on it.

At minimum (and having not yet familiarised myself with the changes to the remote API, so I might be laying my ignorance bare here), I imagine this will involve:

  • a client.link() method
  • a link argument to create_container

Sound good?

Support inserting data into running containers

Hi

I'm trying to replicate the following command using the docker-py api. I understand that the -a option is not supported. Do you have any suggestions for achieving the same result?

cat myapp.tar | docker run -i -a stdin progrium/buildstep /bin/bash -c "mkdir -p /app && tar -xC /app"

Thanks in advance!

0.5.0 portspec changes break client.port() resulting in KeyError

Traceback (most recent call last):
  File "test.py", line 4, in <module>
    print c.port('9f9500d4f2fd', '8080')
  File "/home/keeb/development/docker-py/docker/client.py", line 287, in port
    return json_['NetworkSettings']['PortMapping'][str(private_port)]
KeyError: '8080'

pull response a little weird

pull returns a string that's a contamination of one or more JSON strings.

Wouldn't it make more sense to return either that last status as a dict, or a list of status dicts?

No error is raised when attempting to remove a running docker container

Currently, attempting to remove a running docker container returns None, like in this example:

>>> import docker
>>> client = docker.Client()
>>> containers = [x.get('Id') for x in client.containers()]
>>> client.remove_container(containers[1])
>>>

However, when you run docker rm at the command line, you get the following error:

$ docker rm 433b3157633f
Error: Impossible to remove a running container, please stop it first

I think that the docker-py module should expose this error, either through a returned JSON object or with something more Pythonic like an exception (ValueError, perhaps?).

Images not tagged when builded through docker-py

This is my use of docker-py:

docker_client = docker.Client(base_url='url_to_registry_server:4243', version='1.3')
match, res = docker_client.build(path=build_path, tag='url_to_registry_server/%s' % tag)

The building is all right, but the image added to the registry has a "" TAG and REGISTRY value when i do a docker ps on the registry server.

Versions:
docker-py = 0.1.4

Client version: 0.5.0
Server version: 0.5.0
Go version: go1.1

I post this issue on 'keeb' s advice on the IRC channel.

Possible tests refactoring

Currently the tests take way too long to execute. Would it be prudent to Mock out the API calls to the docker REST API?

This would, however imply that we would need to maintain those mocked API responses and update them accordingly as the REST API is updated but it would really cut down the run time of the tests.

I'm thinking this would be a good idea as we should not really be testing, for instance, if a given container is created/started but rather do we get a good response from the API and how we handle godd/bad responses in the client.

It might also be vise to have a set of tests that do in fact call the real API (integration tests of sorts) but then those would not need to be run every time during development but rather only before merging or something like that. This step is really optional, and I'm not really sure it's needed yet.

Also, if the API is mocked out we could set up Travis or something of the sorts.

What are your thoughts on this?

create_container should document the required format for the command to run

When I ran the following code I expected a container to be up running sshd.

client = Client() client.create_container(image='base', command='/usr/sbin/sshd -D')

Unfortunately the command actually had to be an array of strings so that docker could run the command properly in the container. So I had to change to:

client = Client() client.create_container(image='base', command=['/usr/sbin/sshd', '-D'])

This could be solved by documenting this better.

feature request: docker build support -dns and -e for corporate network environments

Corporate networks will disable external dns lookups. If the build command supported -dns, then building docker images would be much easier inside corporate networks.

Corporate networks will force all network traffic through a network proxy, supporting the -e option allows for the build command to use http_proxy and https_proxy env settings to enable building the image.

Add documentation for naming containers

Currently there is no mention of how to name a container in the documentation (README.md),

I did find it has been implemented in docker-py and works as expected.

inconsistant api for environment and bind mount arguments

When passing environment variable arugments to the create_container method, they must be formatted as a list of strings formatted like "{0}={1}", but the new bind mount takes a dict and does the split inside the create_container method. There should be a consistent API for key/value pairs.

Not compatible with python 2.7

When I try to run the create_container command, I get an error:

/usr/local/lib/python2.7/dist-packages/docker/client.pyc in create_container(self, image, command, hostname, user, detach, stdin_open, tty, mem_limit, ports, environment, dns, volumes, volumes_from)
    184             detach, stdin_open, tty, mem_limit, ports, environment, dns,
    185             volumes, volumes_from)
--> 186         return self.create_container_from_config(config)
    187 
    188     def create_container_from_config(self, config):

/usr/local/lib/python2.7/dist-packages/docker/client.pyc in create_container_from_config(self, config)
    192             raise ValueError("{0} is an unrecognized image. Please pull the "
    193                 "image first.".format(config['Image']))
--> 194         return self._result(res, True)
    195 
    196     def diff(self, container):

/usr/local/lib/python2.7/dist-packages/docker/client.pyc in _result(self, response, json)
     44             self._raise_for_status(response)
     45         if json:
---> 46             return response.json()
     47         return response.text
     48 

TypeError: 'dict' object is not callable

Works fine under python 3.3.

Client.stop/start/restart issues

Currenty the start/stop/restart methods work on the premise that a container ID, or rather a list of container IDs, are passed to it. I have a couple of issues with this.

  1. The fact that you can pass a list of ids isn't really documented that well (i found that out looking at the code). Granted the restart and stop commands do mention 'containers' (plural) in the docs example but the start command doesn't.
  2. It's rather inconsistent that create_container returns a dict {'Id': '123123'} and not just the id. Also why the capital I in id?

So i tried passing that dict to the start/stop commands and nothing happened (it failed silently).

The way I see it there are a couple of options:

  1. Start/stop/restart, given that create_container returns a dict, should accept that dict (or list of dicts), extract the id and start/stop/restart the container anyway (Guard against just passing a list of strings).
  2. The commands should check if they got a string, or list of string, and blow up otherwise...but then i think create_container should return just a string.
  3. The commands should accept either a string or dict, or list of strings or a list of dicts and just work(tm) either way

And also the docs should be updated accordingly to reflect this and make it more clear. Either way i think input should be checked somehow and either blow up or something. A silent failure is not an option.

Anyway, I'm available to help with this. But I wanted to discuss what ppl think is best?

docker-py doesn't work with Docker 0.5.2 default configuration

Due to the change in Docker 0.5.2 where the Docker daemon only listens on a unix socket, docker-py no longer works out of the box. You can re-enable the network binding of the Docker daemon but if the docker-py client is on the same host then that shouldn't really be necessary. It's not clear to me if the requests library supports the ability to make HTTP requests over unix sockets.

using lxc_conf in start

How do I use lxc_conf in start?

I'd like to set cpu and cpu shares, something like this:

docker run -i -t -lxc-conf="lxc.cgroup.cpu.shares=1" -lxc-conf="lxc.cgroup.cpuset.cpus=0" my_image /bin/bash stress_cpu.sh

According to the documentation I should be able to pass a dictionary:

lxc_conf allows to pass LXC configuration options in dict form.

So my code looks like this:

self.client.start(container, lxc_conf = self.get_lxc_conf())
def get_lxc_conf(self):        
  return {
  #Restrict container to a core
  'lxc.cgroup.cpuset.cpus' : str(self.cpu_number), 
  #All containers get the same share
  'lxc.cgroup.cpu.cpu.shares' : str(1) 
}

However, I can't get it work, I keep getting the following error message:

500 Server Error: Internal Server Error ("json: cannot unmarshal object into Go value of type []docker.KeyValuePair")

I get the same error even with the dictionary example in the API docs:

def get_lxc_conf(self):
    return {"lxc.utsname":"docker"}

I've tried passing lists and strings

Thanks!

running start more than once causes binds to be broken

I'm not sure if this should be reported here or on docker itself. Therefore I start here.

If I start a container using docker-py (in proxy the remote API) with some ports exposed and then start the container again (is was already running) (by container id), with the same ports exposed it will actually drop the ports. See output below.

The docker cli doesn't show this issue because it doesn't allow starting a running container.

effect -> Running start multiple times can now ruin your running containers.

(runner)thatcher@blue1:~/Develop/runner$ ./runner.py testports.yml 
processing sshd-sample
s_ports =  {'22/tcp': [{'HostPort': '', 'HostIp': ''}]}

(runner)thatcher@blue1:~/Develop/runner$ docker ps
CONTAINER ID        IMAGE                  COMMAND                CREATED             STATUS              PORTS                                          NAMES
3cf76a25a0ab        dhrp/sshd:latest       /usr/sbin/sshd -D      2 seconds ago       Up 2 seconds        0.0.0.0:49155->22/tcp                          blue_cat            

(runner)thatcher@blue1:~/Develop/runner$ vi testports.yml 
(runner)thatcher@blue1:~/Develop/runner$ ./runner.py testports.yml 
processing sshd-sample # by container id
s_ports =  {'22/tcp': [{'HostPort': '', 'HostIp': ''}]}
500 Server Error: Internal Server Error ("Cannot start container 3cf76a25a0ab: The container 3cf76a25a0ab99945db5a15b44f22b3469d3e6e6aac11755667fde148b75fb1b is already running.")

(runner)thatcher@blue1:~/Develop/runner$ docker ps
CONTAINER ID        IMAGE                  COMMAND                CREATED             STATUS              PORTS                                          NAMES
3cf76a25a0ab        dhrp/sshd:latest       /usr/sbin/sshd -D      51 seconds ago      Up 51 seconds                                                      blue_cat            

'UnixHTTPConnectionPool' object has no attribute 'strip'

When installing docker-py using python setup.py install, it gets the latest versions of the dependencies. For requests it fetches 2.0.0, while it seems the code targets 1.2.0 (which is frozen in requirements.txt for pip install).

Versions should probably also be constrained for setup.py based install.

Upgrade to requests 2.0.1 (or newer)

Could docker-py be updated to be compatible with python-requests 2.0.1?

I'm getting this error: AttributeError: 'UnixHTTPConnectionPool' object has no attribute 'strip'

traceback:

File "/usr/lib/python2.7/site-packages/docker/client.py", line 314, in info
            return self._result(self.get(self._url("/info")), True)
          File "/usr/lib/python2.7/site-packages/requests/sessions.py", line 373, in get
            return self.request('GET', url, **kwargs)
          File "/usr/lib/python2.7/site-packages/requests/sessions.py", line 361, in request
            resp = self.send(prep, **send_kwargs)
          File "/usr/lib/python2.7/site-packages/requests/sessions.py", line 464, in send
            r = adapter.send(request, **kwargs)
          File "/usr/lib/python2.7/site-packages/requests/adapters.py", line 296, in send
            conn = self.get_connection(request.url, proxies)
          File "/usr/lib/python2.7/site-packages/docker/unixconn/unixconn.py", line 65, in get_connection
            return UnixHTTPConnectionPool(self.base_url, socket_path)
          File "/usr/lib/python2.7/site-packages/docker/unixconn/unixconn.py", line 53, in __init__
            super(UnixHTTPConnectionPool, self).__init__(self, 'localhost')
          File "/usr/lib/python2.7/site-packages/requests/packages/urllib3/connectionpool.py", line 144, in __init__
            ConnectionPool.__init__(self, host, port)
          File "/usr/lib/python2.7/site-packages/requests/packages/urllib3/connectionpool.py", line 73, in __init__
            host = host.strip('[]')
        AttributeError: 'UnixHTTPConnectionPool' object has no attribute 'strip'

Sanitize base_url

I spent ages trying to find out why all non-GET operations were failing. It turns out I had an extra slash (/) at the end of the base_url passed into Client().

So I entered c = Client("http://myhost.com/") instead of c = Client("http://myhost.com").

The traceback was not very clear:

In [19]: c.remove_image('aabd9dfce66d689928f028253970ccf1b35cfe9d4375d266414c4ef5e0bdcac4')
---------------------------------------------------------------------------
APIError                                  Traceback (most recent call last)
<ipython-input-19-bb4d163bc668> in <module>()
----> 1 c.remove_image('aabd9dfce66d689928f028253970ccf1b35cfe9d4375d266414c4ef5e0bdcac4')

docker/client.pyc in remove_image(self, image)
    567     def remove_image(self, image):
    568         res = self._delete(self._url("/images/" + image))
--> 569         self._raise_for_status(res)
    570
    571     def restart(self, container, timeout=10):

docker/client.pyc in _raise_for_status(self, response, explanation)
    103             response.raise_for_status()
    104         except requests.exceptions.HTTPError as e:
--> 105             raise APIError(e, response, explanation=explanation)
    106
    107     def _stream_result(self, response):

<type 'str'>: (<type 'exceptions.AttributeError'>, AttributeError("'NoneType' object has no attribute 'status_code'",))

Only by looking at the access logs on the docker machine I saw that all requests were being redirected with a 301 (Moved Permanently):

10.33.33.1 - dockerapi [23/Nov/2013:00:51:11 +0000] "DELETE //v1.6/images/aabd9dfce66d689928f028253970ccf1b35cfe9d4375d266414c4ef5e0bdcac4 HTTP/1.1" 301 0 "-" "python-requests/1.2.3 CPython/2.7.5 Darwin/12.5.0"
10.33.33.1 - dockerapi [23/Nov/2013:00:51:11 +0000] "GET /v1.6/images/aabd9dfce66d689928f028253970ccf1b35cfe9d4375d266414c4ef5e0bdcac4 HTTP/1.1" 404 19 "-" "python-requests/1.2.3 CPython/2.7.5 Darwin/12.5.0"

This worked for GET requests, but other request types failed.

My suggestion would be to sanitize base_url through urlparse or always use urljoin to join base_url and the rest of the url.

Volumes parameter on function create_container

Hi,

I'm trying to create a container with volumes param. Here is the code:

import docker
c = docker.Client(base_url='unix://var/run/docker.sock')
c.create_container('ubuntu', ..., volumes={"/root/data": "/root/data"})

And the traceback is:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/docker/client.py", line 235, in create_container
return self.create_container_from_config(config)
File "/usr/local/lib/python2.7/dist-packages/docker/client.py", line 243, in create_container_from_config
return self._result(res, True)
File "/usr/local/lib/python2.7/dist-packages/docker/client.py", line 82, in _result
self._raise_for_status(response)
File "/usr/local/lib/python2.7/dist-packages/docker/client.py", line 79, in _raise_for_status
raise APIError(e, response=response, explanation=explanation)
docker.client.APIError: 500 Server Error: Internal Server Error ("json: cannot unmarshal string into Go value of type struct {}")

Would you help me? Thanks...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.