簡體   English   中英

無法在正在運行的 Docker 容器中使用 ssh localhost

[英]Unable to ssh localhost within a running Docker container

我正在為需要 ssh 到本地主機(即 ssh user@localhost)的應用程序構建一個 Docker 圖像

我正在使用一台 Ubuntu 台式機,並從一個基本的 ubuntu:16.04 容器開始。 以下是我的Dockerfile的內容:

FROM ubuntu:16.04

RUN apt-get update && apt-get install -y \
        openjdk-8-jdk \
        ssh && \
        groupadd -r custom_group && useradd -r -g custom_group -m user1

USER user1

RUN ssh-keygen -b 2048 -t rsa -f ~/.ssh/id_rsa -q -N "" && \
        cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys

然后我使用命令構建這個容器:

docker build -t test-container .

並使用以下命令運行它:

docker run -it test-container

容器打開並顯示以下提示,並且正確生成密鑰以啟用 ssh 到本地主機:

user1@0531c0f71e0a:/$ 
user1@0531c0f71e0a:/$ cd ~/.ssh/
user1@0531c0f71e0a:~/.ssh$ ls
authorized_keys  id_rsa  id_rsa.pub

然后 ssh 進入 localhost 並受到錯誤的歡迎:

user1@0531c0f71e0a:~$ ssh user1@localhost
ssh: connect to host localhost port 22: Cannot assign requested address

我做錯了什么或需要配置任何額外的網絡設置嗎? 我只想將 ssh 放入正在運行的容器中的本地主機。

首先,您需要在映像構建腳本中安裝ssh服務器:

  • RUN sudo apt-get install -y openssh-server

然后你需要啟動ssh服務器:

  • RUN sudo /etc/init.d/ssh start

或者甚至可能在Dockerfile的最后幾行(你必須實例化一個二進制文件以保持容器運行......)

 USER root
 CMD [ "sh", "/etc/init.d/ssh", "start"]

在主機上比

# init a container from an the image
run -d --name my-ssh-container-name-01 \
    -v /opt/local/dir:/opt/container/dir my-image-01

正如在OP注釋中所述@ user2915097,這是由於容器中的ssh實例嘗試使用IPv6連接到主機。 使用-4強制通過IPv4連接解決了這個問題。

$ docker run -it ubuntu ssh -4 user@hostname

對於Docker Compose,我能夠將以下內容添加到我的.yml文件中:

network_mode: "host"

我相信Docker中的等價物是:

--net=host

我今天也遇到了這個錯誤,這是修復它的方法:

如果(且僅當)您在未投入生產的正在運行的容器中遇到此錯誤。 做這個:

docker exec -it -u 0 [your container id here] /bin/bash

然后當你以上帝模式進入容器時,運行這個:

service ssh start

然后您可以運行基於 ssh 的命令。

當然,最佳做法是在所有這些之前在您的 Dockerfile 中執行此操作,但如果您尚未完成圖像構建過程,則無需擔心。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM