Docker – How to send text to stdin of docker container

dockerpipestdin

I have a docker container which runs a java program in foreground on startup. The java program listens to input on stdin. How can I programmatically send text to the java program?

The container is started with -it, so I can docker attach <container-name>, type my text, send it with enter and detach using ^p ^q.

I tried docker exec <container-name> echo my-text, but this gets echoed to stdout, not the java program. Can I somehow pipe this to the java program?

I also found a similar question in the Docker forums, but the solution uses screen and I'd rather have a cleaner solution.

Best Answer

I would add this as a comment to the previous answer but am unable due to being a new user.

socat can be used with out using network for example you can attach to a container named container0 using the following:

socat EXEC:"docker attach container0",pty STDIO

Ctrl-c will be caught by socat and will not be passed to the container. You will likely see terminal control codes depending on what the container is doing with it's tty.

You can also pipe commands to the container. For example if your container was running a shell on it's tty and you wanted to have it run echo "Hello World" and didn't care or want the output back

echo "echo \"Hello World\"" | socat EXEC:"docker attach container0",pty STDIN

note the use of STDIN instead of STDIO.

There may be a better way than this but so far this is the best I've found.