AWS EC2 Security Groups
Use EC2 security groups as stateful firewalls by defining inbound and outbound rules based on ports, CIDR ranges, and other security groups.
Security groups are AWS’s built-in stateful firewall for EC2 and many other services. They control which traffic is allowed in and out based on protocol, port, and source or destination. Because they are stateful, return traffic for an allowed request is automatically permitted, which makes them simpler to reason about than traditional stateless firewall rules.
Inbound rules define who can reach the resource. Outbound rules define where the resource can initiate connections. Sources can be IP ranges in CIDR notation or other security groups. Referencing another security group is powerful because it lets you describe trust between tiers without hard-coding instance IP addresses.
| Pattern | Example rule |
|---|---|
| Web server | Allow TCP 80 and 443 from 0.0.0.0/0 |
| SSH admin access | Allow TCP 22 from a trusted office or VPN CIDR |
| Database tier | Allow TCP 5432 from the application security group |
| Private egress | Restrict outbound traffic to known destinations if required |
A good pattern is layered access. Public load balancers may accept internet traffic, application servers may accept traffic only from the load balancer’s security group, and databases may accept traffic only from the application group. That design is cleaner and safer than allowing broad CIDR ranges everywhere.
Beginners often open SSH or database ports to the world for convenience. That may work in a lab, but it is a poor habit. Restrict sources as tightly as possible, document why each rule exists, and review stale rules during regular operations. Security groups are easy to change, which is exactly why they should be managed carefully.
Pair this lesson with AWS VPC because security groups work best when subnet and routing design are already clear.
aws ec2 describe-security-groups --output table
aws ec2 authorize-security-group-ingress --group-id sg-1234567890abcdef0 --protocol tcp --port 22 --cidr 203.0.113.0/24
aws ec2 revoke-security-group-ingress --group-id sg-1234567890abcdef0 --protocol tcp --port 22 --cidr 0.0.0.0/0
Operational note
Treat EC2 instances as managed infrastructure, not pets. Capture launch settings in infrastructure as code, keep bootstrap steps repeatable, and monitor CPU, memory, disk, and patch level from the start. That way replacing an instance is a routine operation instead of a risky manual repair exercise. Shared standards like this make future environments easier to launch, review, and support.
Stateful behavior
What does it mean that an EC2 security group is stateful?
Tiered access
What is a common secure pattern for database security groups?