I have built the same AWS setup by hand more times than I’d like to admit. A VPC, a couple of subnets, a security group, an EC2 box, an RDS instance, some IAM bits. Forty-five minutes of clicking through the console, and then the client asks for a staging copy. So you click it all again, and this time you forget the one checkbox that mattered.
That got old fast. This post is the Terraform version of that exact setup: a React frontend, a Node.js API and a PostgreSQL database on RDS, all created by one terraform apply. I ran every command below on a real AWS account, and I’ll show you where it broke on me, because it did. Twice.
What You’re Building
It’s a small Task Manager app, nothing fancy, but it has all the moving parts of a real deployment:
- Frontend: a React single-page app served by nginx
- Backend: a Node.js Express API kept alive by PM2
- Database: PostgreSQL on Amazon RDS, sitting in private subnets
- Network and access: a VPC with public and private subnets, security groups and an IAM role for the instance
Terraform creates 17 resources in total. One EC2 instance runs nginx and the API, and the database lives on its own where the internet can’t reach it. That’s a good shape for dev, test and small internal tools. It isn’t highly available, and I’ll cover what to add for production near the end.
Why Bother With Terraform for This?
Because the console doesn’t scale, and it doesn’t remember. When you provision by hand, the only record of what you built is whatever you can recall. With Terraform you describe the setup once, keep it in Git, and get the same result every time. Need a second environment? Change a variable. Done with the project? terraform destroy removes everything, so there’s no forgotten NAT gateway quietly billing you at the end of the month.
If you’re new to the idea, my post on hosting a static website on AWS with CloudFront, S3 and Terraform covers the basics of providers, state and variables with a smaller example.
Before You Start: Cost and Free Tier
This setup uses the smallest instance sizes (t2.micro for EC2 and db.t3.micro for RDS). On an older AWS account with the classic 12 month Free Tier, that can run at $0. AWS changed the rules for accounts created after mid July 2025, though. New accounts get a credit based free plan instead of the old 12 months. Open the Billing console and check what your own account actually gets before you assume it’s free.
If you’re paying full price, expect roughly $8 a month for the EC2 instance and about $15 for the RDS instance with its storage, so around $23 to $24 a month if you leave it running. Rough numbers, check the AWS pricing pages for your region. The easy fix is to destroy it when you’re done practicing.
Prerequisites
You need Terraform 1.0 or newer, the AWS CLI, and working credentials. Quick check:
terraform version
# Terraform v1.6.0
aws --version
# aws-cli/2.32.17 Python/3.13.11
aws configure list
# NAME : VALUE : TYPE : LOCATION
# profile : <not set> : None : None
# access_key : ****************ABCD : shared-credentials-file :
# secret_key : ****************wXyZ : shared-credentials-file :
# region : us-east-1 : config-file : ~/.aws/config
You also need an EC2 key pair for SSH. See what you already have:
aws ec2 describe-key-pairs --region us-east-1 --query 'KeyPairs[*].KeyName' --output table
# --------------------
# | DescribeKeyPairs |
# +------------------+
# | my-key-pair |
# +------------------+
No key pair yet? Create one and lock down the file permissions, because SSH will refuse to use a key that’s readable by everyone:
aws ec2 create-key-pair \
--key-name terraform-key \
--query 'KeyMaterial' \
--output text > terraform-key.pem
chmod 400 terraform-key.pem
Project Layout
Here’s how I organised the repo. The app and the infrastructure live side by side, which makes it easy to change both in one commit:
new-app-aws/
├── frontend/ # React application
│ ├── src/
│ │ ├── App.js
│ │ └── App.css
│ ├── Dockerfile
│ └── package.json
├── backend/ # Node.js API
│ ├── index.js
│ ├── Dockerfile
│ └── package.json
├── database/
│ └── init.sql # schema and sample data
└── terraform/ # Infrastructure as Code
├── main.tf
├── variables.tf
├── outputs.tf
├── user_data.sh
└── terraform.tfvars
The backend is a plain Express server with CRUD endpoints for tasks. This is the core of backend/index.js:
app.get('/api/tasks', async (req, res) => {
const result = await pool.query('SELECT * FROM tasks ORDER BY created_at DESC');
res.json(result.rows);
});
app.post('/api/tasks', async (req, res) => {
const { title, description } = req.body;
const result = await pool.query(
'INSERT INTO tasks (title, description) VALUES ($1, $2) RETURNING *',
[title, description || '']
);
res.status(201).json(result.rows[0]);
});
Parameterised queries (the $1 and $2), nothing clever. The app isn’t the interesting part here. The infrastructure is.
The Terraform Configuration
I’ll walk through the four pieces that matter: network, the EC2 instance, the database and the security groups.
Network: VPC and Subnets
resource "aws_vpc" "main" {
cidr_block = var.vpc_cidr
enable_dns_hostnames = true
enable_dns_support = true
tags = {
Name = "${var.project_name}-vpc"
Environment = var.environment
}
}
# Public subnets for EC2
resource "aws_subnet" "public" {
count = 2
vpc_id = aws_vpc.main.id
cidr_block = cidrsubnet(var.vpc_cidr, 8, count.index)
availability_zone = data.aws_availability_zones.available.names[count.index]
map_public_ip_on_launch = true
}
# Private subnets for RDS
resource "aws_subnet" "private" {
count = 2
vpc_id = aws_vpc.main.id
cidr_block = cidrsubnet(var.vpc_cidr, 8, count.index + 10)
availability_zone = data.aws_availability_zones.available.names[count.index]
}
Public subnets are for the EC2 instance, which needs to be reachable. Private subnets are for RDS, which doesn’t. The count = 2 gives you subnets in two availability zones, and that isn’t optional: an RDS subnet group has to span at least two AZs, even if you only run a single database instance.
The EC2 Instance and Its user_data Script
This is my favourite part. The instance carries a user_data script that deploys the whole application when it first boots, so there’s no manual SSH session to set things up.
resource "aws_instance" "main" {
ami = data.aws_ami.ubuntu.id
instance_type = var.ec2_instance_type
key_name = var.key_pair_name
subnet_id = aws_subnet.public[0].id
vpc_security_group_ids = [aws_security_group.ec2.id]
iam_instance_profile = aws_iam_instance_profile.ec2.name
user_data = data.template_file.user_data.rendered
root_block_device {
volume_size = var.ec2_volume_size
volume_type = "gp3"
delete_on_termination = true
encrypted = true
}
}
The script installs Node.js, nginx and PM2, clones the repo, waits for the database, builds the React frontend and starts the API. One shot, and it works.
Heads up, two things I’d change today. First, data.template_file comes from the hashicorp/template provider, which is archived and doesn’t even install on Apple Silicon Macs. Terraform has had a built in templatefile() function for years, so use user_data = templatefile("${path.module}/user_data.sh", { ... }) and drop the extra provider. Second, my script installed Node 18 in the original run. That release is past end of life now, so pick a current LTS version in your own script.
The RDS PostgreSQL Database
resource "aws_db_instance" "main" {
identifier = "${var.project_name}-db"
engine = "postgres"
engine_version = var.db_engine_version
instance_class = var.db_instance_class
allocated_storage = var.db_allocated_storage
storage_type = "gp3"
storage_encrypted = true
db_name = var.db_name
username = var.db_username
password = var.db_password
db_subnet_group_name = aws_db_subnet_group.main.name
vpc_security_group_ids = [aws_security_group.rds.id]
publicly_accessible = false
skip_final_snapshot = var.db_skip_final_snapshot
backup_retention_period = var.db_backup_retention_period
}
Look at publicly_accessible = false. It means the database gets no public address at all. Combined with the security group below, the only thing that can talk to it is your application server.
Security Groups
The EC2 group opens SSH and HTTP:
resource "aws_security_group" "ec2" {
name = "${var.project_name}-ec2-sg"
description = "Security group for Task Manager EC2 instance"
vpc_id = aws_vpc.main.id
# SSH
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = var.ssh_allowed_ips
}
# HTTP
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
The RDS group is stricter. It accepts PostgreSQL traffic from one place only, the EC2 security group:
resource "aws_security_group" "rds" {
name = "${var.project_name}-rds-sg"
vpc_id = aws_vpc.main.id
ingress {
from_port = 5432
to_port = 5432
protocol = "tcp"
security_groups = [aws_security_group.ec2.id]
}
}
Referencing a security group instead of an IP range is a nice trick. Even if the instance’s IP changes or you add a second app server to the same group, the rule keeps working and nothing else gets in.
Deploying It, Step by Step
Step 1: Set Your Variables
Create terraform/terraform.tfvars:
# AWS
aws_region = "us-east-1"
# Project
project_name = "taskmanager"
environment = "dev"
# SSH (lock this down, see the hardening section)
ssh_allowed_ips = ["0.0.0.0/0"]
key_pair_name = "terraform-key"
# App repo that user_data clones
github_repo = "https://github.com/your-username/your-repo.git"
# EC2
ec2_instance_type = "t2.micro"
ec2_volume_size = 20
# Database
db_name = "taskmanager"
db_username = "dbadmin"
db_password = "use-a-long-random-password-here"
db_instance_class = "db.t3.micro"
db_allocated_storage = 20
db_engine_version = "15.15"
db_skip_final_snapshot = true
db_backup_retention_period = 7
db_multi_az = false
Two lessons I learned the hard way on this file:
- Don’t call the database user
admin. RDS treats it as a reserved word and the apply fails. More on that in the troubleshooting section. - Don’t guess the PostgreSQL version. Ask AWS which ones exist in your region:
aws rds describe-db-engine-versions --engine postgres \
--query "DBEngineVersions[?EngineVersion>='15'].EngineVersion" \
--output table
# --------------------------
# |DescribeDBEngineVersions|
# +------------------------+
# | 15.7 |
# | 15.8 |
# | 15.10 |
# | 15.15 |
# +------------------------+
Pick something from your own list. The versions available change over time, so 15.15 was simply valid on the day I ran this.
Step 2: terraform init
cd terraform
terraform init
Initializing the backend...
Initializing provider plugins...
- Finding latest version of hashicorp/template...
- Finding hashicorp/aws versions matching "~> 5.0"...
- Installing hashicorp/template v2.2.0...
- Installed hashicorp/template v2.2.0 (signed by HashiCorp)
- Installing hashicorp/aws v5.100.0...
- Installed hashicorp/aws v5.100.0 (signed by HashiCorp)
Terraform has been successfully initialized!
That downloads the providers and prepares the working directory. Nothing exists in AWS yet.
Step 3: terraform plan
terraform plan
Plan: 17 to add, 0 to change, 0 to destroy.
Changes to Outputs:
+ application_url = (known after apply)
+ ec2_public_ip = (known after apply)
+ rds_endpoint = (known after apply)
+ ssh_command = (known after apply)
Never skip the plan. Read it. It’s the cheapest place to catch a typo, a wrong region or a resource you didn’t mean to create.
Step 4: terraform apply
terraform apply
Terraform shows the plan again and waits for you to type yes. This is what my run looked like (IDs changed, timings are real):
aws_vpc.main: Creating...
aws_iam_role.ec2: Creating...
aws_iam_role.ec2: Creation complete after 2s [id=taskmanager-ec2-role]
aws_vpc.main: Creation complete after 16s [id=vpc-0a1b2c3d4e5f67890]
aws_security_group.ec2: Creation complete after 6s [id=sg-0a1b2c3d4e5f67890]
aws_security_group.rds: Creation complete after 5s [id=sg-0f9e8d7c6b5a43210]
aws_db_instance.main: Creating...
aws_db_instance.main: Still creating... [7m10s elapsed]
aws_db_instance.main: Creation complete after 7m18s
aws_instance.main: Creating...
aws_instance.main: Creation complete after 37s [id=i-0123456789abcdef0]
Apply complete! Resources: 17 added, 0 changed, 0 destroyed.
Outputs:
application_url = "http://203.0.113.25"
database_name = "taskmanager"
ec2_public_ip = "203.0.113.25"
rds_endpoint = "taskmanager-db.abcdefghijkl.us-east-1.rds.amazonaws.com:5432"
rds_port = 5432
ssh_command = "ssh -i terraform-key.pem ubuntu@203.0.113.25"
RDS is the slow one, around seven to eight minutes. The EC2 instance is up in under a minute. Grab a coffee.
Wait for the Bootstrap Script
Terraform finishing doesn’t mean your app is up. The infrastructure is ready, but the user_data script is still installing and building things on the instance. Give it another 5 to 10 minutes.
Follow its progress over SSH:
ssh -i terraform-key.pem ubuntu@203.0.113.25
sudo tail -f /var/log/user-data.log
=========================================
Starting Task Manager Deployment
=========================================
Updating system packages...
Installing Node.js...
Installing nginx...
Installing PostgreSQL client...
Installing PM2...
Cloning repository...
Waiting for database to be available...
taskmanager-db.abcdefghijkl.us-east-1.rds.amazonaws.com:5432 - accepting connections
Database is up!
Initializing database...
Setting up backend...
Starting backend with PM2...
[PM2] Done.
Setting up frontend...
Installing frontend dependencies and building...
Deploying frontend to nginx...
nginx: configuration file /etc/nginx/nginx.conf test is successful
=========================================
Deployment completed successfully!
=========================================
When the log ends with “Deployment completed successfully”, the app is up. The checks to prove it are in the Setup Confirmation section near the end of this post.
What Went Wrong (and How I Fixed It)
My first deployment didn’t work. Here are the three problems you’re most likely to hit.
1. The PostgreSQL Version Doesn’t Exist
Error: creating RDS DB Instance: InvalidParameterCombination:
Cannot find version 15.4 for postgres
I’d typed a version from memory. AWS doesn’t offer every minor version, and old ones get retired. Run the describe-db-engine-versions command from earlier, pick a version from the list, and update terraform.tfvars:
db_engine_version = "15.15"
2. Reserved Database Username
Error: creating RDS DB Instance: InvalidParameterValue:
MasterUsername admin cannot be used as it is a reserved word
Annoying, because admin is what everyone types first. I switched to dbadmin:
db_username = "dbadmin"
Steer clear of other obvious ones too, like postgres and rdsadmin.
3. The App Doesn’t Load After 10 Minutes
If the URL still shows nothing, work through this in order:
First, read the bootstrap log. Most failures show up here as a failed npm install, a bad git clone or a database connection error:
ssh -i terraform-key.pem ubuntu@203.0.113.25
sudo tail -100 /var/log/user-data.log
Second, check the security group. Port 80 has to be open to the world:
aws ec2 describe-security-groups \
--group-ids sg-0a1b2c3d4e5f67890 \
--query 'SecurityGroups[0].IpPermissions'
Third, check the API logs. A missing environment variable or a wrong database host will be right there:
pm2 logs taskmanager-backend
Living With the Setup
See What’s Deployed
terraform show
terraform output application_url
# http://203.0.113.25
terraform output ssh_command
# ssh -i terraform-key.pem ubuntu@203.0.113.25
Change Something
Edit the variable, run apply again, and Terraform works out the difference:
ec2_instance_type = "t2.small"
terraform apply
Careful with changes to the instance type or user_data. Depending on what you change, Terraform may stop or even replace the instance, and replacing it re-runs the whole bootstrap. Read the plan before you say yes.
Tear It All Down
terraform destroy
Plan: 0 to add, 0 to change, 17 to destroy.
Do you really want to destroy all resources?
Terraform will destroy all your managed infrastructure, as shown above.
There is no undo. Only 'yes' will be accepted to confirm.
Enter a value: yes
aws_instance.main: Destroying...
aws_db_instance.main: Destroying...
aws_db_instance.main: Destruction complete after 5m18s
aws_instance.main: Destruction complete after 42s
Destroy complete! Resources: 17 destroyed.
Everything is gone: instance, database, VPC, security groups, IAM role. Notice db_skip_final_snapshot = true in my variables. That’s fine for a throwaway lab, but it means the data is deleted with no safety net. For anything you care about, set it to false.
Making It Production Ready
What I’ve shown is great for learning, demos and dev environments. Before you point real users at it, fix these:
Security
- Close SSH to the world. Set
ssh_allowed_ips = ["YOUR_IP/32"]. Better still, skip SSH entirely. The instance already has an SSM role attached, so you can use AWS Systems Manager Session Manager and leave port 22 closed. - Stop putting the database password in a file. Mark the variable
sensitive = trueand pass it with an environment variable such asTF_VAR_db_password. Even better, setmanage_master_user_password = trueon the RDS resource and let AWS keep the password in Secrets Manager. - Add HTTPS. Plain HTTP on port 80 isn’t acceptable for a real app. Use Let’s Encrypt on the instance, or put an Application Load Balancer in front with a certificate from AWS Certificate Manager.
- Turn on Multi-AZ for RDS:
db_multi_az = true.
Availability and Scaling
- An Application Load Balancer in front of the app
- An Auto Scaling Group instead of a single instance
- RDS read replicas if reads become your bottleneck
- CloudFront for the static frontend
Monitoring and Backups
- CloudWatch logs for the app, plus alarms on CPU, memory and disk. Memory and disk need the CloudWatch agent, they aren’t collected by default.
- Longer RDS backup retention, for example
db_backup_retention_period = 30, and a real final snapshot on destroy - Remote Terraform state in S3 with locking. Local state on your laptop is a single point of failure for your whole infrastructure.
Setup Confirmation
Terraform saying “Apply complete” isn’t proof that the app works. Run these checks, in this order. The output under each one is from my own run.
1. Check the Services
pm2 status
┌─────┬────────────────────────┬─────────┬─────────┬──────────┐
│ id │ name │ status │ ↺ │ cpu │
├─────┼────────────────────────┼─────────┼─────────┼──────────┤
│ 0 │ taskmanager-backend │ online │ 0 │ 0% │
└─────┴────────────────────────┴─────────┴─────────┴──────────┘
sudo systemctl status nginx
● nginx.service - A high performance web server and a reverse proxy server
Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
Active: active (running)
2. Hit the App and the API
Open the application_url from the Terraform outputs in a browser. You should see the Task Manager with five sample tasks. Add one, tick one off, delete one. If that all works, the frontend, API and database are talking to each other.
Then test the API directly, which is faster for spotting problems:
curl http://203.0.113.25/api/tasks
[
{
"id": 1,
"title": "Setup AWS Account",
"description": "Create and configure AWS free tier account for DevOps practice",
"completed": true,
"created_at": "2026-01-12T01:12:45.123Z",
"updated_at": "2026-01-12T01:12:45.123Z"
},
{
"id": 2,
"title": "Learn Docker",
"description": "Study Docker containers and create sample Dockerfiles",
"completed": false,
"created_at": "2026-01-12T01:12:45.123Z",
"updated_at": "2026-01-12T01:12:45.123Z"
}
]
And the health check endpoint:
curl http://203.0.113.25/health
# {"status":"OK","timestamp":"2026-01-12T01:20:15.456Z"}
If the browser shows the Task Manager, the API returns your tasks as JSON and the health endpoint says OK, then the infrastructure, the application and the database are all working together. You can now destroy it (see “Tear It All Down” above) or keep building on it.
Frequently Asked Questions
How long does the whole deployment take?
About 15 minutes end to end in my run: roughly 8 minutes for Terraform (mostly RDS), then 5 to 10 for the user_data script to finish building the app.
Can I use this for a real production app?
As a starting point, yes. As is, no. You’d want HTTPS, a load balancer, Multi-AZ, proper secrets handling and remote state first. The structure scales to that, since you’d be adding resources to the same code.
Why a single EC2 instance instead of containers?
Because it’s the simplest thing that shows the full Terraform workflow. If you want the container route, I wrote up deploying a full-stack app with a GitLab CI/CD pipeline, and a Kubernetes version using GitHub Actions, Helm and ArgoCD. To practise on a small cluster first, start with K3s on Ubuntu 24.04.
Can I run this on the AWS free tier?
If your account has the classic 12 month free tier, the t2.micro and db.t3.micro sizes used here qualify. Newer accounts get credits instead, so check your Billing console. The cost section near the top has rough prices if you’re paying.
Why is the database in a private subnet?
Because nothing outside the application needs to reach it. With publicly_accessible = false and a security group that only accepts traffic from the EC2 group, the database has no route from the internet at all. That removes a whole class of attacks.
Does this work for a Next.js app?
The Terraform part is the same. The app and its memory needs differ, though. If you’re on a small instance, my Next.js on AWS free tier guide covers swap, PM2 and Nginx for a 1GB server.
Wrapping Up
You’ve gone from nothing to a working full-stack app on AWS with one command, and the whole thing is described in code you can review, version and reuse. The part I value most isn’t the speed. It’s that I can destroy an environment without fear, because bringing it back is one terraform apply away.
My advice is to start small, like this. Get comfortable with resources, variables and outputs. Add a load balancer or a second environment once the basics feel boring. Don’t try to build the perfect production setup on day one. Build something that works, learn from where it breaks, and iterate.