使用commit方式构建具有sshd服务的centos镜像

一般我们是通过SSH服务来管理服务器的,但是现在很多Docker镜像不带SSH服务,那我们该如何来管理这些容器呢?现在我们通常使用attach和nsenter工具。但是都无法解决远程管理容器的问题,当我们需要远程管理容器的时候,就需要SSH的支持了。

1.搜索centos
$ docker search centos -s 10

备注:STARS数最多,OFFICIAL是"[OK]"的这个就是官方的centos镜像。

2.下载centos
$ docker pull centos

3.查看镜像
$ docker images

REPOSITORY   TAG      IMAGE ID        CREATED      SIZE
centos       latest   e934aafc2206    3 days ago   199MB

 

4.启动centos容器
$ docker run -it centos /bin/bash

5.安装sshd服务
[root@52162961c0e2 /]# yum install passwd openssl openssh-server -y

启动sshd服务报如下错误:
[root@52162961c0e2 /]# /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
sshd: no hostkeys available -- exiting.

 

6.执行以下三条命令:

#ssh-keygen -q -t rsa -b 2048 -f /etc/ssh/ssh_host_rsa_key -N ''
#ssh-keygen -q -t ecdsa -f /etc/ssh/ssh_host_ecdsa_key -N ''
#ssh-keygen -t dsa -f /etc/ssh/ssh_host_ed25519_key -N ''

7.重新启动sshd服务
[root@52162961c0e2 /]# /usr/sbin/sshd -D &
[1] 85

安装网络工具包:yum install net-tools
使用netstat命令查看端口:netstat -nlp

可以看到,容器的22端口即SSH服务的默认监听端口处于监听状态。

8.使用ssh-keygen命令生成公钥私钥信息
[root@52162961c0e2 /]# ssh-keygen -t rsa -P ''
执行完成之后在/root/.ssh/目录下会有id_rsa和id_rsa.pub两个文件生成。

9.粘贴 52162961c0e2 容器的/root/.ssh/id_rsa.pub公钥内容:

把上面的公钥内容拷贝到192.168.1.160主机的/root/.ssh/目录下的authorized_keys文件中,并将authorized_keys文件权限改为600:
$ chmod 600 authorized_keys
通过192.168.1.160主机ssh远程登录52162961c0e2容器

10.修改密码passwd root

[root@52162961c0e2 sbin]# passwd root
Changing password for user root.
New password: ##输入:aaaa
[root@52162961c0e2 sbin]# passwd root
Changing password for user root.
New password: ##输入:aaaa
BAD PASSWORD: The password is a palindrome
Retype new password: 
passwd: all authentication tokens updated successfully

 

创建一个可执行文件run.sh用于启动ssh服务

[root@52162961c0e2 ~]# yum install vim ##安装vim编辑器
[root@52162961c0e2 ~]# cd ~
[root@52162961c0e2 ~]# pwd
/root
[root@52162961c0e2 ~]# vim run.sh
run.sh内容如下:
#!/bin/bash
/usr/sbin/sshd -D
[root@52162961c0e2 ~]# chmod +x run.sh

 

11.exit退出容器

12.通过commit执行提交命令,保存镜像
$ docker commit -m "add sshd" -a "ruthless" 52162961c0e2 sshd:v1
sha256:0b0c0adfc3d449132a38530afe06c3a12df2650f81e53169e60b51046215bd39

13.启动新的容器
使用sshd:v1镜像,启动新的容器,并添加映射的端口20022-->22,20022是宿主机上的端口,22是容器中SSH服务监听的端口
$ docker run -d -p 20022:22 --name centos_sshd sshd:v1 /root/run.sh
$ docker ps

注意:[root@rocketmq-nameserver4 ~]# docker run -d -p 20022:22 --name centos_sshd sshd:v1 /root/run.sh
docker: Error response from daemon: Conflict. The container name "/centos_sshd" is already in use by container "e0a9d7ad00b9cd18dfa5499567a4ad14d1a8ba4838ca49186f1256e7cf312338". You have to remove (or rename) that container to be able to reuse that name.
See 'docker run --help'.
解决方案:
$ docker stop centos_sshd
$ docker rm centos_sshd

14.测试
$ ssh 192.168.1.160 -p 20022 ##登陆密码为aaaa

posted on 2018-04-10 19:21  Ruthless  阅读(663)  评论(0编辑  收藏  举报