How to Fix AWS EC2 SSH Connection Refused Error
In this tutorial, you'll learn about How to Fix AWS EC2 SSH Connection Refused Error. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
You try to SSH into your EC2 instance and get Connection refused or Operation timed out — the instance is not accepting SSH connections.
Step-by-Step Fix
1. Check security group inbound rules
aws ec2 describe-security-groups --group-ids sg-12345678
Look for SSH (port 22) in the output:
{
"IpPermissions": [
{
"FromPort": 22,
"ToPort": 22,
"IpProtocol": "tcp",
"IpRanges": [{"CidrIp": "0.0.0.0/0"}]
}
]
}
2. Add SSH inbound rule if missing
aws ec2 authorize-security-group-ingress --group-id sg-12345678 --protocol tcp --port 22 --cidr 0.0.0.0/0
3. Verify the key pair
ssh -i ~/.ssh/my-key.pem ec2-user@54.123.45.67 -vvv
Expected output on success:
debug1: Authentication succeeded (publickey).
debug1: channel 0: new [client-session]
4. Check instance status
aws ec2 describe-instance-status --instance-ids i-12345678
Expected output:
{
"InstanceStatuses": [
{
"InstanceId": "i-12345678",
"InstanceState": {"Name": "running"},
"SystemStatus": {"Status": "ok"},
"InstanceStatus": {"Status": "ok"}
}
]
}
5. Fix key permissions
chmod 400 ~/.ssh/my-key.pem
6. Check network ACLs
aws ec2 describe-network-acls --filters Name=association.subnet-id,Values=subnet-12345678
Ensure inbound/outbound rules allow port 22 traffic.
Common Mistakes
| Mistake | Fix |
|---|---|
| Wrong key file | Use the correct .pem file that matches the instance |
| Key permissions too open | Run chmod 400 key.pem |
| Wrong username | Use ec2-user (Amazon Linux), ubuntu (Ubuntu), or admin |
| Security group missing SSH | Add inbound rule for port 22 |
| Instance not running | Start the instance |
Prevention
- Use EC2 Instance Connect for browser-based SSH.
- Restrict SSH access to your IP address only.
- Use Systems Manager Session Manager for password-less access.
- Keep security group rules minimal.
Common Mistakes with ec2 ssh
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging
These mistakes appear frequently in real-world AWS code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro