如何在Docker容器中配置SSH?解决连接失败问题
解决Docker容器SSH连接被拒绝的问题
问题核心原因
你的docker-compose.yml中给host1服务设置了command: tail -F anything,这会直接覆盖Dockerfile里的CMD指令,导致原本应该启动的SSH服务(/usr/sbin/sshd -D)没有运行。同时新版Ubuntu的openssh-server默认需要/run/sshd目录才能启动,你的Dockerfile缺少这一步,双重原因导致容器内没有SSH服务,自然无法连接。
修复步骤
1. 修改Dockerfile,补全SSH服务依赖
FROM ubuntu # 安装SSH服务并创建必要目录 RUN apt-get update && apt-get install -y openssh-server RUN mkdir -p /run/sshd # 设置root密码 RUN echo 'root:password' | chpasswd # 允许root密码登录 RUN sed -i 's/#PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config # 启动SSH服务 CMD ["/usr/sbin/sshd", "-D"]
2. 修改docker-compose.yml,合并启动命令
保留tail命令维持容器前台运行的同时,启动SSH服务:
version: '3' services: host1: build: context: C:\Users\GavinAn\ssh_ubuntu dockerfile: ssh_ubuntu.dockerfile ports: - 5814 - 30303 - 30304 - 30305 - 2222:22 command: sh -c "/usr/sbin/sshd -D & tail -F anything" host2: image: ubuntu ports: - 30303 - 30304 - 30305 command: tail -F anything
验证操作
- 重建并启动容器:
docker-compose down docker-compose build host1 docker-compose up -d - 本地测试SSH连接:
输入密码ssh root@localhost -p 2222password即可登录。 - 用容器IP连接时,直接使用端口22:
ssh root@<容器IP> -p 22
内容的提问来源于stack exchange,提问作者Gavin An
相关产品推荐
相关产品推荐

