Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

docker

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.

like image 827
jeffreyveon Avatar asked Nov 11 '13 16:11

jeffreyveon


People also ask

Does docker have an API?

Docker provides an API for interacting with the Docker daemon (called the Docker Engine API), as well as SDKs for Go and Python. The SDKs allow you to build and scale Docker apps and solutions quickly and easily. If Go or Python don't work for you, you can use the Docker Engine API directly.

How do I push code into container?

Just use the -v switch to specify the local directory path that you wish to mount, along with the location where it should be mounted within the running container: docker run -d -P --name <name of your container> -v /path/to/local/directory:/path/to/container/directory <image name> ...

How do I pass an environment variable in docker run?

When we launch our Docker container, we can pass environment variables as key-value pairs directly into the command line using the parameter –env (or its short form -e). As can be seen, the Docker container correctly interprets the variable VARIABLE1.


1 Answers

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.

like image 126
Geoffrey Bachelet Avatar answered Sep 19 '22 00:09

Geoffrey Bachelet