docker容器不能使用`service sshd restart`

cin*_*nqS 2 ssh sshd docker dockerfile

我正试图建立一个Hadoop Dockerfile

在构建过程中,我添加了:

  && apt install -y openssh-client \
  && apt install -y openssh-server \
  && ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa \
  && cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys \
  && chmod 0600 ~/.ssh/authorized_keys
  && sed -i '/\#AuthorizedKeysFile/ d' /etc/ssh/sshd_config \
  && echo "AuthorizedKeysFile ~/.ssh/authorized_keys" >> /etc/ssh/sshd_config \
  && /etc/init.d/ssh restart
Run Code Online (Sandbox Code Playgroud)

我以为我在运行此容器时:

docker run -it --rm hadoop/tag bash
Run Code Online (Sandbox Code Playgroud)

我将能够:

ssh localhost
Run Code Online (Sandbox Code Playgroud)

但我得到一个错误:

ssh:连接到主机localhost端口22:连接被拒绝

如果我在容器内手动运行此命令:

/etc/init.d/ssh restart
# or this
service ssh restart
Run Code Online (Sandbox Code Playgroud)

然后我可以建立联系。我认为这意味着sshd重新启动无法正常工作

我使用FROM javaDockerfile

Dan*_*owe 5

构建过程仅构建图像。当时运行的进程(使用RUN)在构建后不再运行,并且在使用映像启动容器时不会再次启动。

您需要做的是在容器运行时启动sshd 。最简单的方法是使用入口点脚本。

Dockerfile:

COPY entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh

ENTRYPOINT ["/entrypoint.sh"]
CMD ["whatever", "your", "command", "is"]
Run Code Online (Sandbox Code Playgroud)

entrypoint.sh:

#!/bin/sh

# Start the ssh server
/etc/init.d/ssh restart

# Execute the CMD
exec "$@"
Run Code Online (Sandbox Code Playgroud)

使用以上方法重建映像,并在使用它启动容器时,应在运行之前启动sshd CMD

如果愿意,还可以将开始的基础图像更改为类似Phusion的基础图像。它可以很容易地启动某些服务,例如syslogd,sshd,您可能希望容器已在运行。