Window10 通过 SSH 访问 Docker 容器

文章顺序

  1. 使用 Docker 搭建 Jenkins 与 GitLab 环境,实现私有 GitLab 项目触发 Webhooks 构建 (环境搭建)
  2. Window10 通过 SSH 访问 Docker 容器(SSH 连接问题解决)
  3. 基于 Docker 实现 GitLab + Jenkins 编译 Laravel 项目并部署多台服务器(部署实战)

参考

问题

  1. 本地主机连接 Docker 容器报错:kex_exchange_identification: Connection closed by remote host
    因为被连接的容器 ssh 服务不是自启动,所以需要手动启动 service ssh start
  2. Docker 容器 ssh 连接其他容器报错:ssh: connect to host 容器名称 port 22: Connection refused(本文容器互联是通过 docker-compose 指定连接同一网络实现)
    因为被连接的容器 ssh 服务不是自启动,所以需要手动启动 service ssh start

环境

软件/系统 版本 说明
Windows Windows 10 专业版 22H2 19045.4046
Docker Desktop 4.27.1
Docker 25.0.2
Docker Compose v2.24.3-desktop.1
debian debian:12-slim Docker 镜像

正文

文件列表

./docker-compose-server.yml
./debian/
	Dockerfile
	sources.list
  1. docker-compose-server.yml

    version: '3'
    services:
      php1:
    	build: ./debian
    	networks:
    	  - servernetwork
    	container_name: php1
    	ports:
    	  - "8081:8000"
    	  # 本地主机访问容器ssh为:ssh root@127.0.0.1 -p 2021
    	  - "2021:22"
    	# 相当于 -d,防止执行完毕后关闭容器 https://blog.csdn.net/fighterandknight/article/details/124478429
    	stdin_open: true
    networks:
      servernetwork:
    
    
  2. debian/Dockerfile

    FROM debian:12-slim
    
    COPY sources.list /etc/apt/
    
    WORKDIR /code
    
    # 设置root密码 https://blog.csdn.net/qq_27865227/article/details/121649574
    RUN apt-get update && \
    	apt-get install -y openssh-server && \
    	apt-get install -y net-tools && \
    	echo "PermitRootLogin yes" >> /etc/ssh/sshd_config && \
    	echo "root:123456" | chpasswd
    # 启动容器后,启动 ssh 服务
    CMD service ssh start
    
  3. debian/sources.list

    deb https://mirrors.aliyun.com/debian/ bookworm main non-free non-free-firmware contrib
    deb-src https://mirrors.aliyun.com/debian/ bookworm main non-free non-free-firmware contrib
    deb https://mirrors.aliyun.com/debian-security/ bookworm-security main
    deb-src https://mirrors.aliyun.com/debian-security/ bookworm-security main
    deb https://mirrors.aliyun.com/debian/ bookworm-updates main non-free non-free-firmware contrib
    deb-src https://mirrors.aliyun.com/debian/ bookworm-updates main non-free non-free-firmware contrib
    deb https://mirrors.aliyun.com/debian/ bookworm-backports main non-free non-free-firmware contrib
    deb-src https://mirrors.aliyun.com/debian/ bookworm-backports main non-free non-free-firmware contrib
    

步骤

  1. 创建并运行容器:
    docker-compose -f docker-compose-server.yml up -d
    
  2. 主机 CMD 连接容器
    # ssh 容器用户名@容器所在主机ip地址 -p 容器映射到容器所在主机的端口
    # 之前一直尝试 ssh 地址为容器地址,是不对的,正确的是容器所在主机的ip+映射到主机的端口号。
    ssh root@127.0.0.1 -p 2021
    
posted @   夏秋初  阅读(303)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示