为镜像添加SSH服务
虽然进入容器可使用 attach 、 exec命令等,但是无法进行远程访问。这时候需要给镜像添加SSH 服务了。
有两种方式:
-
使用 Dockerfile 进行添加
-
使用 Docker commit 命令
这里我们使用 Dockerfile 创建
目录
话不多说,我们直接开始:
创建工作目录
[root@localhost ~]# mkdir sshd_ubuntu
[root@localhost ~]# ls
anaconda-ks.cfg ip.txt sshd_ubuntu test
创建 Dockerfile 和 run.sh 文件
[root@localhost ~]# cd sshd_ubuntu/
[root@localhost sshd_ubuntu]# touch Dockerfile run.sh
[root@localhost sshd_ubuntu]# ls
Dockerfile run.sh
编写 run.sh
#!/bin/bash
/usr/sbin/sshd -D
在宿主主机上生成 SSH 密钥对,并创建 authorized_keys 文件
ssh-keygen -t rsa
...
cat ~/.ssh/id_rsa.pub > authorized_keys
编写 Dockerfile
# 基础镜像
FROM ubuntu:16.04
# 作者信息
MAINTAINER dcpnet (815787213@qq.com)
# 更新
RUN apt-get update
# 安装 ssh服务
RUN apt-get install -y openssh-server
RUN mkdir -p /var/run/sshd
RUN mkdir -p /root/.ssh
# 取消 pam 限制
RUN sed -ri 's/session requried pam_loginuid.so/#session required pam_loginuid.so/g' /etc/pam.d/sshd
# 复制配置文件到相应位置,并赋予脚本可执行权限
ADD authorized_keys /root/.ssh/authorized_keys
ADD run.sh /run.sh
RUN chmod 755 /run.sh
# 开放端口
EXPOSE 22
# 设置自启动命令
CMD ["/run.sh"]
创建镜像
在 sshd_ubuntu 目录下,使用 docker build 命令来创建镜像。
cd sshd_ubuntu
docker build -t sshd:Dockerfile .
执行完成后,可以在尾部看键
Successfully built 14011d63b230
Successfully tagged sshd:Dockerfile
查看镜像
[root@localhost sshd_ubuntu]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
sshd Dockerfile 14011d63b230 10 seconds ago 216MB
运行容器
[root@localhost sshd_ubuntu]# docker run -d -p 10122:22 sshd:Dockerfile
连接到容器
[root@localhost sshd_ubuntu]# ssh 127.0.0.1 -p 10122
The authenticity of host '[127.0.0.1]:10122 ([127.0.0.1]:10122)' can't be established.
ECDSA key fingerprint is SHA256:6c0zstBCbANGJKwcBkaO1oS9P45qg7IFwo2+bPH7yNU.
ECDSA key fingerprint is MD5:fc:35:7f:e2:6c:bb:32:96:96:1c:5a:62:f7:78:93:f9.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '[127.0.0.1]:10122' (ECDSA) to the list of known hosts.
Welcome to Ubuntu 16.04.7 LTS (GNU/Linux 3.10.0-1127.el7.x86_64 x86_64)
* Documentation: https://help.ubuntu.com
* Management: https://landscape.canonical.com
* Support: https://ubuntu.com/advantage
The programs included with the Ubuntu system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.
Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.
root@481701bd041b:~#
成功连接上了