Chạy backend NestJS monolithic trên môi trường serverless container mà không cần quản lý EC2 instances. Backend service chứa tất cả modules (Users, Products, Orders, Cart, Payment) sẽ được triển khai và quản lý hoàn toàn tự động trong private subnets của VPC.
Frontend (Next.js) → API Gateway → ECS Fargate (NestJS Backend) → DynamoDB
CLI Alternative:
# Verify ECS CLI setup
aws ecs list-clusters --region ap-southeast-1
# Check available ECS services
aws ecs describe-clusters --region ap-southeast-1


vinashoes-clusterCLI Alternative:
# Create ECS cluster
aws ecs create-cluster \
--cluster-name vinashoes-cluster \
--configuration executeCommandConfiguration='{logging=OVERRIDE,logConfiguration={cloudWatchLogGroupName="/aws/ecs/containerinsights/vinashoes-cluster/performance"}}' \
--region ap-southeast-1
# Verify cluster creation
aws ecs describe-clusters \
--clusters vinashoes-cluster \
--include ATTACHMENTS \
--region ap-southeast-1

Task definition configuration:
vinashoes-backend-taskInfrastructure requirements:
OS, Architecture, Network mode:
Task size:
Lưu ý về Task Size:
ecsTaskRole (nếu đã tạo)ecsTaskExecutionRole (bắt buộc cho Fargate)Container - 1:
backend-container<account-id>.dkr.ecr.ap-southeast-1.amazonaws.com/vinashoes/backend-service:latestPrivate registry authentication:
Port mappings:
3000backend-3000 (optional)Resource allocation limits (optional):
1 (in vCPU)3 (in GB)1 (in GB)Environment variables (optional):
Database Configuration:
MONGODB_URI = ``JWT_SECRET = ``PORT = ``Email Configuration:
EMAIL_MAILER = ``EMAIL_HOST = ``EMAIL_USER = ``EMAIL_PASS = ``EMAIL_PORT = ``EMAIL_ENCRYPTION = ``EMAIL_FROM = ``Stripe Configuration:
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY = ``STRIPE_SECRET_KEY = ``Application Environment:
NODE_ENV = production🔒 Security Best Practice:
/ecs/vinashoes-backend-taskap-southeast-1ecstrue (để auto-create log group)Auto-create CloudWatch Log Group: UI mới có option awslogs-create-group: true để tự động tạo log group, không cần tạo manual trước.
CMD-SHELL,curl -f http://localhost:3000/health || exit 130 seconds5 seconds360 seconds🏥 Health Check Configuration: Để tránh “Unknown” health status, cần configure health check trong container definition:
/health endpointStorage (optional):
21 GB (default minimum)Monitoring (optional):
Tags (optional):
Click “Create” để tạo task definition
⚠️ Quan trọng:
ecsTaskExecutionRole) đã được tạo trướcawslogs-create-group: true🔐 Production Security:
# Create secrets in AWS Secrets Manager
aws secretsmanager create-secret \
--name "vinashoes/mongodb" \
--description "MongoDB connection string" \
--secret-string "mongodb+srv://username:[email protected]/database" \
--region ap-southeast-1
aws secretsmanager create-secret \
--name "vinashoes/stripe" \
--description "Stripe API keys" \
--secret-string '{"publishable":"pk_test_...","secret":"sk_test_..."}' \
--region ap-southeast-1
# Reference secrets trong task definition
"secrets": [
{
"name": "MONGODB_URI",
"valueFrom": "arn:aws:secretsmanager:ap-southeast-1:account:secret:vinashoes/mongodb"
}
]

vinashoes-cluster
Task definition family:
Task definition revision:
Service name:

Existing cluster:
Compute configuration - advanced:
Option 1: Capacity provider strategy (Recommended):
01Option 2: Launch type (Simple):
Platform version:
Capacity Provider vs Launch Type:


1 (có thể tăng lên 2-4 cho HA)50200🚀 Quick Setup (5 phút):
vinashoes-alb, Internet-facing0.0.0.0/0vinashoes-backend-tg, port 3000, health check /health/health
⚡ Load Balancer CLI Setup:
# Create target group
aws elbv2 create-target-group \
--name vinashoes-backend-tg \
--protocol HTTP \
--port 3000 \
--vpc-id vpc-xxx \
--target-type ip \
--health-check-path /health \
--region ap-southeast-1
# Create load balancer (if not exists)
aws elbv2 create-load-balancer \
--name vinashoes-alb \
--subnets subnet-xxx subnet-yyy \
--security-groups sg-xxx \
--region ap-southeast-1
CLI Status Check:
# Check service status
aws ecs describe-services \
--cluster vinashoes-cluster \
--services vinashoes-backend \
--region ap-southeast-1
# Check running tasks
aws ecs list-tasks \
--cluster vinashoes-cluster \
--service-name vinashoes-backend \
--region ap-southeast-1
# Get task details
aws ecs describe-tasks \
--cluster vinashoes-cluster \
--tasks $(aws ecs list-tasks --cluster vinashoes-cluster --service-name vinashoes-backend --query 'taskArns[0]' --output text) \
--region ap-southeast-1

Get ALB URL & Test:
# Get ALB DNS from EC2 Console
ALB_URL="http://vinashoes-alb-xxx.ap-southeast-1.elb.amazonaws.com"
# Test endpoints
curl $ALB_URL/health
curl $ALB_URL/api/products
Browser Test:
http://vinashoes-alb-xxx.ap-southeast-1.elb.amazonaws.com/health{"status":"ok"}🔍 Troubleshooting Commands:
# Check target group health
aws elbv2 describe-target-health \
--target-group-arn $(aws elbv2 describe-target-groups --names vinashoes-backend-tg --query 'TargetGroups[0].TargetGroupArn' --output text) \
--region ap-southeast-1
# View container logs
aws logs filter-log-events \
--log-group-name /ecs/vinashoes-backend \
--start-time $(date -d '10 minutes ago' +%s)000 \
--region ap-southeast-1
Container Insights:
vinashoes-clusterKey Metrics:
📊 Monitoring CLI:
# Get cluster metrics
aws cloudwatch get-metric-statistics \
--namespace AWS/ECS \
--metric-name CPUUtilization \
--dimensions Name=ClusterName,Value=vinashoes-cluster Name=ServiceName,Value=vinashoes-backend \
--start-time $(date -u -d '1 hour ago' +%Y-%m-%dT%H:%M:%S) \
--end-time $(date -u +%Y-%m-%dT%H:%M:%S) \
--period 300 \
--statistics Average \
--region ap-southeast-1
# Check service events
aws ecs describe-services \
--cluster vinashoes-cluster \
--services vinashoes-backend \
--query 'services[0].events[:5]' \
--region ap-southeast-1
/ecs/vinashoes-backend📋 Log Management CLI:
# Stream real-time logs
aws logs tail /ecs/vinashoes-backend --follow --region ap-southeast-1
# Search for specific patterns
aws logs filter-log-events \
--log-group-name /ecs/vinashoes-backend \
--filter-pattern "ERROR" \
--start-time $(date -d '1 hour ago' +%s)000 \
--region ap-southeast-1
# Get recent logs
aws logs filter-log-events \
--log-group-name /ecs/vinashoes-backend \
--start-time $(date -d '30 minutes ago' +%s)000 \
--region ap-southeast-1 \
--query 'events[*].[logStreamName,message]' \
--output table
AWS CLI Commands:
# Update service to 0 desired tasks
aws ecs update-service --cluster vinashoes-cluster --service vinashoes-backend-service --desired-count 0 --region ap-southeast-1
# Delete service
aws ecs delete-service --cluster vinashoes-cluster --service vinashoes-backend-service --region ap-southeast-1
AWS CLI Commands:
# Delete cluster
aws ecs delete-cluster --cluster vinashoes-cluster --region ap-southeast-1
AWS CLI Commands:
# Deregister task definition
aws ecs deregister-task-definition --task-definition vinashoes-backend-task --region ap-southeast-1
AWS CLI Commands:
# Get ALB ARN
ALB_ARN=$(aws elbv2 describe-load-balancers --names vinashoes-alb --query 'LoadBalancers[0].LoadBalancerArn' --output text --region ap-southeast-1)
# Delete ALB
aws elbv2 delete-load-balancer --load-balancer-arn $ALB_ARN --region ap-southeast-1
# Get target group ARN
TG_ARN=$(aws elbv2 describe-target-groups --names vinashoes-backend-tg --query 'TargetGroups[0].TargetGroupArn' --output text --region ap-southeast-1)
# Delete target group
aws elbv2 delete-target-group --target-group-arn $TG_ARN --region ap-southeast-1
AWS CLI Commands:
# Delete log group
aws logs delete-log-group --log-group-name /ecs/vinashoes-backend-task --region ap-southeast-1
AWS CLI Commands:
# Detach policies from task execution role
aws iam detach-role-policy --role-name ecsTaskExecutionRole --policy-arn arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy
aws iam detach-role-policy --role-name ecsTaskExecutionRole --policy-arn arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly
# Delete task execution role
aws iam delete-role --role-name ecsTaskExecutionRole
# If task role exists, delete it too
aws iam detach-role-policy --role-name ecsTaskRole --policy-arn arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy
aws iam delete-role --role-name ecsTaskRole
Verification Commands:
# Verify cluster deleted
aws ecs describe-clusters --clusters vinashoes-cluster --region ap-southeast-1 || echo "Cluster deleted"
# Verify service deleted
aws ecs describe-services --cluster vinashoes-cluster --services vinashoes-backend-service --region ap-southeast-1 || echo "Service deleted"
# Verify ALB deleted
aws elbv2 describe-load-balancers --names vinashoes-alb --region ap-southeast-1 || echo "ALB deleted"
| Dịch vụ | Chi phí | Mô tả |
|---|---|---|
| ECS Fargate CPU | $0.04048/vCPU/giờ | Compute cho containers |
| ECS Fargate Memory | $0.004445/GB/giờ | Memory cho containers |
| Application Load Balancer | $0.0225/giờ | Load balancer |
| Data Transfer Out | $0.008/GB | Outbound data transfer |
Chi phí hàng tháng ước tính:
Lợi ích của ECS Fargate:
Tính toán ROI:
AWS Cost Explorer Commands:
# Get ECS costs for last month
aws ce get-cost-and-usage \
--time-period Start=2024-01-01,End=2024-02-01 \
--granularity MONTHLY \
--metrics BlendedCost \
--group-by Type=DIMENSION,Key=SERVICE \
--filter '{
"Dimensions": {
"Key": "SERVICE",
"Values": ["Amazon Elastic Container Service"]
}
}' \
--region us-east-1
CloudWatch Monitoring:
# Monitor ECS CPU utilization
aws cloudwatch get-metric-statistics \
--namespace AWS/ECS \
--metric-name CPUUtilization \
--dimensions Name=ClusterName,Value=vinashoes-cluster Name=ServiceName,Value=vinashoes-backend-service \
--start-time 2024-01-01T00:00:00Z \
--end-time 2024-02-01T00:00:00Z \
--period 86400 \
--statistics Average \
--region ap-southeast-1
Fargate Optimization:
ALB Optimization:
Monitoring & Alerts:
# Test health endpoint works
curl -UseBasicParsing http://18.143.162.50:3000/health
# If returns {"status":"ok"} → Container is healthy, just missing health check config
⚡ Quick Answer: Health status “Unknown” KHÔNG ảnh hưởng đến API Gateway setup. Có thể tiếp tục Task 10 ngay!
ALB Security Group:
0.0.0.0/0ECS Security Group:
ECS Fargate với Load Balancer setup thành công:
vinashoes-cluster running/health endpoint workingTest URLs:
# ALB endpoint (copy từ EC2 Console)
http://vinashoes-alb-xxx.ap-southeast-1.elb.amazonaws.com/health
Next step : Task 10 - API Gateway với custom domain api.vinashoes.org