我正在嘗試設定一個 Ubuntu 容器,openssh-server
以便我可以從主機 ssh 進入它。我知道這不是標準的做法,但我真的很想這麼做ssh
。
這是我的Dockerfile
# Select base image
FROM ubuntu:16.04
# Set the current working directory
WORKDIR /home
# Update the system, download any packages essential for the project
RUN dpkg --add-architecture i386
RUN apt-get update && apt-get upgrade -y
RUN apt-get install -y git build-essential make gcc vim net-tools iputils-ping ca-certificates openssh-server libc6:i386 libstdc++6:i386
# Allow ssh root login
RUN echo "root:root" | chpasswd
# RUN rpl "PermitRootLogin prohibit-password" "PermitRootLogin yes" /etc/ssh/sshd_config
RUN sed -i 's/prohibit-password/yes/' /etc/ssh/sshd_config
RUN cat /etc/ssh/sshd_config
RUN mkdir /root/.ssh
RUN chown -R root:root /root/.ssh;chmod -R 700 /root/.ssh
RUN echo “StrictHostKeyChecking=no” >> /etc/ssh/ssh_config
RUN service ssh restart
# Open port 22 so linked containers can see it
EXPOSE 22
# Import any additional files into the environment (from the host)
ADD otherfile .
我啟動容器,docker run -t -d -p 2222:22
但每當我嘗試 ssh 進入它時,我總是會收到錯誤ssh_exchange_identification: Connection closed by remote host
:
➜ ssh -v -p 2222 root@localhost /bin/bash
OpenSSH_7.9p1, LibreSSL 2.7.3
debug1: Reading configuration data /Users/giorgio/.ssh/config
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 48: Applying options for *
debug1: /etc/ssh/ssh_config line 52: Applying options for *
debug1: Connecting to localhost port 2222.
debug1: Connection established.
debug1: identity file /Users/giorgio/.ssh/id_rsa type -1
debug1: identity file /Users/giorgio/.ssh/id_rsa-cert type -1
debug1: identity file /Users/giorgio/.ssh/id_dsa type -1
debug1: identity file /Users/giorgio/.ssh/id_dsa-cert type -1
debug1: identity file /Users/giorgio/.ssh/id_ecdsa type -1
debug1: identity file /Users/giorgio/.ssh/id_ecdsa-cert type -1
debug1: identity file /Users/giorgio/.ssh/id_ed25519 type -1
debug1: identity file /Users/giorgio/.ssh/id_ed25519-cert type -1
debug1: identity file /Users/giorgio/.ssh/id_xmss type -1
debug1: identity file /Users/giorgio/.ssh/id_xmss-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_7.9
ssh_exchange_identification: Connection closed by remote host
有誰知道導致此錯誤的原因以及如何修復它?
答案1
RUN service ssh restart
這會在鏡像建立階段運行 ssh 服務重新啟動(實際上是啟動),而不是在未來運行的容器中運行。您沒有CMD
或,因此它預設為您的基礎映像中配置的(ENTRYPOINT
Dockerfile
這是bash)
換句話說,當您啟動容器時,沒有 ssh 守護程式在執行。臨時解決方案是在正在執行的容器上啟動 exec 命令:docker exec your_container_name service ssh start
若要正確解決問題,您需要指示映像在建立容器時啟動 sshd(請參閱dockerize ssh 服務在碼頭工人文檔)。簡而言之:
- 刪除
RUN service ssh restart
線 - 新增接下來的兩行
RUN mkdir /var/run/sshd
CMD ['/usr/sbin/sshd', '-D']
- 重建你的鏡像,啟動一個新的容器,ssh 並享受。