如何实现Docker容器到服务器的SSH无密码认证?
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
ramparnuser:su - ramparn - Ensure the
.sshdirectory 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
sshcommand 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:
- Edit
/etc/ssh/sshd_config(as root on the server) and ensure these lines are uncommented:PubkeyAuthentication yes AuthorizedKeysFile .ssh/authorized_keys - Restart the SSH service:
sudo systemctl restart sshd
- Edit
- Firewall blocking access: Make sure the server's port 22 is open to your container's IP address.
内容的提问来源于stack exchange,提问作者user9294423

