Fork me on GitHub

用ssh连接docker容器

用docker commit 的方式创建ssh直连docker容器镜像

  1. 拉取镜像,这里采用centos:7作为基础镜像
docker pull centos:7
  1. 运行镜像,生成容器
docker run -d --name ssh_box --privileged=true centos:7 /usr/sbin/init
07228ec257564c4874ca24216d651bda65573d49e4149064a079cacca27de4e1 # 生成的容器ID

--name 给新生成的容器命名
--privileged=true 给容器访问Linux内核特权,后面要访问systemctl
返回一串容器ID表示容器生成成功

  1. 进入刚刚生成的容器
docker exec -it 07228ec25756 /bin/bash
  1. 进入容器后,使用passwd密码来修改密码(如提示没有这个命令行使用yum install passwd安装)
passwd

5.安装vim和Openssh(docker 容器中执行)

yum install vim openssh-server openssh-clients -y

6.修改SSH配置文件

 vim /etc/ssh/sshd_config

修改如下:

PubkeyAuthentication yes #启用公钥私钥配对认证方式 
AuthorizedKeysFile .ssh/authorized_keys #公钥文件路径(和上面生成的文件同) 
PermitRootLogin yes #root能使用ssh登录
ClientAliveInterval 60  #参数数值是秒 , 是指超时时间
ClientAliveCountMax 3 #设置允许超时的次数
  1. 重启ssh服务,并设置开机启动
 systemctl restart sshd.service
 systemctl enable sshd.service

Failed to get D-Bus connection: Operation not permitted
这里如果报这个错误说明容器权限不足,第2步执行有误
8.退出容器并保存更改

exit
  1. 用刚才生成的容器创建镜像
 docker commit -m 'openssh' -a 'Docker for ssh' ffe81683c404 ssh_box

-m:来指定提交的说明信息,跟我们使用的版本控制工具一样
-a 可以指定更新的用户信息
ffe81683c404: 创建镜像的容器的ID,就是上面的容器id,也就是我们刚才进入的容器id
ssh_box: 目标镜像的仓库名

docker images可以查看到新生成的镜像

10.删除构建容器(可选)
我们用centos基础容器修改配置后已经生成了所需要的镜像,之前的构建容器就可以删除了

docker stop 07228ec25756
docker rm 07228ec25756
  1. 用新生成的镜像启动新的容器并打通22端口
docker run -d -p 2222:22 ssh_box /usr/sbin/sshd -D

12.然后可以使用xshell连接新生成的容器

ip: 为宿主主机的ip,而不是docker容器的ip
端口:就是上面的2222
用户名: root
密码: 就是上面password部分设置的密码
在mac上可通过ssh root@127.0.0.1 -p:2222 登录新生成的容器

至此ssh连接docker容器连接成功

以Dockerfile的方式创建ssh直连docker容器

  1. 创建Dockerfile文件
#生成的新镜像以centos7镜像为基础
FROM centos:7
MAINTAINER by jesse (jesse152@163.com)
#升级系统
RUN yum -y update
#安装openssh-server
RUN yum -y install openssh-server
#修改/etc/ssh/sshd_config
RUN sed -i 's/UsePAM yes/UsePAM no/g' /etc/ssh/sshd_config

# 生成sshkey
RUN ssh-keygen -t dsa -f /etc/ssh/ssh_host_dsa_key
RUN ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key

#变更root密码
RUN echo "root:jesse131978"|chpasswd
#开放窗口的22端口
EXPOSE 22
#运行脚本,启动sshd服务
CMD    ["/usr/sbin/sshd", "-D"]

2.在dockerfile文件同级目录中运行创建命令

docker build -t centos7_ssh .

命令成功后,就会创建一个名字为centos7_ssh的image,可以使用“docker images”来查看
3. 根据镜像创建容器

docker run -d -P --name=ssh_box centos7_ssh
  1. 查看容器ip
docker inspect ssh_box

5.查看端口

docker port ssh_box 22

知道ip和端口后就可以通过ssh建立连接了

远程Dockerfile

我将Dockerfile文件上传至github,可通过命令直接用github上的Dockerfile

docker build -t linux git@github.com:Jesse121/mylinux.git
参考文章
  1. Docker容器使用问题:Failed to get D-Bus connection: Operation not permitted
  2. ssh 直接登录docker容器
posted @ 2020-08-22 10:26  Jesse131  阅读(18994)  评论(0编辑  收藏  举报