在Docker 建立一个SSH连接的 Ubuntu 容器

  1. 在一个文件夹中创建dockerfile 文件,文件内容如下

    powershell 复制代码
    # 使用官方的 Ubuntu 镜像
    FROM ubuntu:latest
    
    # 安装 SSH 服务
    RUN apt-get update && apt-get install -y openssh-server
    
    # 创建 SSH 目录并设置权限
    RUN mkdir -p /var/run/sshd && ssh-keygen -A
    RUN echo 'root:123456' | chpasswd
    
    # 显式开启 root + 密码登录,避免不同基础镜像默认值差异
        # PermitRootLogin yes:允许 root 登录
        # PasswordAuthentication yes:允许密码认证
        # KbdInteractiveAuthentication no:关闭交互式认证(避免和密码认证混杂)
        # UsePAM no:关闭 PAM(容器场景常用于减少兼容问题)
    RUN sed -ri 's/^#?PermitRootLogin\s+.*/PermitRootLogin yes/' /etc/ssh/sshd_config \
        && sed -ri 's/^#?PasswordAuthentication\s+.*/PasswordAuthentication yes/' /etc/ssh/sshd_config \
        && sed -ri 's/^#?KbdInteractiveAuthentication\s+.*/KbdInteractiveAuthentication no/' /etc/ssh/sshd_config \
        && sed -ri 's/^#?UsePAM\s+.*/UsePAM no/' /etc/ssh/sshd_config
    
    # 暴露 SSH 端口
    EXPOSE 22
    
    # 设置容器启动时自动运行 SSH 服务
    CMD ["/usr/sbin/sshd", "-D"]
  2. dockerfile 文件所在的文件夹中打开终端,输入如下命令构建一个镜像,镜像名字叫ubuntu-with-ssh

    powershell 复制代码
    docker build -f dockerfile -t ubuntu-with-ssh .
  3. 在终端中输入如下命令,将根据镜像运行一个容器,容器名字叫 ubuntu-ssh

    powershell 复制代码
    docker run -d -p 2222:22 --name ubuntu-ssh ubuntu-with-ssh
  4. 在终端中使用如下命令,根据提示输入密码,就可以连接ubuntu 了

    • 注意:端口用的是主机的 2222 端口
    powershell 复制代码
    ssh root@127.0.0.1 -p 2222
    • 如果是使用软件连的,可以参考图片
相关推荐
java_logo5 小时前
Docker 部署 NetBox:轻松搭建 IPAM / DCIM 网络资产管理平台
docker·容器·轩辕镜像·netbox部署·netbox部署方案·netbox部署文档·docker部署netbox
码农阿豪5 小时前
【金仓数据库征文】Mac开发环境|SpringBoot3 + MyBatisPlus对接KES V9 Docker实战全指南
数据库·macos·docker
PC2005-cloud6 小时前
从零上手 openGauss:Docker 部署 + 全场景连接教程
运维·docker·容器
AlfredZhao9 小时前
Docker 查看容器日志:别只记 `docker logs -f`
docker
初级炼丹师(爱说实话版)12 小时前
Ubuntu服务器配置docker
服务器·ubuntu·docker
生活爱好者!13 小时前
NAS还能用来开视频会议?docker一键部署MiroTalk SFU
运维·docker·容器
兵bing15 小时前
Docker Compose 进阶配置与最佳实践笔记
docker
是良辰15 小时前
Docker Nginx HTTPS 自签证书部署完整操作文档
nginx·docker·https
bellus-16 小时前
Ubuntu 26.04 Miniforge3 安装与配置完整指南
linux·运维·ubuntu
@CLoudbays_Martin1116 小时前
网站被攻击,服务器都登录不了怎么办?
服务器·ssh·ddos