【问题标题】:Why can't I execute kill command in a docker container from host's command line?为什么我不能从主机的命令行在 docker 容器中执行 kill 命令?
【发布时间】:2022-01-14 09:30:34
【问题描述】:

这样就可以了。

//get inside container
$ docker exec -it -u root container bash

// run kill ( works perfectly )
# kill -9 $(pgrep gunicorn)

但我想直接做,而不必登录容器的外壳。

我试试这个。

$ docker exec -it -u root container bash -c "kill -9 $(pgrep gunicorn)"

我收到此错误。

bash: line 0: kill: (1227) - No such process
bash: line 1: 1988: command not found
bash: line 2: 8789: command not found
bash: line 3: 8989: command not found
bash: line 4: 11471: command not found
bash: line 5: 97065: command not found
bash: line 6: 729921: command not found
bash: line 7: 750108: command not found
bash: line 8: 851794: command not found
bash: line 9: 851862: command not found

我尝试了其他东西。

$ docker exec -it -u root container bash -c "touch test-file"

这也很有效。

那么为什么我不能像这样运行kill 命令?

【问题讨论】:

  • 猜测,因为pgrep gunicorn首先在主机上执行,并返回一个与容器中的不匹配的进程ID。您可以尝试使用单引号来阻止该表达式首先被主机上的外壳评估?
  • 你是对的。解决了。谢谢。
  • 另外注意一个Docker容器通常只运行一个进程,所以你应该可以docker stop container; docker rm container停止容器中的一个进程并清理它。在正常使用中您不需要docker exec,也不需要在容器内查找进程ID。

标签: bash docker


【解决方案1】:

正如@SiHa 所建议的,必须使用单引号来阻止表达式被主机上的外壳评估。用单引号替换双引号后工作正常。

【讨论】:

    猜你喜欢
    • 2015-10-21
    • 2020-07-28
    • 2021-05-12
    • 2014-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-06
    • 1970-01-01
    相关资源
    最近更新 更多