How to send text to stdin of docker container?

Solution 1:

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.

Solution 2:

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.