docker容器开启ssh服务远程连接

这里使用的容器是centos7环境,基本是个比较纯净的环境,几乎什么都没装

根据自己需求,先安装一些基本的(容器,默认是root用户)

yum install -y net-tools

接着安装openssl,openssh-server

yum install -y openssl openssh-server

然后启动ssh

/usr/sbin/sshd -D

这里会报错

[root@68e7598797d7 /]# /usr/sbin/sshd -D
Could not load host key: /etc/ssh/ssh_host_rsa_key
Could not load host key: /etc/ssh/ssh_host_ecdsa_key
Could not load host key: /etc/ssh/ssh_host_ed25519_key

进行下面的设置

[root@68e7598797d7 /]# ssh-keygen -q -t rsa -b 2048 -f /etc/ssh/ssh_host_rsa_key -N ''  
[root@68e7598797d7 /]# ssh-keygen -q -t ecdsa -f /etc/ssh/ssh_host_ecdsa_key -N ''
[root@68e7598797d7 /]# ssh-keygen -t dsa -f /etc/ssh/ssh_host_ed25519_key -N ''

接着修改sshd_config文件配置信息,路径为 /etc/ssh/sshd_config

1.将 Port 22 前面的注释去掉(开启22号端口)

2.将  PermitRootLogin  的 no  改为 yes (这里是设置是否允许root用户登录,可根据自己需求决定是否开启) 

重新启动ssh

[root@68e7598797d7 /]# /usr/sbin/sshd -D &

注意,如果设置都没问题的话,命令结尾加个‘&’,自动后台运行

启动成功会返回进程号

[root@68e7598797d7 /]# /usr/sbin/sshd -D &
[1] 16

给root添加密码

添加过的可跳过此步骤

[root@68e7598797d7 /]# passwd

将当前容器保存成新的镜像

先退出并关闭刚才的容器,可以使用 exit 命令,然后保存镜像

docker commit mycontainer newimage

'mycontainer' 为刚才使用的容器,'newimage'为新的镜像名,可以根据自己的需要改动

基于新镜像重新启动一个容器

docker run -itd --name newcont -p 8000:22 newimage

命令中的端口号可以指定也可以使用大写P自动映射(建议自己指定)

进入容器并重新开启ssh

[root@68e7598797d7 /]# /usr/sbin/sshd -D &
[1] 15

和之前启动的操作是一样的

使用xshell远程连接

启动完成后就可以通过xshell或者其他连接工具进行远程连接了,记住,ip是宿主机的IP地址,端口号宿主机上的端口,即上面端口映射命令中的 8000 !

发布了85 篇原创文章 · 获赞 61 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/Leo_csdn_/article/details/96150534