jeffreyveon
jeffreyveon

Reputation: 13830

Docker - how to send input to a program via the API

I have been using Docker's remote API to create a container, run a Python program in it, attach to the container and stream the output written to stdout to the web.

Now, I wanted my Python program to accept user input from stdin. E.g.

import sys
name = sys.stdin.readline()
print "Your name is: " + name

How do I pass the user input to this Python program running inside a Docker container via the API? I don't see any API end-points which will allow me to pass "input" to a process running inside a docker container.

Thanks.

Upvotes: 6

Views: 8445

Answers (4)

bouquetf
bouquetf

Reputation: 445

The question is a bit old but I think what you were looking for was the attach entry point from the remote API. Check here : https://docs.docker.com/reference/api/docker_remote_api_v1.17/#attach-to-a-container

It opens a socket stream you have deal with to talk to docker. You also have a possibility by using websocket with this alternative : https://docs.docker.com/reference/api/docker_remote_api_v1.17/#attach-to-a-container-websocket

I've found this IRC chat which explains in details how to proceed: https://botbot.me/freenode/docker/2014-12-22/?msg=28120891&page=10

hope it helps

Upvotes: 2

Geoffrey Bachelet
Geoffrey Bachelet

Reputation: 4317

You can in fact attach the stdin of a container using docker attach. Example:

Start a "listening" container:

docker run -i -t ubuntu:precise /bin/bash -c 'read FOO; echo $FOO;'

Then in another terminal:

# lookup container id
docker ps

# attach the container
docker attach 91495c6374b1

You are now hooked to the listening container's stdin and can type thing and everything should work.

As to doing that using the remote API... I think this is possible using the /containers/{id}/attach endpoint with stdin=1 and possibly stream=1. Couldn't get it to work and still working on understanding the go code behind this, but from what I can see in the implementation this should definitely be possible.

Upvotes: 6

Jason Livesay
Jason Livesay

Reputation: 6377

Maybe just run an sshd server inside the container? http://docs.docker.io/en/latest/examples/running_ssh_service/

Upvotes: 0

rajalokan
rajalokan

Reputation: 497

Don't think docker support this bit of interactiveness. There are couple of solutions though

  1. You can start container on bash and run commands from inside container.

  2. Or you can turn your python program to be a daemon service waiting for arguments. Use subprocess.Popenhttp://docs.python.org/2/library/subprocess.html#subprocess.Popen to start a python as a process. Look out for this SO question running-an-interactive-command-from-within-python

Hope this helps.

Upvotes: 0

Related Questions