An API client for docker written in Python
Our latest stable is always available on PyPi.
pip install docker-py To instantiate a Client class that will allow you to communicate with a Docker daemon, simply do:
c=docker.Client(base_url='unix://var/run/docker.sock', version='1.12', timeout=10)base_url refers to the protocol+hostname+port where the docker server is hosted. version is the version of the API the client will use and timeout specifies the HTTP request timeout, in seconds.
c.build(path=None, tag=None, quiet=False, fileobj=None, nocache=False, rm=False, stream=False, timeout=None, custom_context=False, encoding=None):Similar to the docker build command. Either path or fileobj needs to be set. path can be a local path (to a directory containing a Dockerfile) or a remote URL. fileobj must be a readable file-like object to a Dockerfile.
If you have a tar file for the docker build context (including a dockerfile) already, pass a readable file-like object to fileobj and also pass custom_context=True. If the stream is compressed also, set encoding to the correct value (e.g gzip).
c.commit(container, repository=None, tag=None, message=None, author=None, conf=None)Identical to the docker commit command.
c.containers(quiet=False, all=False, trunc=True, latest=False, since=None, before=None, limit=-1)Identical to the docker ps command.
c.copy(container, resource)Identical to the docker cp command.
c.create_container(image, command=None, hostname=None, user=None, detach=False, stdin_open=False, tty=False, mem_limit=0, ports=None, environment=None, dns=None, volumes=None, volumes_from=None, network_disabled=False, name=None, entrypoint=None, cpu_shares=None, working_dir=None, memswap_limit=0)Creates a container that can then be started. Parameters are similar to those for the docker run command except it doesn't support the attach options (-a). See "Port bindings" and "Using volumes" below for more information on how to create port bindings and volume mappings.
command is the command to be run in the container. String or list types are accepted.
The environment variable accepts a dictionary or a list of strings in the following format ["PASSWORD=xxx"] or {"PASSWORD": "xxx"}.
The mem_limit variable accepts float values (which represent the memory limit of the created container in bytes) or a string with a units identification char ('100000b', 1000k', 128m', '1g'). If a string is specified without a units character, bytes are assumed as an intended unit.
volumes_from and dns arguments raise TypeError exception if they are used against v1.10 of docker remote API. Those arguments should be passed to start() instead.
c.diff(container)Identical to the docker diff command.
c.export(container)Identical to the docker export command.
c.history(image)Identical to the docker history command.
c.images(name=None, quiet=False, all=False, viz=False)Identical to the docker images command.
c.import_image(src, data=None, repository=None, tag=None)Identical to the docker import command. If src is a string or unicode string, it will be treated as a URL to fetch the image from. To import an image from the local machine, src needs to be a file-like object or bytes collection. To import from a tarball use your absolute path to your tarball. To load arbitrary data as tarball use whatever you want as src and your tarball content in data.
c.info()Identical to the docker info command.
c.insert(image, url, path)Identical to the docker insert command.
c.inspect_container(container)Identical to the docker inspect command, but only for containers.
c.inspect_image(image_id)Identical to the docker inspect command, but only for images.
c.kill(container, signal=None)Kill a container. Similar to the docker kill command.
c.login(username, password=None, email=None, registry=None)Identical to the docker login command (but non-interactive, obviously).
c.logs(container, stdout=True, stderr=True, stream=False, timestamps=False)Identical to the docker logs command. The stream parameter makes the logs function return a blocking generator you can iterate over to retrieve log output as it happens.
c.attach(container, stdout=True, stderr=True, stream=False, logs=False)The logs function is a wrapper around this one, which you can use instead if you want to fetch/stream container output without first retrieving the entire backlog.
c.ping()Hits the /_ping endpoint of the remote API and returns the result. An exception will be raised if the endpoint isn't responding.
c.port(container, private_port)Identical to the docker port command.
c.pull(repository, tag=None, stream=False)Identical to the docker pull command.
c.push(repository, tag=None, stream=False)Identical to the docker push command.
c.remove_container(container, v=False, link=False) ``` Removeacontainer. Similartothe`docker rm`command. ```pythonc.remove_image(image) ``` Removeanimage. Similartothe`docker rmi`command. ```pythonc.restart(container, timeout=10) ```Restart a container. Similar to the `dockerrestart` command. ```pythonc.search(term) ``` Identicaltothe`docker search`command. ```pythonc.start(container, binds=None, port_bindings=None, lxc_conf=None, publish_all_ports=False, links=None, privileged=False, dns=None, dns_search=None, volumes_from=None, network_mode=None, restart_policy=None, cap_add=None, cap_drop=None) ``` Similartothe`docker start`command, butdoesn'tsupportattachoptions. Use`docker logs`torecover`stdout`/`stderr`. `binds`allowstobindadirectoryinthehosttothecontainer. See"Using volumes"belowformoreinformation. `port_bindings`exposescontainerportstothehost. See"Port bindings"belowformoreinformation. `lxc_conf`allowstopassLXCconfigurationoptionsusingadictionary. `privileged`startsthecontainerinprivilegedmode. [Links](http://docs.docker.io/en/latest/use/working_with_links_names/) canbespecifiedwiththe`links`argument. Theycaneitherbespecifiedasadictionarymappingnametoaliasorasalistof`(name, alias)`tuples. `dns`and`volumes_from`areonlyavailableiftheyareusedwithversionv1.10ofdockerremoteAPI. Otherwisetheyareignored. `network_mode`isavailablesincev1.11andsetstheNetworkmodeforthecontainer ('bridge': createsanewnetworkstackforthecontaineronthedockerbridge, 'none': nonetworkingforthiscontainer, 'container:[name|id]': reusesanothercontainernetworkstack), 'host': usethehostnetworkstackinsidethecontainer. `restart_policy`isavailablesincev1.2.0andsetstheRestartPolicyforhowacontainershouldorshouldnotberestartedonexit. Bydefaultthepolicyissettonomeaningdonotrestartthecontainerwhenitexits. Theusermayspecifytherestartpolicyasadictionaryforexample: forexample: ```{"MaximumRetryCount": 0, "Name": "always"}```foralwaysrestartingthecontaineronexitorcanspecifytorestartthecontainertorestartonfailureandcanlimitnumberofrestarts. forexample: ```{"MaximumRetryCount": 5, "Name": "on-failure"}````cap_add`and`cap_drop`areavailablesincev1.2.0andcanbeusedtoaddordropcertaincapabilities. Theusermayspecifythecapabilitiesasanarrayforexample: ``` [ "SYS_ADMIN", "MKNOD" ] ``` ```pythonc.stop(container, timeout=10) ``` Stopsacontainer. Similartothe`docker stop`command. ```pythonc.tag(image, repository, tag=None, force=False) ``` Identicaltothe`docker tag`command. ```pythonc.top(container) ``` Identicaltothe`docker top`command. ```pythonc.version() ``` Identicaltothe`docker version`command. ```pythonc.wait(container) ``` Waitforacontainerandreturnitsexitcode. Similartothe `dockerwait` command. Portbindings=============Portbindingsisdoneintwoparts. Firstly, byprovidingalistofportstoopeninsidethecontainerinthe`Client.create_container`method. ```pythonc.create_container('busybox', 'ls', ports=[1111, 2222]) ``` Bindingsarethendeclaredinthe`Client.start`method. ```pythonc.start(container_id, port_bindings={1111: 4567, 2222: None}) ``` Youcanlimitthehostaddressonwhichtheportwillbeexposedlikesuch: ```pythonc.start(container_id, port_bindings={1111: ('127.0.0.1', 4567)}) ``` Orwithouthostportassignment: ```pythonc.start(container_id, port_bindings={1111: ('127.0.0.1',)}) ``` IfyouwishtouseUDPinsteadofTCP (default), youneedtodeclareitlikesuchinboththe`create_container()`and`start()`calls: ```pythoncontainer_id=c.create_container('busybox', 'ls', ports=[(1111, 'udp'), 2222]) c.start(container_id, port_bindings={'1111/udp': 4567, 2222: None}) ``` Usingvolumes=============Similarly, volumedeclarationisdoneintwoparts. First, youhavetoprovidealistofmountpointstothe`Client.create_container`method. ```pythonc.create_container('busybox', 'ls', volumes=['/mnt/vol1', '/mnt/vol2']) ``` Volumemappingsarethendeclaredinsidethe`Client.start`methodlikethis: ```pythonc.start(container_id, binds={'/home/user1/':{'bind': '/mnt/vol2', 'ro': False }, '/var/www':{'bind': '/mnt/vol1', 'ro': True } }) ``` ConnectiontodaemonusingHTTPS================================*Theseinstructionsaredocker-pyspecific. Pleaserefertohttp://docs.docker.com/articles/https/first.**Authenticateserverbasedonpublic/defaultCApool```pythonclient=docker.Client(base_url='<https_url>', tls=True) ``` EquivalentCLIoptions: `docker --tls ...`IfyouwanttouseTLSbutdon'twanttoverifytheservercertificate (forexamplewhentestingwithaself-signedcertificate): ```pythontls_config=docker.tls.TLSConfig(verify=False) client=docker.Client(base_url='<https_url>', tls=tls_config) ``` *AuthenticateserverbasedongivenCA```pythontls_config=docker.tls.TLSConfig(ca_cert='/path/to/ca.pem') client=docker.Client(base_url='<https_url>', tls=tls_config) ``` EquivalentCLIoptions: `docker --tlsverify --tlscacert /path/to/ca.pem ...`*Authenticatewithclientcertificate, donotauthenticateserverbasedongivenCA```pythontls_config=docker.tls.TLSConfig( client_cert=('/path/to/client-cert.pem', '/path/to/client-key.pem') ) client=docker.Client(base_url='<https_url>', tls=tls_config) ``` EquivalentCLIoptions: `docker--tls--tlscert/path/to/client-cert.pem--tlskey/path/to/client-key.pem ...` *Authenticatewithclientcertificate, authenticateserverbasedongivenCA```pythontls_config=docker.tls.TLSConfig( client_cert=('/path/to/client-cert.pem', '/path/to/client-key.pem'), ca_cert='/path/to/ca.pem' ) client=docker.Client(base_url='<https_url>', tls=tls_config) ``` EquivalentCLIoptions: `docker--tlsverify--tlscert/path/to/client-cert.pem--tlskey/path/to/client-key.pem--tlscacert/path/to/ca.pem ...`