Chapter 6: The EC2 server¶
6.1 Launch (console)¶
EC2 → Instances → Launch instances:
| Section | Choose | Watch out |
|---|---|---|
| Name and tags | <project>-<env>-app + Project/Environment/Owner tags |
|
| Application and OS image | Ubuntu Server LTS (current) | Never a snapshot/AMI of another environment (H13) |
| Instance type | Sized for the app | |
| Key pair | A new key pair per environment (<project>-<env>), or "Proceed without a key pair" if you'll use Session Manager |
Never reuse staging's key on production |
| Network settings → Edit | VPC, public subnet, Auto-assign public IP: enable (an Elastic IP comes later) | |
| Firewall (security groups) | Select existing security group → <project>-<env>-ec2 |
Do not use "Create security group" (it creates launch-wizard-N with SSH from anywhere: H2) |
| Configure storage | gp3, size with headroom; Encrypted (on if 2.3 is done) | |
| Advanced details → IAM instance profile | A role with AmazonSSMManagedInstanceCore (for Session Manager) + only the app's needed permissions |
|
| Advanced details → Metadata version | V2 only (token required) | |
| Advanced details → Termination protection | Enable for production |
Caution
Never use the wizard's Create security group option. It creates a group named launch-wizard-N with SSH open to the whole internet (H2). Create named groups first (Chapter 5) and pick Select existing security group.
After launch: EC2 → Elastic IPs → Allocate → Associate with the instance (H14). Point DNS at the Elastic IP.
6.2 First login hardening¶
sudo apt update && sudo apt -y full-upgrade
sudo apt -y install unattended-upgrades && sudo dpkg-reconfigure -plow unattended-upgrades
sudo timedatectl set-timezone UTC
# SSH: keys only, no root login
sudo sshd -T | grep -E '^(passwordauthentication|permitrootlogin|pubkeyauthentication)'
# want: passwordauthentication no · permitrootlogin no (or prohibit-password) · pubkeyauthentication yes
# If not: edit /etc/ssh/sshd_config(.d/*.conf), then: sudo sshd -t && sudo systemctl reload ssh
# Host firewall for host-level services (remember: does NOT cover Docker-published ports, H1)
sudo ufw default deny incoming && sudo ufw allow 22/tcp && sudo ufw allow 80/tcp && sudo ufw allow 443/tcp && sudo ufw enable
Docker: install from Docker's official apt repository (docs.docker.com → Install Docker Engine on Ubuntu). Add only the deploy user to the docker group (H19).
6.3 Session Manager instead of SSH (recommended)¶
- Instance needs the SSM agent (preinstalled on Ubuntu AMIs as a snap) and an instance profile with
AmazonSSMManagedInstanceCore. (Default Host Management Configuration can manage instances without an instance profile, but needs IMDSv2 and is per-Region. AWS's Session Manager troubleshooting page still says an instance profile is required, so use the instance profile; it's the documented path.) - Connect: EC2 → instance → Connect → Session Manager.
- Once it works, delete the SSH rule from the security group.