惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

阮一峰的网络日志
阮一峰的网络日志
IT之家
IT之家
H
Heimdal Security Blog
Jina AI
Jina AI
宝玉的分享
宝玉的分享
博客园 - 【当耐特】
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
爱范儿
爱范儿
T
Tailwind CSS Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Apple Machine Learning Research
Apple Machine Learning Research
有赞技术团队
有赞技术团队
酷 壳 – CoolShell
酷 壳 – CoolShell
WordPress大学
WordPress大学
AWS News Blog
AWS News Blog
C
Cisco Blogs
Cisco Talos Blog
Cisco Talos Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
D
Darknet – Hacking Tools, Hacker News & Cyber Security
The Hacker News
The Hacker News
The Cloudflare Blog
Hugging Face - Blog
Hugging Face - Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
T
Threatpost
S
Securelist
P
Privacy International News Feed
C
CXSECURITY Database RSS Feed - CXSecurity.com
博客园 - 聂微东
博客园 - 叶小钗
J
Java Code Geeks
V
V2EX
博客园 - Franky
Spread Privacy
Spread Privacy
K
Kaspersky official blog
C
Cyber Attacks, Cyber Crime and Cyber Security
Simon Willison's Weblog
Simon Willison's Weblog
Project Zero
Project Zero
大猫的无限游戏
大猫的无限游戏
S
SegmentFault 最新的问题
C
Cybersecurity and Infrastructure Security Agency CISA
C
CERT Recently Published Vulnerability Notes
Latest news
Latest news
NISL@THU
NISL@THU
罗磊的独立博客
W
WeLiveSecurity
Google DeepMind News
Google DeepMind News
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园_首页
V
Visual Studio Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Running a Tomcat App on ECS Fargate — A Complete Step-by-Step Guide
nao1515 · 2026-05-10 · via DEV Community

Introduction

This guide walks you through migrating an existing Tomcat application to AWS ECS Fargate — covering everything from session management and DB migration to Auto Scaling, with a production-ready setup in mind.

Who this is for

  • Developers migrating a Tomcat app to AWS
  • Engineers new to ECS Fargate

Final Architecture

Internet
    │
   ALB (port 80/443)
    │
  ECS Fargate
    ├─ ElastiCache (Redis) ← session store
    └─ RDS (PostgreSQL)   ← persistent data

Enter fullscreen mode Exit fullscreen mode


STEP 1: Create Security Groups

Create dedicated security groups for ALB, ECS, Redis, and RDS. Following the principle of least privilege, only allow what is strictly necessary.

# ALB — allow HTTP/HTTPS from the internet
aws ec2 create-security-group \
  --group-name sg-alb \
  --description "ALB SG" \
  --vpc-id vpc-xxxxxxxx

aws ec2 authorize-security-group-ingress \
  --group-id sg-alb --protocol tcp --port 80 --cidr 0.0.0.0/0
aws ec2 authorize-security-group-ingress \
  --group-id sg-alb --protocol tcp --port 443 --cidr 0.0.0.0/0

# ECS — allow 8080 from ALB only
aws ec2 create-security-group \
  --group-name sg-ecs \
  --description "ECS SG" \
  --vpc-id vpc-xxxxxxxx

aws ec2 authorize-security-group-ingress \
  --group-id sg-ecs --protocol tcp --port 8080 \
  --source-group sg-alb

# Redis — allow 6379 from ECS only
aws ec2 create-security-group \
  --group-name sg-redis \
  --description "Redis SG" \
  --vpc-id vpc-xxxxxxxx

aws ec2 authorize-security-group-ingress \
  --group-id sg-redis --protocol tcp --port 6379 \
  --source-group sg-ecs

# RDS — allow 5432 from ECS only
aws ec2 create-security-group \
  --group-name sg-rds \
  --description "RDS SG" \
  --vpc-id vpc-xxxxxxxx

aws ec2 authorize-security-group-ingress \
  --group-id sg-rds --protocol tcp --port 5432 \
  --source-group sg-ecs

Enter fullscreen mode Exit fullscreen mode

Here is a summary of the security group rules:

Security Group Inbound Rule
sg-alb 0.0.0.0/0 → 80, 443
sg-ecs sg-alb → 8080
sg-redis sg-ecs → 6379
sg-rds sg-ecs → 5432

STEP 2: Store Credentials in Secrets Manager

Store passwords and other sensitive values in Secrets Manager so they never appear as plain text in your task definition.

aws secretsmanager create-secret \
  --name myapp/db-password \
  --secret-string "your-db-password"

aws secretsmanager create-secret \
  --name myapp/db-user \
  --secret-string "your-db-user"

aws secretsmanager create-secret \
  --name myapp/redis-password \
  --secret-string "your-redis-password"

Enter fullscreen mode Exit fullscreen mode


STEP 3: Provision RDS

# Subnet group (private subnets)
aws rds create-db-subnet-group \
  --db-subnet-group-name myapp-rds-subnet \
  --db-subnet-group-description "myapp RDS subnet" \
  --subnet-ids subnet-aaaaaaaa subnet-bbbbbbbb

# RDS instance
aws rds create-db-instance \
  --db-instance-identifier myapp-db \
  --db-instance-class db.t4g.small \
  --engine postgres \
  --engine-version 15.4 \
  --master-username myapp \
  --master-user-password "your-db-password" \
  --db-name myapp \
  --db-subnet-group-name myapp-rds-subnet \
  --vpc-security-group-ids sg-rds \
  --multi-az \
  --storage-type gp3 \
  --allocated-storage 20 \
  --no-publicly-accessible

Enter fullscreen mode Exit fullscreen mode


STEP 4: Provision ElastiCache (Redis)

Because Fargate replaces the underlying instance on every task restart, any session stored in memory will be lost. With multiple tasks running, a request routed to a different task will fail to find the session.

Externalizing sessions to ElastiCache (Redis) solves both problems.

# Subnet group
aws elasticache create-cache-subnet-group \
  --cache-subnet-group-name myapp-redis-subnet \
  --cache-subnet-group-description "myapp redis subnet" \
  --subnet-ids subnet-aaaaaaaa subnet-bbbbbbbb

# Parameter group
aws elasticache create-cache-parameter-group \
  --cache-parameter-group-name myapp-redis-params \
  --cache-parameter-group-family redis7 \
  --description "myapp redis params"

aws elasticache modify-cache-parameter-group \
  --cache-parameter-group-name myapp-redis-params \
  --parameter-name-values \
    ParameterName=maxmemory-policy,ParameterValue=allkeys-lru \
    ParameterName=timeout,ParameterValue=300

# Redis cluster (Multi-AZ, encrypted)
aws elasticache create-replication-group \
  --replication-group-id myapp-redis \
  --description "myapp session store" \
  --engine redis \
  --engine-version 7.0 \
  --cache-node-type cache.t4g.medium \
  --num-cache-clusters 2 \
  --multi-az-enabled \
  --automatic-failover-enabled \
  --cache-subnet-group-name myapp-redis-subnet \
  --cache-parameter-group-name myapp-redis-params \
  --security-group-ids sg-redis \
  --at-rest-encryption-enabled \
  --transit-encryption-enabled \
  --auth-token "your-redis-password"

Enter fullscreen mode Exit fullscreen mode

Spring Session configuration

Add the dependencies to pom.xml:

<dependency>
    <groupId>org.springframework.session</groupId>
    <artifactId>spring-session-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>io.lettuce</groupId>
    <artifactId>lettuce-core</artifactId>
</dependency>

Enter fullscreen mode Exit fullscreen mode

Configure application.yml:

spring:
  session:
    store-type: redis
    timeout: 30m
  data:
    redis:
      host: ${REDIS_HOST}
      port: ${REDIS_PORT}
      password: ${REDIS_PASSWORD}
      ssl:
        enabled: true
      lettuce:
        pool:
          max-active: 8
          max-idle: 8
          min-idle: 2

Enter fullscreen mode Exit fullscreen mode


STEP 5: Build Docker Images and Push to ECR

Dockerfile (application)

FROM tomcat:10.1-jdk17

RUN rm -rf /usr/local/tomcat/webapps/*
COPY target/myapp.war /usr/local/tomcat/webapps/ROOT.war

EXPOSE 8080
CMD ["catalina.sh", "run"]

Enter fullscreen mode Exit fullscreen mode

Dockerfile.migration (Flyway)

FROM flyway/flyway:10-alpine

COPY db/migration /flyway/sql
COPY flyway.conf /flyway/conf/flyway.conf

ENTRYPOINT ["flyway", "migrate"]

Enter fullscreen mode Exit fullscreen mode

flyway.conf:

flyway.url=jdbc:postgresql://${DB_HOST}:5432/${DB_NAME}
flyway.user=${DB_USER}
flyway.password=${DB_PASSWORD}
flyway.locations=filesystem:/flyway/sql
flyway.baselineOnMigrate=true

Enter fullscreen mode Exit fullscreen mode

Push to ECR

# Create repositories
aws ecr create-repository --repository-name myapp
aws ecr create-repository --repository-name myapp-migration

# Login
aws ecr get-login-password --region ap-northeast-1 \
  | docker login --username AWS --password-stdin \
    <account_id>.dkr.ecr.ap-northeast-1.amazonaws.com

# Application image
docker build -t myapp .
docker tag myapp:latest \
  <account_id>.dkr.ecr.ap-northeast-1.amazonaws.com/myapp:latest
docker push \
  <account_id>.dkr.ecr.ap-northeast-1.amazonaws.com/myapp:latest

# Migration image
docker build -f Dockerfile.migration -t myapp-migration .
docker tag myapp-migration:latest \
  <account_id>.dkr.ecr.ap-northeast-1.amazonaws.com/myapp-migration:latest
docker push \
  <account_id>.dkr.ecr.ap-northeast-1.amazonaws.com/myapp-migration:latest

Enter fullscreen mode Exit fullscreen mode


STEP 6: Create CloudWatch Logs Groups

aws logs create-log-group --log-group-name /ecs/myapp/migration
aws logs create-log-group --log-group-name /ecs/myapp/tomcat

Enter fullscreen mode Exit fullscreen mode


STEP 7: Create the IAM Execution Role

The ECS agent needs this role to pull images from ECR and fetch secrets from Secrets Manager.

aws iam create-role \
  --role-name ecsTaskExecutionRole \
  --assume-role-policy-document '{
    "Version": "2012-10-17",
    "Statement": [{
      "Effect": "Allow",
      "Principal": { "Service": "ecs-tasks.amazonaws.com" },
      "Action": "sts:AssumeRole"
    }]
  }'

aws iam attach-role-policy \
  --role-name ecsTaskExecutionRole \
  --policy-arn arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy

aws iam attach-role-policy \
  --role-name ecsTaskExecutionRole \
  --policy-arn arn:aws:iam::aws:policy/SecretsManagerReadWrite

Enter fullscreen mode Exit fullscreen mode


STEP 8: Register the Task Definition

The key point here is dependsOn with condition: SUCCESS — Tomcat will not start until the migration container exits cleanly.

{
  "family": "myapp-task",
  "networkMode": "awsvpc",
  "requiresCompatibilities": ["FARGATE"],
  "cpu": "512",
  "memory": "1024",
  "executionRoleArn": "arn:aws:iam::<account_id>:role/ecsTaskExecutionRole",
  "containerDefinitions": [
    {
      "name": "migration",
      "image": "<account_id>.dkr.ecr.ap-northeast-1.amazonaws.com/myapp-migration:latest",
      "essential": false,
      "secrets": [
        { "name": "DB_USER", "valueFrom": "arn:aws:secretsmanager:ap-northeast-1:<account_id>:secret:myapp/db-user" },
        { "name": "DB_PASSWORD", "valueFrom": "arn:aws:secretsmanager:ap-northeast-1:<account_id>:secret:myapp/db-password" }
      ],
      "environment": [
        { "name": "DB_HOST", "value": "myapp-db.xxxx.ap-northeast-1.rds.amazonaws.com" },
        { "name": "DB_NAME", "value": "myapp" }
      ],
      "logConfiguration": {
        "logDriver": "awslogs",
        "options": {
          "awslogs-group": "/ecs/myapp/migration",
          "awslogs-region": "ap-northeast-1",
          "awslogs-stream-prefix": "ecs"
        }
      }
    },
    {
      "name": "tomcat",
      "image": "<account_id>.dkr.ecr.ap-northeast-1.amazonaws.com/myapp:latest",
      "essential": true,
      "dependsOn": [
        { "containerName": "migration", "condition": "SUCCESS" }
      ],
      "portMappings": [
        { "containerPort": 8080, "protocol": "tcp" }
      ],
      "environment": [
        { "name": "DB_HOST", "value": "myapp-db.xxxx.ap-northeast-1.rds.amazonaws.com" },
        { "name": "DB_NAME", "value": "myapp" },
        { "name": "REDIS_HOST", "value": "myapp-redis.xxxx.ng.0001.apne1.cache.amazonaws.com" },
        { "name": "REDIS_PORT", "value": "6379" },
        { "name": "TZ", "value": "Asia/Tokyo" }
      ],
      "secrets": [
        { "name": "DB_USER", "valueFrom": "arn:aws:secretsmanager:ap-northeast-1:<account_id>:secret:myapp/db-user" },
        { "name": "DB_PASSWORD", "valueFrom": "arn:aws:secretsmanager:ap-northeast-1:<account_id>:secret:myapp/db-password" },
        { "name": "REDIS_PASSWORD", "valueFrom": "arn:aws:secretsmanager:ap-northeast-1:<account_id>:secret:myapp/redis-password" }
      ],
      "healthCheck": {
        "command": ["CMD-SHELL", "curl -f http://localhost:8080/health || exit 1"],
        "interval": 30,
        "timeout": 5,
        "retries": 3,
        "startPeriod": 90
      },
      "logConfiguration": {
        "logDriver": "awslogs",
        "options": {
          "awslogs-group": "/ecs/myapp/tomcat",
          "awslogs-region": "ap-northeast-1",
          "awslogs-stream-prefix": "ecs"
        }
      }
    }
  ]
}

Enter fullscreen mode Exit fullscreen mode

aws ecs register-task-definition \
  --cli-input-json file://task-definition.json

Enter fullscreen mode Exit fullscreen mode

Note: Setting essential: false on the migration container means the task keeps running after migration completes. Tomcat uses condition: SUCCESS to wait for a clean exit before starting.


STEP 9: Create the ALB

# Create ALB
aws elbv2 create-load-balancer \
  --name myapp-alb \
  --subnets subnet-aaaaaaaa subnet-bbbbbbbb \
  --security-groups sg-alb \
  --scheme internet-facing \
  --type application

# Create target group
# Important: Fargate requires --target-type ip, not instance
aws elbv2 create-target-group \
  --name myapp-tg \
  --protocol HTTP \
  --port 8080 \
  --vpc-id vpc-xxxxxxxx \
  --target-type ip \
  --health-check-path /health \
  --health-check-interval-seconds 30 \
  --healthy-threshold-count 2 \
  --unhealthy-threshold-count 3

# Create listener
aws elbv2 create-listener \
  --load-balancer-arn <alb-arn> \
  --protocol HTTP \
  --port 80 \
  --default-actions Type=forward,TargetGroupArn=<tg-arn>

# Shorten deregistration delay (default 300s is too long)
aws elbv2 modify-target-group-attributes \
  --target-group-arn <tg-arn> \
  --attributes Key=deregistration_delay.timeout_seconds,Value=30

Enter fullscreen mode Exit fullscreen mode


STEP 10: Create the ECS Cluster and Service

# Create cluster
aws ecs create-cluster --cluster-name myapp-cluster

# Create service
aws ecs create-service \
  --cluster myapp-cluster \
  --service-name myapp-service \
  --task-definition myapp-task \
  --desired-count 8 \
  --launch-type FARGATE \
  --network-configuration "awsvpcConfiguration={
    subnets=[subnet-aaaaaaaa,subnet-bbbbbbbb],
    securityGroups=[sg-ecs],
    assignPublicIp=DISABLED
  }" \
  --load-balancers "targetGroupArn=<tg-arn>,containerName=tomcat,containerPort=8080" \
  --deployment-configuration \
    "minimumHealthyPercent=50,maximumPercent=200,deploymentCircuitBreaker={enable=true,rollback=true}"

Enter fullscreen mode Exit fullscreen mode

Enabling deploymentCircuitBreaker means ECS automatically rolls back to the previous revision if a deployment fails repeatedly.


STEP 11: Configure Auto Scaling

Auto Scaling handles traffic spikes without manual intervention.

aws application-autoscaling register-scalable-target \
  --service-namespace ecs \
  --resource-id service/myapp-cluster/myapp-service \
  --scalable-dimension ecs:service:DesiredCount \
  --min-capacity 4 \
  --max-capacity 12

aws application-autoscaling put-scaling-policy \
  --policy-name cpu-tracking \
  --service-namespace ecs \
  --resource-id service/myapp-cluster/myapp-service \
  --scalable-dimension ecs:service:DesiredCount \
  --policy-type TargetTrackingScaling \
  --target-tracking-scaling-policy-configuration '{
    "TargetValue": 70.0,
    "PredefinedMetricSpecification": {
      "PredefinedMetricType": "ECSServiceAverageCPUUtilization"
    },
    "ScaleOutCooldown": 60,
    "ScaleInCooldown": 300
  }'

Enter fullscreen mode Exit fullscreen mode

Setting Value Reason
min-capacity 4 Baseline task count
max-capacity 12 Peak capacity
TargetValue 70% Scale out when CPU exceeds 70%
ScaleOutCooldown 60s React quickly to load spikes
ScaleInCooldown 300s Prevent aggressive scale-in

Verify the Deployment

# Check running tasks
aws ecs list-tasks --cluster myapp-cluster

# Check service status
aws ecs describe-services \
  --cluster myapp-cluster \
  --services myapp-service \
  --query 'services[0].{Status:status,Running:runningCount,Desired:desiredCount}'

# Get the ALB DNS name and open it in a browser
aws elbv2 describe-load-balancers \
  --names myapp-alb \
  --query 'LoadBalancers[0].DNSName'

Enter fullscreen mode Exit fullscreen mode


Common Pitfalls

Problem Cause Fix
Task exits immediately after start Application startup error Check CloudWatch Logs for the stack trace
Health check never passes Tomcat takes too long to start Set startPeriod to 90–120 seconds
Cannot pull image from ECR Missing permissions on ecsTaskExecutionRole Attach AmazonECSTaskExecutionRolePolicy
Cannot connect to Redis Security group misconfiguration Verify sg-ecs → sg-redis on port 6379
Tomcat does not start after migration Missing dependsOn Add condition: SUCCESS to the task definition
ALB returns 502 Target type set to instance Change to ip

Summary

Step What you do
1 Create security groups
2 Store credentials in Secrets Manager
3 Provision RDS
4 Provision ElastiCache
5 Build images and push to ECR
6 Create CloudWatch Logs groups
7 Create IAM execution role
8 Register task definition
9 Create ALB
10 Create ECS cluster and service
11 Configure Auto Scaling

Fargate eliminates server management and hands off deployment and scaling to AWS. Setting up session management, DB migration, and Auto Scaling from the start dramatically reduces rework later.