我天真地期望这个命令在一个正在运行的容器中运行bash shell:

docker run "id of running container" /bin/bash

看起来是不可能的,我得到了一个错误:

2013/07/27 20:00:24 Internal server error: 404 trying to fetch remote history for 27d757283842

因此,如果我想在运行容器中运行bash shell(例如用于诊断目的)

我必须在里面运行SSH服务器并通过SSH登录吗?


当前回答

请关注这个拉请求:https://github.com/docker/docker/pull/7409

它实现了即将到来的docker exec <container_id> <命令>实用程序。当它可用时,应该可以在运行的容器中启动和停止ssh服务。

还有nsinit可以做到这一点:“nsinit提供了一种方便的方式来访问正在运行的容器名称空间中的shell”,但它看起来很难运行。 https://gist.github.com/ubergarm/ed42ebbea293350c30a6

其他回答

首先,通过获取所需容器的容器id

docker ps

你会得到这样的结果:

CONTAINER ID        IMAGE                  COMMAND             CREATED             STATUS                          PORTS                    NAMES
3ac548b6b315        frontend_react-web     "npm run start"     48 seconds ago      Up 47 seconds                   0.0.0.0:3000->3000/tcp   frontend_react-web_1

现在复制这个容器id并运行以下命令:

docker exec -it container_id sh

docker exec -it 3ac548b6b315 sh

在运行容器时,分配名称是很有用的。您不需要引用container_id。

Docker运行——name container_name yourimage Docker exec -it container_name bash

如果目标是检查应用程序的日志,这篇文章展示了启动tomcat并作为CMD的一部分跟踪日志。tomcat日志可以通过'docker logs containerid'在主机上获取。

http://blog.trifork.com/2013/08/15/using-docker-to-efficiently-create-multiple-tomcat-instances/

由于情况正在发生变化,目前访问正在运行的容器的推荐方式是使用nsenter。

你可以在这个github存储库上找到更多信息。但通常你可以这样使用nsenter:

PID=$(docker inspect --format {{.State.Pid}} <container_name_or_ID>)
nsenter --target $PID --mount --uts --ipc --net --pid

或者你可以使用包装器docker-enter:

docker-enter <container_name_or_ID>

关于这个话题的一个很好的解释可以在Jérôme Petazzoni的博客上找到: 为什么不需要在docker容器中运行sshd

这是我的解决方案

在Dockerfile中:

# ...
RUN mkdir -p /opt
ADD initd.sh /opt/
RUN chmod +x /opt/initd.sh
ENTRYPOINT ["/opt/initd.sh"]

在initd.sh文件中

#!/bin/bash
...
/etc/init.d/gearman-job-server start
/etc/init.d/supervisor start
#very important!!!
/bin/bash

镜像构建后,你有两个选择使用exec或attach:

使用exec(首选)并运行: ——name $CONTAINER_NAME -dt $IMAGE_NAME 然后 - $CONTAINER_NAME /bin/bash 并使用CTRL + D分离 使用attach并运行: ——name $CONTAINER_NAME -dit $IMAGE_NAME 然后 附加$CONTAINER_NAME 并使用CTRL + P和CTRL + Q分离 注意:选项之间的区别是参数-i