运行 我的应用程序容器时自动启动和公开 ssh 的正确方法

Proper way to automatically start and expose ssh when running my app container

我有包含 python 应用程序的容器,我需要它们在 运行 启动它们时自动启动并公开 ssh。我知道it's against Docker's best practices, but right now I don't have any other solution。我很想知道在 docker 容器中自动 运行 附加服务的最佳方法。

由于 Docker 只会启动一个进程,安装 sshd 是不够的。显然有多种选择来处理它:

  1. 使用流程管理器,如 Monit 或 Supervisor
  2. 使用 ENTRYPOINT 选项
  3. /etc/bash.bashrc 的末尾附加一个命令(例如 service sshd start)(参见 this answer

选项 1 对我来说似乎太过分了。此外,我想我必须 运行 带有 cmd 的容器调用进程管理器而不是 bash 或我的 python 应用程序:不完全是我想要的。

对于这种情况,我不知道如何使用选项 2。我是否应该编写一个自定义脚本来启动 sshd 然后 运行ning 所提供的命令(如果有的话)?这个脚本应该是什么样子?

选项 3 非常简单但很脏。如果我 运行 容器使用 /bin/bash.

之外的另一个命令,它也不会工作

最佳解决方案是什么以及如何设置?

您提到选项 1 似乎有点矫枉过正。为什么它矫枉过正? Supervisor配置起来非常简单,基本上会做你想做的事。

首先,编写启动您的 python 应用程序和 sshd 的主管配置文件:

[supervisord]
nodaemon=true

[program:sshd]
command=/usr/sbin/sshd -D

[program:pythonapp]
command=/path/to/python myapp.py -x args etc etc

调用该文件 supervisord.conf 并将其提交到您的存储库中的某处。在您的 Dockerfile 中,将该文件作为容器构建步骤之一复制到容器中,公开 SSH 端口和您的应用程序(如果需要)并设置 CMD 以启动 supervisord:

COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf
EXPOSE 22 80
CMD ["/usr/bin/supervisord"]

这很干净,也很容易理解。这就是我在需要时 运行 在一个容器中进行多个进程的方式。它甚至 suggested in the Docker docs 作为一个很好的解决方案。

如果您不想使用进程管理器,您可以将您的实际容器命令包装在一个 shell 脚本和 sudo service ssh start 中,然后执行您的实际命令。

sudo 服务 ssh 启动
python myapp.py -x args blah blah

这会将 ssh 作为守护进程启动,然后您的 python 应用程序将在之后启动。

是的,我们可以为容器中的多进程配置Supervisord。如果你想使用 Openssh-server 我们可以像下面这样配置 Supervisor-:

[supervisord]
nodaemon=true

[program:sshd]
command=/usr/sbin/sshd -D

在 supervisord.conf 文件中。

我们可以在 docker 镜像中添加 supervisord.conf 文件,更新 Dockerfile 中的一行。

RUN apt update && apt install -y supervisor openssh-server    
COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf
EXPOSE 22
CMD ["/usr/bin/supervisord"]

参考link-:Gotechnies