【问题标题】:Send command to running container using attach without docker exec在没有 docker exec 的情况下使用 attach 将命令发送到正在运行的容器
【发布时间】:2019-09-24 08:26:46
【问题描述】:

我有一个在 docker 容器中运行的循环进程,它接受输入的命令。目前我必须使用docker attach <container>,然后在退出之前输入我的命令,例如restart

据我所知,我不能使用docker exec,因为我想与之交互的进程已经在运行,所以无论如何我可以以编程方式将命令传递给docker attach

编辑:这是运行程序内部的命令,不是 shell 可用的命令

【问题讨论】:

  • 服务已经运行时可以使用docker execdocker exec container_name command
  • 我不能,因为命令在 shell 中不可用,它已经是一个正在运行的进程。

标签: docker


【解决方案1】:

一个解决方案可能是使用类似的东西:

echo "your input here" | docker attach <your container>

但是...这要求不要使用-t 选项,这可能会给您带来其他问题...


检查此问题:Redirect stdin to docker attach Michael Crosby 提供了一个示例:

此问题已解决。

docker run -i busybox sh -c "while true; do cat /dev/stdin; sleep 1; done;"
test

# ... from another terminal
echo test | docker attach 27f04f3fd73a

这里应该注意的是,当您使用--tty , -t (Allocate a pseudo-TTY) 选项运行容器时,它不起作用。我还没有完全理解为什么会发生这种情况所以我不会尝试解释它,这里已经写了一些东西:Confused about Docker -t option to Allocate a pseudo-TTY


另外,来自docker runreference

对于交互式进程(如 shell),您必须同时使用 -i -t 才能为容器进程分配 tty。 -i -t 通常写成 -it,您将在后面的示例中看到。当客户端从管道接收其标准输入时,禁止指定 -t,如:

$ echo test | docker run -i busybox cat

【讨论】:

  • 我遇到了-t 标志可能在 docker-compose 中使用的问题,当我尝试通过管道传递给它时,我收到了错误 the input device is not a TTY
【解决方案2】:

作为described here,您可以使用socatecho 'restart' | socat EXEC:'docker attach &lt;container&gt;',pty STDIN

另一个完整的例子:

# Run the program in docker, here bash, in background
docker run -it --rm --name test ubuntu &
# Send "ls -la" to the bash running inside docker
echo 'ls -la' | socat EXEC:'docker attach test',pty STDIN
# Show the result
docker logs test

【讨论】:

    【解决方案3】:

    也可以使用expect向具有终端的docker容器发送命令:

    发送-t.exp:

    #!/usr/bin/expect -f
    set container [lindex $argv 0]
    set command [lindex $argv 1]
    spawn docker attach $container
    send -- "$command\n"
    expect "*\n"
    expect "*\n"
    # set timeout 1
    # expect eof
    

    用法:

    send-t.exp container 'command args'

    例子:

    send-t.exp my-container 'find /'

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-09
      • 1970-01-01
      • 1970-01-01
      • 2021-12-05
      • 1970-01-01
      • 2012-07-15
      • 1970-01-01
      • 2020-08-23
      相关资源
      最近更新 更多