How do I troubleshoot "Connection refused" or "Connection timed out" errors when I use SSH to connect to my EC2 instance with SSH?

9 minute read
2

I receive "Connection refused" or "Connection timed out" errors when I use SSH to connect to my Amazon Elastic Compute Cloud (Amazon EC2) instance.

Short description

If your connection times out, then you get the following error message:

"ssh: connect to host ec2-X-X-X-X.compute-1.amazonaws.com port 22: Connection timed out"

This error message comes from the SSH client. The error indicates that the server didn't respond to the client and the client program gave up (timed out). The following are common causes for this error:

  • The security group or network ACL doesn't allow access.
  • There's a firewall on the instance's operating system.
  • There's a firewall between the client and the server.
  • The host doesn't exist.

If your connection is refused, then you get the following error message:

"ssh: connect to host ec2-X-X-X-X.compute-1.amazonaws.com port 22: Connection refused"

This message comes remotely from a host. The following are common causes for this error:

  • The host reached the instance but there was no service listening on the SSH port.
  • A firewall blocked the package and was set to reject it instead of dropping it.

Resolution

"Connection timed out" error

If you receive the "Connection timed out" error, then verify the following:

  • The instance's IP address or hostname is correct.
  • The instance passes its health checks.
  • The security group of the instance allows incoming traffic on TCP port 22.
  • The network ACLs of the instance subnet allows incoming traffic on TCP port 22 and allows ephemeral ports for the outgoing traffic.
  • The route table of the instance's subnet is configured properly to provide connectivity between the EC2 instance and the SSH client.
  • There isn't a firewall that blocks the connection between the SSH client and the EC2 instance.
  • SSH isn't blocked by the instance's TCP Wrappers (on the Red Hat website).

Note: The last two verification steps require OS-level access to the instance.

"Connection refused" error

If you receive the "Connection refused" error, then verify the following:

  • There's no firewall on the instance that rejects the SSH connection.
  • The SSH daemon (sshd) is running and listening on port 22.

Note: Both verification steps require OS-level access to the instance.

If the instance passes both health checks, use one of the following methods with your configuration

  • Method 1: Use the EC2 Serial Console for Linux.
  • Method 2: Use AWS Systems Manager Session Manager.
  • Method 3: Run the AWSSupport-TroubleshootSSH automation runbook.
  • Method 4: Use a user data script.

Method 1: Use the EC2 Serial Console for Linux

You can configure the EC2 Serial Console for Linux to troubleshoot OS-level issues on supported Nitro-based instance types. The serial console allows you to troubleshoot boot issues, network configuration issues, and SSH configuration issues. The serial console is accessible from the Amazon EC2 console or the AWS Command Line Interface (AWS CLI).

Before you use the serial console, grant access to the console at the account level. Then, create AWS Identity and Access Management (IAM) policies that grant access to your IAM users.

Note: Each instance that uses the serial console must include at least one password-based Linux user with sudo access.

For more information on how to configure the EC2 Serial Console for Linux, see Configure access to the EC2 Serial Console. If there isn't a Linux account with a login password configured, you must run ssm-user to reset the password for an account with sudo access. For more information on how to run ssm-user commands, see Managing ssm-user sudo account permissions on Linux and macOS.

After configuration, connect to the EC2 instance through the EC2 serial console as a password-configured Linux user.

Next, run the following commands. These commands verify that the SSH connections aren't blocked by the OS firewall or TCP wrapper. The commands also verify that the sshd service is running and listening on port 22.

  1. If you have iptables rules configured, then run the following command to add a rule in iptables that accepts all SSH connections on default port 22:

    $ sudo iptables -I INPUT 1 -p tcp --dport 22 -j ACCEPT

    Because it's a best practice to use security groups instead of an OS-based firewall, the firewall can be deactivated altogether. To deactivate the OS-based firewall, use one of the following sets of commands, depending on your operating system:

    Important: The following commands flush all main iptables rules. The commands also add a rule that allows incoming SSH connections. The commands change the default policy of the main chain to ACCEPT so that instance network connectivity isn't affected when the iptables rule is flushed. Because these commands flush all main iptables, they also flush any existing rules.

    Distributions that use UFW (Ubuntu, Debian):

    $ sudo iptables -F$ sudo iptables -P INPUT ACCEPT
    $ sudo ufw disable

    Distributions that use firewalld (Red Hat, CentOS):

    $ sudo iptables -F $ sudo iptables -P INPUT ACCEPT
    $ sudo systemctl disable firewalld

    Note: After you regain access to your instance, review your firewall configuration (UFW, firewalld, iptables).

  2. Verify that SSH is running and verify that the SSH TCP port (22) is in the listening state:

    $ sudo systemctl restart sshd$ sudo ss -tpln | grep -iE '22|ssh'
    LISTEN 0 128 *:22 *:* users:(("sshd",pid=1901,fd=3))
    LISTEN 0 128 [::]:22 [::]:* users:(("sshd",pid=1901,fd=4))

    Note: If your system doesn't have the ss command, you can use the legacy netstat command with the same syntax shown in the preceding example.

  3. Make sure that the TCP wrapper doesn't block an SSH connection:

    $ if [[ $( cat /etc/hosts.[ad]* | grep -vE '^#' | awk 'NF' | wc -l) -ne 0 ]];\
    then sudo sed -i '1i sshd2 sshd : ALL: allow' /etc/hosts.allow; fi
  4. Next, connect to the instance through SSH.

  5. Disconnect the EC2 Serial Console session if it's no longer required.

Method 2: Use AWS Systems Manager Session Manager

Note: To use this method, the instance must be an SSM managed instance and its SSM agent ping status must be Online. For more information on Session Manager and a complete list of prerequisites, see Setting up Session Manager.

Confirm that SSH connections aren't blocked by the firewall or TCP wrapper and that the sshd service is running and listening on port 22. To do so, complete the following steps:

  1. Open the AWS Systems Manager.
  2. Start a session for the instance using Session Manager.
  3. Follow steps 1 - 4 from Method 1: Use EC2 Serial console for Linux.
  4. Close the Session Manager session if it's no longer required.

Method 3: Run the AWSSupport-TroubleshootSSH runbook

The AWSSupport-TroubleshootSSH automation runbook installs the Amazon EC2Rescue tool for Linux on the instance. This tool checks for and attempts to fix issues that prevent a remote connection Linux host through SSH.

To run the AWSSupport-TroubleshootSSH runbook, complete the following steps:

  1. Open the AWSSupport-TroubleshootSSH page.
  2. Select Run this Automation (console).

To learn more, see I'm receiving errors when trying to connect to my EC2 instance using SSH. How can I use the AWSSupport-TroubleshootSSH automation workflow to troubleshoot SSH connection issues?

Method 4: Use a user data script

If none of the methods described are suitable in your environment, then use an EC2 user-data script. The EC2 user-data script turns off the OS-level firewall and the TCP wrapper, and then restarts the sshd service.

Important:

  • This procedure requires a stop and start of the EC2 instance. If the instance has any data stored on instance store volumes, then that data is deleted after the instances stops.
  • If the instance is part of an Amazon EC2 Auto Scaling group, then other instances in the same Auto Scaling group might stop when you terminate the instance.
  • If the instance is launched by services that use AWS Auto Scaling, then other instances in the same Auto Scaling group might stop when you terminate the instance.
  • Instance termination depends on the instance scale-in protection settings for the Auto Scaling group. If the instance is part of an Auto Scaling group, temporarily remove the instance from the Auto Scaling group before you start the resolution steps.
  • Stopping and starting the instance changes the public IP address of the instance. It's a best practice to use an Elastic IP address instead of a public IP address when you route external traffic to the instance.

Follow these steps to configure user-data for the instance:

  1. Open the Amazon EC2 console.

  2. Choose Instances from the navigation pane, and then select the instance that you plan to connect to.

  3. Stop the instance.

  4. Choose Actions, then choose Instance Settings, and then choose Edit User Data.

  5. Copy the following user data script into the Edit User Data dialog box, and then choose Save.

    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
    iptables -P INPUT ACCEPT
    iptables -F
    systemctl restart sshd.service || service sshd restart
    if [[ $( cat /etc/hosts.[ad]* | grep -vE '^#' | awk 'NF' | wc -l) -ne 0 ]];\
    then sudo sed -i '1i sshd2 sshd : ALL: allow' /etc/hosts.allow; fi
    --//
  6. Connect to the instance through SSH.

  7. The preceding user data script is set to run on every reboot of the instance. After you regain access to the instance, remove the user-data script.

Note: This method flushes all main iptables rules. After you regain access to the instance, review the firewall configuration for accuracy (for example, UFW, firewalld, iptables).

To remove user data, complete the following steps:

  1. Complete steps 1 - 4 from Method 4: Use a user data script.
  2. Delete the user data script in the Edit User Data dialog box.

Related information

Error connecting to your instance: Connection timed out

How do I troubleshoot Amazon EC2 instance connection timeout errors from the internet?

How can I troubleshoot connecting to my Amazon EC2 Linux instance using SSH?

Why is my EC2 Linux instance unreachable and failing its status checks?

AWS OFFICIAL
AWS OFFICIALUpdated 4 days ago
5 Comments

Check if kes are in SHA-1 or some warrants - if yes then try "update? change keys to RSA . The another advice is if you user PUTTY for SSH connection, followed steps are recommended:

  • backup all keys (and on your decision PUTTY confit)
  • install (update )putty to the latest stable version
  • try to connect, in case of no change disable/enable compression and check connection

Trying to lower key file access privileges may also help mostly if not only you are only user of one stem account.

In my opinion upgrading keys to the latest standard (avoiding MD5 fingerprinting) or changing them to latest version will help. If this is new instance and you can't connect - verify Security Groups for PORT 22 - if port is open limit it to accept only your IP and try to connect. Soft restart of instance may be some solution in scenarios of resources problem.

Not elegant way that helps (USE IT ONLY AT INSTANCES WITHOUT CRITICAL/LIVE SERVICES to avoid data loss, USE OF IT IS JUST EXAMPLE based on own experience where asap action was needed and this fast way helped , in my case it was data breach - it was on ARM IoT device without chance to physical access over the same day) sio "hard reset" allowed our learning emploee diagnoze data breach and secure device with redirect pockets for analyse. On AWS use this only as I advised - DO NOT USE or USE at very last choice ;)

replied a year ago

Thank you for your comment. We'll review and update the Knowledge Center article as needed.

profile pictureAWS
MODERATOR
replied a year ago

I was experiencing this same error message "Connection Timed Out", when I tried to SSH using the SSH Client, at that moment my security group was only permitting inbound traffic via SSH from my local IP, but when I reconfigured it to allow SSH traffic from anywhere (0.0.0.0), the error message cleared and I was able to successfully SSH into the Amazon Linux 2 instance.

I had to use this type of security group configuration, because this was a testing environment, so in a production environment, how does one resolve this error message when using a local IP from my computer?

Thanks

replied 9 months ago

Thank you for your comment. We'll review and update the Knowledge Center article as needed.

profile pictureAWS
MODERATOR
replied 9 months ago

Here is the official resolution video from AWS. Please check it out.

How do I fix Connection refused or Connection timed out errors when connecting to an EC2 instance? https://www.youtube.com/watch?v=b1K0CNYxtC0

profile picture
replied 2 months ago