
Two different problems
| Message | Meaning | Look at |
|---|---|---|
| Connection timed out | Packets never reach the instance (network) | Security group, public IP, route table, NACL, firewall |
| Connection refused | Reached the host but nothing listens on 22 | sshd stopped, wrong port, instance still booting |
| Permission denied (publickey) | Reached sshd, login rejected | Key file, user name, file permissions |
Fix "Connection timed out"
- Security group inbound rule: SSH, TCP 22, source = your public IP (
My IPin the console). Your IP changes on home and mobile networks. - The instance needs a public IPv4 address or Elastic IP, and you must use that address, not the private 10.x/172.x one.
- The subnet route table needs
0.0.0.0/0 → igw-.... A private subnet (route to a NAT gateway) cannot accept inbound SSH from the internet. - Network ACL: allow inbound 22 and outbound ephemeral ports 1024-65535 (NACLs are stateless).
- Office or college networks often block outgoing port 22: try from a mobile hotspot to test.
- Use EC2 Instance Connect or Reachability Analyzer in the console to test the path.
Fix "Permission denied (publickey)"
- Use the right user for the AMI:
ec2-user(Amazon Linux),ubuntu(Ubuntu),admin(Debian),centosorrockyfor those images. - Use the key pair chosen at launch:
ssh -i mykey.pem ec2-user@<public-ip>. - Fix key permissions on Linux or Mac:
chmod 400 mykey.pem(SSH refuses keys readable by others). - Lost the key? Use Session Manager or EC2 Instance Connect to get in, then add a new public key to
~/.ssh/authorized_keys.
Better: no SSH at all
AWS Systems Manager Session Manager gives a shell in the browser or CLI (aws ssm start-session --target i-...) without opening port 22 or managing keys. The instance needs the SSM agent (included in Amazon Linux and Ubuntu AMIs), an instance profile with the AmazonSSMManagedInstanceCore policy, and a route to the SSM endpoints. Every session can be logged, which auditors like.
Questions
Is it safe to allow SSH from 0.0.0.0/0?
No. Bots scan port 22 constantly. Allow only your IP, or use Session Manager and close port 22 completely.
Why did SSH work yesterday and time out today?
Usually your public IP changed, so the security group rule no longer matches, or the instance was stopped and started and got a new public IP.