Chapter 5: Network and security groups¶
5.1 Layout¶
Internet
│ 80/443 only
┌─────────▼──────────┐ SG: <project>-<env>-ec2
│ EC2 (public subnet)│ nginx → 127.0.0.1:8000 → gunicorn (Docker)
│ Elastic IP │ Redis/Celery on internal Docker networks
└─────────┬──────────┘
│ 5432 (source = <project>-<env>-ec2)
┌─────────▼──────────┐ SG: <project>-<env>-rds
│ RDS (private subnets) │ Public access: No
└─────────────────────┘
SSH: only from <office IP>/32, or no port 22 at all (Session Manager)
Use the default VPC only if you understand its subnets are public (they route to an internet gateway). For RDS, create a DB subnet group of private subnets (route table without 0.0.0.0/0 → igw-…).
5.2 Security groups (create these BEFORE launching anything)¶
VPC → Security groups → Create security group. Name and description are permanent (H3). Give every rule a description.
<project>-<env>-ec2: "<env> app server: web public, SSH office only"
| Dir | Type | Port | Source | Description |
|---|---|---|---|---|
| In | HTTPS | 443 | 0.0.0.0/0 (+ ::/0 if IPv6) | HTTPS public |
| In | HTTP | 80 | 0.0.0.0/0 (+ ::/0) | Redirect to HTTPS + certbot |
| In | SSH | 22 | <office IP>/32 |
SSH from office (omit if using Session Manager) |
| Out | All | All | 0.0.0.0/0 | default |
<project>-<env>-rds: "<env> RDS: Postgres from <env> app only"
| Dir | Type | Port | Source | Description |
|---|---|---|---|---|
| In | PostgreSQL | 5432 | security group <project>-<env>-ec2 |
Postgres from app |
Never add: 8000, 5432, 6379, or "All traffic" from 0.0.0.0/0.
Find your office IP from the office network: curl -s https://checkip.amazonaws.com.
5.3 Changing security groups on running systems (zero downtime pattern)¶
- Add the new rule/group alongside the old one (rules are additive).
- Verify the service still works (DB check, site check).
- Remove the old rule/group.
- Verify again from inside and from outside.
Warning
Keep an SSH session open while changing SSH rules; open a new session to confirm before closing the old one. A wrong office IP otherwise locks you out.