大网数据广告活动
服务器运维问答

How to send text to stdin of docker container?

· 52CE 我爱测

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 doc…

问题原文

原帖链接 · paolo · CC BY-SA 3.0

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.

社区高分解答

原帖链接 · Dave Akers · CC BY-SA 4.0

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.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2017-11-29)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0 / CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。