Window10 通过 SSH 访问 Docker 容器

夏秋初的学习笔记 / 2024-02-19 / 原文

参考

  • https://zhuanlan.zhihu.com/p/462481693
  • https://blog.csdn.net/piaopu0120/article/details/120550181
  • https://blog.csdn.net/qq_27865227/article/details/121649574
  • https://blog.csdn.net/fighterandknight/article/details/124478429

环境

软件/系统 版本 说明
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
    
    # 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