You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Docker容器到服务器的SSH无密码认证?

SSH无密码认证配置指南(Docker容器 ↔ Ubuntu服务器)

Hey there! Let's get that passwordless SSH authentication working between your Docker container and the target server. Since you've already got the foundational setup done, here's a straightforward, step-by-step walkthrough tailored to your scenario:

1. 在Docker容器中生成SSH密钥对

Since your container runs with root privileges, we'll generate keys under the root user:

  • First, access your running container (replace <container-name-or-id> with your actual container's name or ID):
    docker exec -it <container-name-or-id> bash
    
  • Generate an RSA key pair—just press Enter for all prompts to use default settings:
    ssh-keygen -t rsa
    

This creates two files in /root/.ssh/: id_rsa (private key, keep this secure!) and id_rsa.pub (public key, which we'll share with the server).

2. 将容器的公钥添加到服务器的authorized_keys

We have two easy methods to do this:

Method 1: Use ssh-copy-id (simplest, if you can SSH to the server with a password)

From inside the container, run:

ssh-copy-id ramparn@173.33.255.20

When prompted, enter the password for the ramparn user on the server. This will automatically append your container's public key to the server's authorized_keys file.

Method 2: Manual copy (if ssh-copy-id isn't available)

  • Inside the container, print your public key and copy the entire output:
    cat /root/.ssh/id_rsa.pub
    
  • Switch to your server's terminal, log in as the ramparn user:
    su - ramparn
    
  • Ensure the .ssh directory exists with correct permissions:
    mkdir -p ~/.ssh && chmod 700 ~/.ssh
    
  • Append the copied public key to authorized_keys (replace <your-container-public-key> with the text you copied):
    echo "<your-container-public-key>" >> ~/.ssh/authorized_keys
    
  • Lock down permissions for authorized_keys (critical for SSH to accept it):
    chmod 600 ~/.ssh/authorized_keys
    

3. 测试无密码登录

From inside your Docker container, run:

ssh ramparn@173.33.255.20

You should be logged into the server as ramparn without entering a password!

Troubleshooting Common Issues

  • No ssh command in the container: Install the OpenSSH client first:
    apt update && apt install -y openssh-client
    
  • Server rejects public key: Check the SSH config on the server:
    1. Edit /etc/ssh/sshd_config (as root on the server) and ensure these lines are uncommented:
      PubkeyAuthentication yes
      AuthorizedKeysFile .ssh/authorized_keys
      
    2. Restart the SSH service:
      sudo systemctl restart sshd
      
  • Firewall blocking access: Make sure the server's port 22 is open to your container's IP address.

内容的提问来源于stack exchange,提问作者user9294423

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:38:30