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

2019-03-21 23:49发布

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.

标签: docker
4条回答
迷人小祖宗
2楼-- · 2019-03-21 23:52

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

查看更多
戒情不戒烟
3楼-- · 2019-03-21 23:52

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.

查看更多
疯言疯语
4楼-- · 2019-03-21 23:52

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

查看更多
Root(大扎)
5楼-- · 2019-03-22 00:11

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.

查看更多
登录 后发表回答