How to Connect to an AWS EC2 Instance Easily
To connect to an EC2 instance, use
ssh with your private key and the instance's public IP address like ssh -i your-key.pem ec2-user@public-ip. Make sure your security group allows SSH (port 22) access from your IP.Syntax
The basic command to connect to an EC2 instance via SSH is:
ssh -i <path-to-private-key> <user>@<public-ip-address>Here:
-i <path-to-private-key>: Specifies the path to your private key file (.pem) downloaded from AWS.<user>: The username depends on the instance OS (e.g.,ec2-userfor Amazon Linux,ubuntufor Ubuntu).<public-ip-address>: The public IP or DNS of your EC2 instance.
bash
ssh -i /path/to/my-key.pem ec2-user@203.0.113.25Example
This example shows how to connect to an Amazon Linux EC2 instance using SSH with a private key file named my-key.pem and the instance's public IP 203.0.113.25.
bash
chmod 400 my-key.pem ssh -i my-key.pem ec2-user@203.0.113.25
Output
Warning: Permanently added '203.0.113.25' (ECDSA) to the list of known hosts.
[ec2-user@ip-203-0-113-25 ~]$
Common Pitfalls
- Incorrect permissions on the private key file: The key file must have restricted permissions (use
chmod 400). - Wrong username: Use the correct user for your instance OS (e.g.,
ec2-user,ubuntu,admin). - Security group blocking SSH: Ensure port 22 is open for your IP in the instance's security group.
- Using the wrong IP address: Use the public IP or public DNS, not the private IP, unless connected via VPN or inside the same network.
bash
Wrong: ssh -i my-key.pem root@203.0.113.25 Right: ssh -i my-key.pem ec2-user@203.0.113.25
Quick Reference
Keep these tips in mind when connecting to EC2:
- Use
chmod 400on your private key file. - Match the username to your instance OS.
- Check security group rules allow SSH from your IP.
- Use the instance's public IP or DNS name.
Key Takeaways
Use SSH with your private key and the correct username to connect to EC2.
Set private key file permissions to 400 to avoid SSH errors.
Ensure security groups allow inbound SSH (port 22) from your IP address.
Use the instance's public IP or DNS, not the private IP, for connection.
Match the SSH username to the EC2 instance's operating system.