Creating EC2

Create EC2

  1. Open the EC2 console
    • Select Instances
    • Select Launch instances Create EC2
  2. Enter the instance name: CloudFront-Server Create EC2
  3. For AMI, select Amazon Linux Create EC2
  4. Select t3.micro, then select Create new key pair Create EC2
  5. Enter the key pair name cloudfront-lab and select Create key pair Create EC2
  6. In Network settings, select Edit Create EC2
  7. Configure networking:
    • VPC: cloudfront-lab-vpc (created in step 2.1)
    • Subnet: one of the cloudfront-lab-subnet-public… subnets
    • Auto-assign public IP: Enable
    • Select Create security group
    • Security group name: cloudfront-sg Create EC2
  8. Expand Advanced details, scroll down to User data and paste the following script: Create EC2 Create EC2
#!/bin/bash
# User data for Amazon Linux 2023. Runs once as root on first boot.
# Log output: /var/log/cloud-init-output.log
set -euxo pipefail
export HOME=/root

# Update the system and install Node.js 24 LTS from the Amazon Linux repo
dnf update -y
dnf install -y nodejs24 nodejs24-npm

# Install PM2 globally
npm install -g pm2@latest

# Create the app directory and install Express
mkdir -p /opt/app
cd /opt/app
npm init -y
npm install express

# Create the Express app
cat <<'EOF' > app.js
const express = require('express');
const app = express();

app.get('/api', (req, res) => {
  console.log(JSON.stringify(req.headers));
  res.json({
    timestamp: new Date().toISOString(),
    headers: req.headers,
  });
});

app.listen(80, () => {
  console.log('api is up!');
});
EOF

# Start the app with PM2 and keep it running across reboots
pm2 start /opt/app/app.js --name api
pm2 save
pm2 startup systemd -u root --hp /root
  1. Select Launch instance Create EC2
  2. The instance is created. Create EC2
  3. Open the details of the new instance. Create EC2
  4. Allow HTTP and HTTPS in the security group:
  • Select the Security tab
  • Under Security groups, select cloudfront-sg
  • In the Inbound rules tab, select Edit inbound rules and add the rules below
  • Select Save rules
Type Protocol Port range Source
HTTP TCP 80 0.0.0.0/0
HTTPS TCP 443 0.0.0.0/0

The app listens on port 80, so the HTTP rule is required for the browser test and for CloudFront to reach the origin.

Create EC2 13. Copy the Public IPv4 DNS Create EC2 14. Open http://<PUBLIC-DNS>/api in a browser, replacing <PUBLIC-DNS> with the value you copied. Create EC2