How To fix Failed to connect to your instance in aws ec2

How To fix Failed to connect to your instance in aws ec2

admin By  September 23, 2025 0 65
learn AWS online

That error usually shows up when you’re trying to connect to an AWS EC2 instance (or another cloud VM) and SSH can’t reach it. Let’s go step by step to fix it.

✅ Troubleshooting Steps for

“Failed to connect to your instance – Error establishing SSH connection”

1) Check if the instance is running

In your AWS console, go to EC2 → Instances.
Make sure the State is running.
If it’s stopped or terminated, you won’t be able to connect.

2) Verify security group rules (firewall)

Open your Security Group attached to the instance.

Ensure you have a rule like this:
Source: Your IP (or 0.0.0.0/0 for testing, but not recommended for security).
Type: SSH
Protocol: TCP
Port Range: 22

3) Confirm the correct key pair

Make sure you’re using the same .pem private key file that was selected when launching the instance. if still facing same issue Then we have last step to fix it.

4) We are trying to fix using Edit User data

Here are the steps you can follow to fix it.

  1. First you can shutdown your ec2 instance.

2) Select ec2instance >Actions >Instance Settings >Edit user data.

Now you can see this window.

3) Put This Script below (modify user data as-text):-

Content-Type: multipart/mixed; boundary=”//”
MIME-Version: 1.0
–//
Content-Type: text/cloud-config; charset=”us-ascii”
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename=”cloud-config.txt”
#cloud-config
cloud_final_modules:
– [scripts-user, always]
–//
Content-Type: text/x-shellscript; charset=”us-ascii”
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename=”userdata.txt”
#! /bin/bash
ls -Al
ls -Al /home
ls -Al /home/ubuntu
ls -Al /home/ubuntu/.ssh
sudo cat /home/ubuntu/.ssh/authorized_keys
chown root:root /home
chmod 755 /home
chown ubuntu:ubuntu /home/ubuntu -R
chmod 700 /home/ubuntu
chmod 700 /home/ubuntu/.ssh
chmod 600 /home/ubuntu/.ssh/authorized_keys
ls -Al
ls -Al /home
ls -Al /home/ubuntu
ls -Al /home/ubuntu/.ssh
sudo cat /home/ubuntu/.ssh/authorized_keys
ufw status
ufw disable
ufw status
systemctl status ssh
systemctl start ssh
systemctl status ssh
systemctl enable ssh
–//

    4) Click Save button and Start Ec2 Instance.

    5) Now Try to connect your ec2 instance through .pem file or directly ec2 dashboard and its successfully connected.

    Thanks for watching….