d11wtq d11wtq - 1 month ago 28
Python Question

How to use docker-py (official docker client) to start a bash shell?

I'm trying to use docker-py to run a docker container and drop me into a bash shell in that container. I get as far as running the container (I can see it with

docker ps
, and I can attach to it just fine with the native docker client), but when I use
attach()
from the official Python library, it just gives me an empty string in response. How do I attach to my bash shell?

>>> import docker
>>> c = docker.Client()
>>> container = c.create_container(image='d11wtq/python:2.7.7', command='/bin/bash', stdin_open=True, tty=True, name='docker-test')
>>> container
{u'Id': u'dd87e4ec75496d8369e0e526f343492f7903a0a45042d312b37859a81e575303', u'Warnings': None}
>>> c.start(container)
>>> c.attach(container)
''

Answer

I ended up releasing a library for this: https://github.com/d11wtq/dockerpty

import docker
import dockerpty

client = docker.Client()
container = client.create_container(
    image='busybox:latest',
    stdin_open=True,
    tty=True,
    command='/bin/sh',
)
client.start(container)

dockerpty.PseudoTerminal(client, container).start()