Docker-跨主机ssh登录容器

一、 软件部署

1.安装docker

# 在线安装(阿里云镜像)
## 配置docker仓库
wget https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.rep -O /etc/yum.repos.d/docker-ce.repo
## yum 安装
sudo yum install docker-ce-19.03.15 docker-ce-cli-19.03.15 containerd.io
##启动docker
sudo systemctl start docker

# 离线安装
rpm -ivh lxc-libs-1.0.9-1.el6.x86_64.rpm
rpm -ivh lua-alt-getopt-0.7.0-1.el6.noarch.rpm
rpm -ivh lua-filesystem-1.4.2-1.el6.x86_64.rpm
rpm -ivh lua-lxc-1.0.9-1.el6.x86_64.rpm  
rpm -ivh lxc-1.0.9-1.el6.x86_64.rpm  
rpm -ivh docker-io-1.7.1-2.el6.x86_64.rpm
rpm -ivh device-mapper-libs-1.02.117-12.el6.x86_64.rpm --force --nodeps

2.拉取镜像,可以选择centos或者ubuntu系统

 docker pull [image_name]

3.使用镜像启动一个简易版容器

 docker run -itd -e "container=docker" --privileged=true --name [docker_name] -h [docker_name] [image_name]

4.容器内安装好Vim、SSH等工具,并配置好root密码,可参考网上教程

 # docker cp实现容器与宿主机直接文件拷贝,例
docker cp ./file1 nos1:/root/
docker cp nos1:/root/ ./file2

5.配置ssh
为避免端口冲突,如果宿主机也要使用ssh功能的话,最好监听端口修改,比如把宿主机监听端口设置为8899

#sed -i 's/#PubkeyAuthentication/PubkeyAuthentication/' /etc/ssh/sshd_config
#sed -i 's/#PasswordAuthentication/PasswordAuthentication/' /etc/ssh/sshd_config
#sed -i 's/#PermitEmptyPasswords/PermitEmptyPasswords/' /etc/ssh/sshd_config

6.编辑启动脚本/etc/rc.local使得容器启动后ssh服务正常启动

#!/bin/sh -e

# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.

/etc/init.d/ssh start &
/bin/bash
exit 0

7.将该容器提交成镜像,防止容器被误删后,所有东西丢失

docker commit -p nos1 nos1:2022 

二、环境启动

1.网络环境

使用VMware虚拟机模拟环境,本次测试网卡仅使用Host-Only模式

PC(VMnet1) : 192.168.57.1
虚拟机(ens33) : 192.168.57.128
容器(eth0) : 192.168.100.2

虚拟机ssh监听8899端口

2.配置docker,并使之生效

#vim /etc/docker/daemon.json
{
"registry-mirrors": ["https://docker.mirrors.ustc.edu.cn"] ,
"bip":"192.168.100.1/24"
}
#保存退出后执行
systemctl daemon-reload
systemctl restart docker

3.启动容器

# 创建容器
docker run -itd -e "container=docker" --privileged=true --name nos1 -h nos1 -p 10000:22 nos1:2022 /etc/rc.local

#容器启动后内部会创建网卡eth0,IP为192.168.100.2,可使用命令进入查看
docker exec -it nos1 bash

三、测试结果

1.宿主机IP测试

# 虚拟机能正常ping通并ssh登录
ping 192.168.57.128

ssh root@192.168.57.128 -p8899

# 可通过宿主机IP ssh登录容器,10000是容器映射出来的端口,此时ssh登录的是容器nos1
ssh root@192.168.57.128 -p10000

2.容器IP测试

# 此时因为192.168.57.0/24与192.168.100.0/24不是同一网段
# 要想达到ssh登录容器的目的需要在PC上配置静态路由

route add -p 192.168.100.0 mask 255.255.255.0 192.168.57.128

经验证,配置好静态路由后可以ssh登录容器,但好像无法ping通容器IP,暂不知具体原因

ssh root@192.168.100.2
点赞

发表回复

电子邮件地址不会被公开。必填项已用 * 标注