09-Docker配置SSH服务
为镜像添加SSH服务
我们习惯于使用ssh管理服务器,docker自带attach和exec也可以用与进入容器,但都无法解决远程管理容器的问题。文章会介绍如果创建一个带有SSH服务的镜像。
基于commit创建
[ ~]# docker pull centos:7 [ ~]# docker run -it centos:7 bash #先为docker修改root密码 [ /]# passwd Changing password for user root. New password: BAD PASSWORD: The password is shorter than 8 characters Retype new password: passwd: all authentication tokens updated successfully. #安装SSH服务 [ /]# yum -y install openssh-server #创建对应key文件 [ /]# 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 ‘‘ #修改SSH配置 [ /]# vi /etc/ssh/sshd_config #UsePAM yes 改为 UsePAM no #UsePrivilegeSeparation sandbox 改为 UsePrivilegeSeparation no #启动 SSH服务 [ /]# /usr/sbin/sshd -D & #创建自启动脚本 [ /]# vi /run.sh #!/bin/bash /usr/sbin/sshd -D [ /]# chmod +x /run.sh [ /]# exit
#保存镜像 [ ~]# docker commit 4213ca71655c sshd:centos #端口映射 [ ~]# docker run -p 10023:22 -d sshd:centos /run.sh [ ~]# docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES b859ee8f4649 sshd:centos "/run.sh" 17 minutes ago Up 17 minutes 0.0.0.0:10023->22/tcp pensive_wiles #测试登录,使用宿主机ip+端口 [c:\~]$ ssh 10023 WARNING! The remote SSH server rejected X11 forwarding request. Last login: Wed Apr 29 14:11:03 2020 from 192.168.3.71 [ ~]#
基于Dockerfile创建
···
[er ~]# mkdir ssh_centos
[ ~]# cd ssh_centos/
[ ssh_centos]# vim Dockerfile
FROM centos:7
RUN echo "123456" | passwd --stdin "root"
RUN yum -y install openssh-server
RUN ssh-keygen -q -t rsa -b 2048 -f /etc/ssh/ssh_host_rsa_key -N ‘‘
RUN ssh-keygen -q -t ecdsa -f /etc/ssh/ssh_host_ecdsa_key -N ‘‘
RUN ssh-keygen -t dsa -f /etc/ssh/ssh_host_ed25519_key -N ‘‘
RUN sed -ri ‘s/UsePAM yes/UsePAM no/g‘ /etc/ssh/sshd_config
RUN sed -ri ‘s/UsePrivilegeSeparation sandbox/UsePrivilegeSeparation no/g‘ /etc/ssh/sshd_config
RUN /usr/sbin/sshd -D &
RUN echo "#!/bin/bash" >> /run.sh
RUN echo "/usr/sbin/sshd -D" >> /run.sh
RUN chmod 755 /run.sh
EXPOSE 22
CMD ["/run.sh"]
···
···
[ ssh_centos]# docker build -t sshdtest:dockerfile .
#有个点(.)代表从当前目录查找dockerfile文件
[ ssh_centos]# docker run -d -p 10122:22 sshdtest:dockerfile
测试
ssh 192.168.3.109 10122
···