3

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.

4

socat can run the command and forward the tty to "something".

An example is creating a network server:

socat EXEC:"docker run -ti debian bash",pty \
      TCP-LISTEN:7977,bind=127.0.0.1,fork

That creates a TCP port for something to connect to. The port forwards everything back and forth to the docker run cli process:

→ nc 127.0.0.1 7977
root@045041cf8e60:/# whoami
whoami
root
root@045041cf8e60:/# ^C

Control characters are local to nc, so the container continues running.

3

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.