从不同的主机上的另一个容器中SSH到Docker容器

11

我有一个在 EC2 主机上运行的 Docker 容器,另一个在另一个 EC2 主机上运行。如何在不提供任何端口号的情况下从一个容器 SSH 到另一个容器?我想要像这样做: ssh root@容器IP地址


2
为了实现这一点,您的第二个容器需要一个可以从第一个容器路由到的IP地址。由于Docker的开箱即用行为是使用私有IP地址,因此这并不容易。这就是为什么人们倾向于将端口映射到外部主机上的不同端口号。另一种选择是使用“覆盖网络”,例如weave。(我在weave工作) - Bryan
1
此外,还需要在容器内安装和启动ssh服务器。ssh在容器中的工作方式与常规发行版不同,因此需要进行特殊设置。 - Dharmit
@Bryan - 谢谢!我会试一下! - user1016313
@Dharmit - 是的,我在容器中运行了SSH服务器。我可以从主机到容器进行SSH,或者通过给定映射端口从外部计算机到容器进行SSH。我想要实现的是通过给定Docker容器的IP地址进行SSH连接。 - user1016313
Stack Overflow是一个关于编程和开发问题的网站。这个问题似乎不属于编程或开发范畴。请参阅帮助中心中的我可以在这里问什么样的问题。也许超级用户Unix&Linux Stack Exchange更适合提问。 - jww
3个回答

6

如果您想通过端口22登录第二个容器,您需要使主机EC2 VM的ssh守护程序让路。

  1. One way is to change your host machine's ssh port by adding an entry in /etc/ssh/sshd_config to something like 3022. Now you can use -p 22:22 when you run your docker container(s) and be able to ssh between them. However, ssh`ing the ec2 instance is on 3022.

  2. If you would like to keep host-vms also ssh enabled on port 22 you will then need to create a second virtual ethernet interface. This is easy to do if you are able to set static IPs. something like ifconfig eth0:0 192.168.1.11 up. However, in ec2 this won't be possible as you have DHCP based IPs.

  3. The third way is to setup your .ssh/config file to map to the non standard port. It does not allow you to ssh over port 22 but at least you don't have to know about the non-standard port. Here is a tutorial, and relevant parts are below.

    # contents of $HOME/.ssh/config
    Host other_docker
        HostName ec2-host-name-of-other-docker.com
        Port 22000
        User some_user
    
        # must be added to authorized keys on other docker host for some_user
        IdentityFile ~/.ssh/this-docker-private-key
    
现在你可以直接执行ssh other_docker


-1
我还没有测试过,但你可能可以像这样做:ssh hostUser@xxx.xxx.xxx.xxx 'ssh containerUser@xxx.xxx.xxx.xxx',使用 ssh 的 command 参数。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接