SSH连接容器
容器有几种接口方案,如Docker、Podman等。本文以Docker为例子进行说明。
容器镜像的操作系统版本为
Ubuntu22.04
。如果我们想通过ssh登录容器,需要在容器内安装和启动sshd。
操作说明
首先通过
docker
接口登录到容器内:docker exec -it <docker_name> bash
然后通过
passwd
命令修改root用户的密码:root@<docker_id>:/# passwd New password: Retype new password: passwd: password updated successfully
安装
ssh-server
和ssh-client
:apt-get update apt-get install -y openssh-server openssh-client
编辑
sshd
的配置文件,开启允许root用户登录:# vi /etc/ssh/sshd_config # 将PermitRootLogin设置为yes PermitRootLogin yes
启动
sshd
:/etc/init.d/ssh restart # 然后通过以下命令检查sshd是否运行 ps -aux | grep sshd # 如果有输出,则sshd已经成功启动
通过
ifconfig
命令看到容器对应的172开头的IP地址(Docker网桥分配的地址):root@df735621d79c:/# ifconfig eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 172.17.0.2 netmask 255.255.0.0 broadcast 172.17.255.255 ether 02:42:ac:11:00:02 txqueuelen 0 (Ethernet) RX packets 26919 bytes 46789116 (46.7 MB) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 15654 bytes 1097706 (1.0 MB) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0 # 这里例子中IP地址为 172.17.0.2
在容器的宿主机上通过ssh登录到容器:
# 第6步中容器对应的IP地址为172.17.0.2,请根据实际情况登录容器 ssh root@172.17.0.2
提示
在完成ssh配置后,可以docker commit容器,再重新以端口映射的方式启动容器,使得可以以宿主机IP+映射的端口登录该容器。
如果容器不方便重置,还想从其他机器直接连接该容器,则可以通过配置ssh配置,将ProxyJump字段设置为宿主机。