5

I can't connect to another EC2 instance in the same security group using public ip.

If I try to connect using public DNS name and private ip, it is working fine.

What I have done so far:

  • created two EC2 public instances
  • attached both instances to security group sg-12345
  • added inbound rules
    • all traffic, source=sg-12345
    • SSH port=22, source= my ip (this is to login into my EC2 instance from my desktop)
dur
  • 15,689
  • 25
  • 79
  • 125
hkonala
  • 319
  • 1
  • 3
  • 7
  • Add EC2 IP too to your SG-12345, like you did for source=MY ip. As @Mark B answered, when you use public IP and EC2 IP is not listed in security group, request will be rejected. Any specific reason to go with public IP while you are within same VPC? – kosa Jun 20 '17 at 18:58
  • @kosa As i have already specified, i added my desktop ip to the rule.i'm able to login to the instance A. But i cannot ssh from A to B using B's public IP address. – hkonala Jun 20 '17 at 19:07
  • Harish, read Mark answer one more time, when you use B public IP to access it from A, B thinks A is NOT within security group. So, now you need to add A IP to security group to allow A to talk to B. To avoid this extra security group configuration, better use B's private IP while connecting from A. – kosa Jun 20 '17 at 19:10
  • 2
    Note that AWS resolves EC2 public DNS hostnames to the public IP of the instance if you're outside the network of the instance, but to the private IP if you're inside the network of the instance. That's why you were able to SSH to the public hostname (because it resolved to the private IP). – jarmod Jun 20 '17 at 19:53

1 Answers1

12

When you use public IP the traffic exits your VPC and comes back in, at which point it is no longer identified as coming from that security group. It looks just like random Internet traffic at that point. Stick to using private IP for both security and speed.

From the docs:

When you specify a security group as the source for a rule, traffic is allowed from the network interfaces that are associated with the source security group for the specified protocol and port. Incoming traffic is allowed based on the private IP addresses of the network interfaces that are associated with the source security group (and not the public IP or Elastic IP addresses).

valid
  • 1,858
  • 1
  • 18
  • 28
Mark B
  • 183,023
  • 24
  • 297
  • 295
  • This did the trick for me. I am using a Squid Proxy on an EC2 instance where some traffic passes through it. I had specific the public IP address - which meant that the traffic was exiting and then coming back. This was giving me connecting refused even though i had specified the SG. After changing to private IP, all works fine. – alext Feb 12 '23 at 13:45