使用 Instance Connect 时连接到 EC2 实例超时:连接被拒绝
Connection to EC2 instance timed out while using Instance Connect: Connection refused
ID: aws/ec2-instance-connect-connection-refused
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| EC2 API 2016-11-15 | active | — | — | — |
| AWS CLI 2.17.0 | active | — | — | — |
| Amazon Linux 2023 | active | — | — | — |
根因分析
EC2 实例的 SSH 守护进程 (sshd) 未运行,或安全组入站规则不允许来自 AWS Instance Connect IP 范围的 SSH 流量(端口 22),或者实例位于没有互联网访问权限的子网中,无法使用 Instance Connect 服务。
English
The EC2 instance's SSH daemon (sshd) is not running, or the security group inbound rule does not allow SSH traffic (port 22) from AWS Instance Connect IP ranges, or the instance is in a subnet without internet access for the Instance Connect service.
官方文档
https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-connect-set-up.html解决方案
-
Verify sshd is running on the instance by connecting via EC2 Serial Console or using AWS Systems Manager Session Manager: `aws ssm start-session --target instance-id`. Then run `systemctl status sshd` and start it if not running.
-
Ensure the security group allows inbound SSH from AWS Instance Connect IP ranges. Check the current ranges at https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-connect-set-up.html#ec2-instance-connect-inbound. Add a rule for port 22 from the source `35.180.0.0/16` (example for us-east-1).
无效尝试
常见但无效的做法:
-
Restarting the EC2 instance from the AWS Console, assuming a complete reboot will fix the SSH daemon.
70% 失败
If sshd is misconfigured or not enabled, a reboot does not change its state unless the init system is fixed.
-
Adding a security group rule allowing SSH from 0.0.0.0/0, thinking it's a general connectivity issue.
60% 失败
While this may allow SSH, it is overly permissive and does not address the Instance Connect-specific IP ranges or sshd status.