用ssh连接docker容器

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

1、拉取镜像,这里采用centos:7作为基础镜像

  docker pull centos:7

2、运行镜像,生成容器

  docker run -d --name ssh_box --privileged=true centos:7 /usr/sbin/init

  07228ec257564c4874ca24216d651bda65573d49e4149064a079cacca27de4e1 # 生成的容器ID

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

3、进入刚刚生成的容器,修改密码

  docker exec -it 07228ec25756 /bin/bash
  passwd

4、安装vim和openssh

  yum install  -y vim openssh-server openssh-clients

5、修改ssh配置文件

  vim /etc/ssh/sshd_config

  修改如下:

  PubkeyAuthentication yes #启用公钥私钥配对认证方式

  AuthorizedKeysFile .ssh/authorized_keys #公钥文件路径(和上面生成的文件同)

  PermitRootLogin yes #root能使用ssh登录

  ClientAliveInterval 60 #参数数值是秒 , 是指超时时间 ClientAliveCountMax 3 #设置允许超时的次数

6、重启ssh,设置开机启动

  systemctl restart sshd

  systemctl enable sshd

7、退出容器,保存更改

  exit

8、用刚刚修改的容器创建镜像

  docker commit -m 'docker for ssh' -a 'bigstar0207' 07228ec25756 centos-ssh

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

9、用新创建的镜像生成新的容器并映射主机端口到容器22端口

  docker run -d -p 2222:22 ssh_box /usr/sbin/sshd -D

10、连接新生成的容器

  通过ssh root@宿主机IP -p:2222 登录新生成的容器

以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 .

3、根据镜像创建容器

  docker run -d -P --name=ssh_box centos7_ssh

4、查看容器IP和端口

  docker inspect ssh_box

  docker port ssh_box 22

  根据IP和端口连接

可将dockerfile文件上传至远程代码仓库,后期可以直接远程创建镜像

docker build -t centos7_ssh git@github.com:jesse121/centos7_ssh

原文来自:https://www.cnblogs.com/jesse131/p/13543308.html

原文地址:https://www.cnblogs.com/bigstar0207/p/14308363.html