!! Please note that the behavior is completely different depending on the version!
Normally docker is listening as a daemon, listening to unix domain sockets. Actually, the protocol that flows to this socket is REST / HTTP, and you can bind it to tcp with the -H
option, and it becomes a web server. The specification is written in "Docker Remote API". And there are also various language clients.
The story of such a python client docker-py.
First of all, normal usage.
import docker
dc = docker.Client()
# docker ps
dc.containers()
# docker images
dc.images()
# docker run -ti ubuntu bash
c = dc.create_container("ubuntu", stdin_open=True, tty=True)
dc.start(c["Id"])
print "docker attach %s" % c["Id"]
However.
Be careful as there are some serious pitfalls, just like "Oh ... I'll tell you what happened right now."
The assembly part of ExposedPorts in / container / create
. Is it a list or a tuple? Some people think that the list is correct and are required to tuple. Moreover, if it is not the correct combination, the correct value will not be obtained. Besides, the trap that no error occurs when using it normally.
import traceback
import docker
dc = docker.Client()
tests = (
[22,], # OK
(22,), # NG
["22/tcp",], # NG
[(22, "tcp"),], # OK
[[22, "tcp"],] # NG
)
for ports in tests:
c = dc.create_container("ubuntu", stdin_open=True, tty=True, command="bash", ports=ports)
dc.start(c["Id"])
info = dc.inspect_container(c["Id"])
print ports, info["Config"]["ExposedPorts"]
try:
assert {'22/tcp': {}} == info["Config"]["ExposedPorts"]
except:
traceback.print_exc()
finally:
dc.stop(c["Id"])
Next is PortBindings in / containers / (id) / start
. Yeah ... I wonder. What is this inconsistency?
import traceback
import docker
dc = docker.Client()
tests = (
# automatic allocation
{22:None}, # OK
{"22/tcp": None}, # OK
# manual allocation
{22:10080}, # OK
{"22/tcp": 10080}, # OK
{22: ":10080"}, # NG
{22: dict(HostPort=10080, HostIp="0.0.0.0")}, # NG
{22: ["0.0.0.0", 10080]}, # NG
{22: ("0.0.0.0", 10080)} # OK
)
for port_bindings in tests:
c = dc.create_container("ubuntu", stdin_open=True, tty=True, command="bash", ports=[22,])
dc.start(c["Id"], port_bindings=port_bindings)
info = dc.inspect_container(c["Id"])
print port_bindings, info["HostConfig"]["PortBindings"]
try:
assert '22/tcp' in info["HostConfig"]["PortBindings"]
except:
traceback.print_exc()
finally:
dc.stop(c["Id"])
Recommended Posts