Tạo EC2

Tạo EC2

  1. Truy cập EC2 console
    • Chọn Instances
    • Chọn Launch instances Create EC2
  2. Nhập tên instance: CloudFront-Server Create EC2
  3. Tại AMI, chọn Amazon Linux Create EC2
  4. Chọn t3.micro, sau đó chọn Create new key pair Create EC2
  5. Nhập tên key pair cloudfront-lab và chọn Create key pair Create EC2
  6. Tại Network settings, chọn Edit Create EC2
  7. Cấu hình networking:
    • VPC: cloudfront-lab-vpc (đã tạo ở bước 2.1)
    • Subnet: một trong các subnet cloudfront-lab-subnet-public…
    • Auto-assign public IP: Enable
    • Chọn Create security group
    • Security group name: cloudfront-sg Create EC2
  8. Mở Advanced details, kéo xuống User data và dán đoạn script sau: 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. Chọn Launch instance Create EC2
  2. Tạo EC2 thành công. Create EC2
  3. Mở chi tiết instance vừa tạo. Create EC2
  4. Cho phép HTTP và HTTPS trong security group:
  • Chọn tab Security
  • Tại Security groups, chọn cloudfront-sg
  • Tại tab Inbound rules, chọn Edit inbound rules và thêm các rule bên dưới
  • Chọn Save rules
Type Protocol Port range Source
HTTP TCP 80 0.0.0.0/0
HTTPS TCP 443 0.0.0.0/0

Ứng dụng lắng nghe ở cổng 80, nên cần rule HTTP để kiểm tra bằng trình duyệt và để CloudFront truy cập origin.

Create EC2 13. Sao chép Public IPv4 DNS Create EC2 14. Mở http://<PUBLIC-DNS>/api trên trình duyệt, thay <PUBLIC-DNS> bằng giá trị vừa sao chép. Create EC2