Understanding Public and Private IP Behavior in AWS EC2
When working with AWS EC2 instances, it's important to understand how public and private IP addresses behave, especially when stopping, starting, and connecting to instances. In this article, we’ll explore these concepts and how to use Elastic IPs to maintain a persistent public IP.
1. Public vs. Private IPv4 in AWS
Each EC2 instance is assigned both a public IPv4 and a private IPv4:
- Public IPv4:
- Used to connect to the instance via SSH from the internet.
- Changes when the instance is stopped and restarted unless an Elastic IP is used.
- Private IPv4:
- Used for internal communication within AWS VPC (Virtual Private Cloud).
- Remains constant even when the instance is stopped and started.
- Cannot be used for SSH access unless connected via a VPN or another instance inside the VPC.
Example Scenario: Connecting via SSH
-
An instance is running with a public IPv4 (e.g., 54.123.45.67).
-
Using this IP, we can connect via:
ssh -i my-key.pem [email protected]
-
Once connected, we can see the private IP assigned to the instance (e.g., 10.0.0.5).
-
If we try to SSH using the private IP from an external network, it won't work since private IPs are not accessible over the internet.
2. What Happens When an Instance is Stopped and Started?
- When an instance is stopped, AWS releases the public IPv4.
- When the instance is started again, it is assigned a new public IPv4.
- The private IPv4 remains unchanged.
Example Test:
- Stop the EC2 instance.
- Note down the public IPv4 before stopping.