0
0
AWScloud~5 mins

Connecting to EC2 instances in AWS - Commands & Configuration

Choose your learning style9 modes available
Introduction
When you launch a virtual server on AWS called an EC2 instance, you need a way to connect to it to manage it. This concept shows how to securely connect to your EC2 instance using SSH, so you can control it like a regular computer.
When you want to install software or update settings on your EC2 server.
When you need to check logs or troubleshoot issues on your EC2 instance.
When you want to deploy your application manually on the EC2 server.
When you need to run commands or scripts directly on the EC2 instance.
When you want to verify that your EC2 instance is running and accessible.
Commands
This command sets the correct permissions on your private key file so SSH will accept it and keep it secure.
Terminal
chmod 400 my-key-pair.pem
Expected OutputExpected
No output (command runs silently)
This command connects you to your EC2 instance using SSH. The -i flag specifies your private key file, and the username and public DNS identify the server.
Terminal
ssh -i my-key-pair.pem ec2-user@ec2-3-15-237-12.us-east-2.compute.amazonaws.com
Expected OutputExpected
Last login: Tue Jun 6 12:34:56 2024 from 203.0.113.25 [ec2-user@ip-172-31-22-33 ~]$
-i - Specifies the private key file for authentication
This command ends your SSH session and disconnects you from the EC2 instance.
Terminal
exit
Expected OutputExpected
logout Connection to ec2-3-15-237-12.us-east-2.compute.amazonaws.com closed.
Key Concept

If you remember nothing else from this pattern, remember: use the correct private key file with proper permissions and the right username to securely connect to your EC2 instance via SSH.

Common Mistakes
Trying to connect without setting the private key file permissions to 400.
SSH refuses to use a key file that is too open for security reasons, causing connection failure.
Run 'chmod 400 my-key-pair.pem' before connecting to restrict permissions.
Using the wrong username for the EC2 instance.
Different AMIs use different default usernames; using the wrong one causes authentication failure.
Use 'ec2-user' for Amazon Linux, 'ubuntu' for Ubuntu AMIs, or check your AMI documentation.
Trying to connect to the wrong public DNS or IP address.
If the address is incorrect or the instance is stopped, SSH cannot reach the server.
Verify the instance is running and use the exact public DNS or IP shown in the AWS console.
Summary
Set the private key file permissions to 400 using chmod before connecting.
Use the ssh command with the -i flag to specify your private key and connect to the EC2 instance.
Exit the SSH session with the exit command when finished.