七、为镜像添加 SSH 服务

很多时候,系统管理员都习惯通过 SSH 服务来远程登录管理服务器,但是 Docker 的很多镜像是不带 SSH 服务的,那么用户怎样才能管理容器呢?
之前介绍了一些进入容器的办法, 比如用 attach 、 exec 等命令,但是这些命令都无法解决远程管理容器的问题。 因此,当读者需要远程登录到容器内进行一些操作的时候,就需要 SSH 的支持了 。
本文将具体介绍如何自行创建一个带有 SSH 服务的镜像,并详细介绍了两种创建容器的方法:基于 docker commit 命令创建和基于 Dockerfile 创建。

一、基于commit命令创建

Docker 提供了 docker commit 命令 , 支持用户提交自己对制定容器的修改,并生成新的镜像。 命令格式为 docker commit CONTAINER [REPOSITORY [ :TAG ]] 。 这里笔者将介绍如何用 docker commit 命令为centos:latest镜像添加 SSH 服务 。

[root@docker ~]# docker run -it centos:latest     
[root@963ec5346096 /]# yum -y install openssh-server
[root@963ec5346096 /]# ssh-keygen -A
[root@963ec5346096 /]# ls /etc/ssh/
moduli	ssh_host_dsa_key  ssh_host_dsa_key.pub	ssh_host_ecdsa_key  ssh_host_ecdsa_key.pub  ssh_host_ed25519_key  ssh_host_ed25519_key.pub  ssh_host_rsa_key  ssh_host_rsa_key.pub  sshd_config
[root@963ec5346096 /]# yum -y install passwd
[root@963ec5346096 /]# echo 123456 | passwd --stdin root

在容器内创建run.sh文件,并添加运行权限,chmod +x run.sh

#!/bin/bash
/usr/sbin/sshd -D

docker commit 963ec5346096 centos:sshd6:将容器制作为镜像
docker run -d centos:sshd6 /run.sh:运行sshd镜像
ssh root@ip :ssh容器ip远程登录

二、基于Dockerfile文件创建

FROM centos:latest    #基础镜像

MAINTAINER yulei     #作者

RUN yum install -y openssh-server       #安装ssh软件包
RUN ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key && \      #生成密钥
    ssh-keygen -t ecdsa -f /etc/ssh/ssh_host_ecdsa_key && \
    ssh-keygen -t ed25519 -f /etc/ssh/ssh_host_ed25519_key
RUN yum -y install passwd  #安装修改密码公具
RUN echo "123456" | passwd --stdin root  #修改root密码
COPY run.sh /run.sh     #拷贝当前位置的run.sh脚本到容器内
RUN chmod 755 /run.sh   #修改run.sh文件的劝降
EXPOSE 22      #声明端口,并不会暴露

CMD ["/run.sh"]   #执行docker命令时执行的默认命令(执行脚本文件,启动sshd服务)

docker build -t centos:sshd7 . :构建镜像
docker run -d centos:sshd7 /run.sh:运行sshd镜像
ssh root@ip :ssh容器ip远程登录

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值