{"id":"ecs","name":"ecs","summary":"Docker コンテナを実行するためのAWS ECSコンテナオーケストレーション。コンテナ化アプリケーションの展開、タスク定義の設定、サービスの設定、クラスタ管理、コンテナ問題のトラブルシューティングなどに使用します。","body":"# AWS ECS\n\nAmazon Elastic Container Service (ECS) is a fully managed container orchestration service. Run containers on AWS Fargate (serverless) or EC2 instances.\n\n## Table of Contents\n\n- [Core Concepts](#core-concepts)\n- [Common Patterns](#common-patterns)\n- [CLI Reference](#cli-reference)\n- [Best Practices](#best-practices)\n- [Troubleshooting](#troubleshooting)\n- [References](#references)\n\n## Core Concepts\n\n### Cluster\n\nLogical grouping of tasks or services. Can contain Fargate tasks, EC2 instances, or both.\n\n### Task Definition\n\nBlueprint for your application. Defines containers, resources, networking, and IAM roles.\n\n### Task\n\nRunning instance of a task definition. Can run standalone or as part of a service.\n\n### Service\n\nMaintains desired count of tasks. Handles deployments, load balancing, and auto scaling.\n\n### Launch Types\n\n| Type | Description | Use Case |\n|------|-------------|----------|\n| **Fargate** | Serverless, pay per task | Most workloads |\n| **EC2** | Self-managed instances | GPU, Windows, specific requirements |\n\n## Common Patterns\n\n### Create a Fargate Cluster\n\n**AWS CLI:**\n\n```bash\n# Create cluster\naws ecs create-cluster --cluster-name my-cluster\n\n# With capacity providers\naws ecs create-cluster \\\n  --cluster-name my-cluster \\\n  --capacity-providers FARGATE FARGATE_SPOT \\\n  --default-capacity-provider-strategy \\\n    capacityProvider=FARGATE,weight=1 \\\n    capacityProvider=FARGATE_SPOT,weight=1\n```\n\n### Register Task Definition\n\n```bash\ncat > task-definition.json << 'EOF'\n{\n  \"family\": \"web-app\",\n  \"networkMode\": \"awsvpc\",\n  \"requiresCompatibilities\": [\"FARGATE\"],\n  \"cpu\": \"256\",\n  \"memory\": \"512\",\n  \"executionRoleArn\": \"arn:aws:iam::123456789012:role/ecsTaskExecutionRole\",\n  \"taskRoleArn\": \"arn:aws:iam::123456789012:role/ecsTaskRole\",\n  \"containerDefinitions\": [\n    {\n      \"name\": \"web\",\n      \"image\": \"123456789012.dkr.ecr.us-east-1.amazonaws.com/my-app:latest\",\n      \"portMappings\": [\n        {\n          \"containerPort\": 8080,\n          \"protocol\": \"tcp\"\n        }\n      ],\n      \"environment\": [\n        {\"name\": \"NODE_ENV\", \"value\": \"production\"}\n      ],\n      \"secrets\": [\n        {\n          \"name\": \"DB_PASSWORD\",\n          \"valueFrom\": \"arn:aws:secretsmanager:us-east-1:123456789012:secret:db-password\"\n        }\n      ],\n      \"logConfiguration\": {\n        \"logDriver\": \"awslogs\",\n        \"options\": {\n          \"awslogs-group\": \"/ecs/web-app\",\n          \"awslogs-region\": \"us-east-1\",\n          \"awslogs-stream-prefix\": \"ecs\",\n          \"mode\": \"non-blocking\",\n          \"max-buffer-size\": \"25m\"\n        }\n      },\n      \"healthCheck\": {\n        \"command\": [\"CMD-SHELL\", \"curl -f http://localhost:8080/health || exit 1\"],\n        \"interval\": 30,\n        \"timeout\": 5,\n        \"retries\": 3,\n        \"startPeriod\": 60\n      }\n    }\n  ]\n}\nEOF\n\naws ecs register-task-definition --cli-input-json file://task-definition.json\n```\n\n### Create Service with Load Balancer\n\n```bash\naws ecs create-service \\\n  --cluster my-cluster \\\n  --service-name web-service \\\n  --task-definition web-app:1 \\\n  --desired-count 2 \\\n  --launch-type FARGATE \\\n  --network-configuration \"awsvpcConfiguration={\n    subnets=[subnet-12345678,subnet-87654321],\n    securityGroups=[sg-12345678],\n    assignPublicIp=DISABLED\n  }\" \\\n  --load-balancers \"targetGroupArn=arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/web-tg/1234567890123456,containerName=web,containerPort=8080\" \\\n  --health-check-grace-period-seconds 60 \\\n  --deployment-configuration \"deploymentCircuitBreaker={enable=true,rollback=true}\"\n```\n\n### Run Standalone Task\n\n```bash\naws ecs run-task \\\n  --cluster my-cluster \\\n  --task-definition my-batch-job:1 \\\n  --launch-type FARGATE \\\n  --network-configuration \"awsvpcConfiguration={\n    subnets=[subnet-12345678],\n    securityGroups=[sg-12345678],\n    assignPublicIp=ENABLED\n  }\"\n```\n\n### Update Service (Deploy New Image)\n\n```bash\n# Register new task definition with updated image\naws ecs register-task-definition --cli-input-json file://task-definition.json\n\n# Update service to use new version\naws ecs update-service \\\n  --cluster my-cluster \\\n  --service web-service \\\n  --task-definition web-app:2 \\\n  --force-new-deployment\n```\n\n### Fargate Spot with SQS-Based Scaling\n\nUse `FARGATE_SPOT` for batch/queue workloads to cut costs ~70%. Always include a fallback to regular `FARGATE`.\n\n```bash\n# Create service with Spot + fallback\naws ecs create-service \\\n  --cluster batch-cluster \\\n  --service-name queue-processor \\\n  --task-definition my-processor:1 \\\n  --desired-count 0 \\\n  --capacity-provider-strategy \\\n    capacityProvider=FARGATE_SPOT,weight=4,base=0 \\\n    capacityProvider=FARGATE,weight=1,base=1 \\\n  --network-configuration \"awsvpcConfiguration={\n    subnets=[subnet-12345678],\n    securityGroups=[sg-12345678],\n    assignPublicIp=DISABLED\n  }\"\n\n# Register scalable target (scale to zero when queue empty)\naws application-autoscaling register-scalable-target \\\n  --service-namespace ecs \\\n  --resource-id service/batch-cluster/queue-processor \\\n  --scalable-dimension ecs:service:DesiredCount \\\n  --min-capacity 0 \\\n  --max-capacity 20\n\n# Scale-out alarm: messages > 100\naws cloudwatch put-metric-alarm \\\n  --alarm-name queue-scale-out \\\n  --metric-name ApproximateNumberOfMessagesVisible \\\n  --namespace AWS/SQS \\\n  --dimensions Name=QueueName,Value=my-queue \\\n  --statistic Average \\\n  --period 60 \\\n  --evaluation-periods 1 \\\n  --threshold 100 \\\n  --comparison-operator GreaterThanThreshold \\\n  --alarm-actions <scale-out-policy-arn>\n\n# Scale-in alarm: queue empty for 3 periods (conservative to avoid flapping)\naws cloudwatch put-metric-alarm \\\n  --alarm-name queue-scale-in \\\n  --metric-name ApproximateNumberOfMessagesVisible \\\n  --namespace AWS/SQS \\\n  --dimensions Name=QueueName,Value=my-queue \\\n  --statistic Average \\\n  --period 60 \\\n  --evaluation-periods 3 \\\n  --threshold 0 \\\n  --comparison-operator LessThanOrEqualToThreshold \\\n  --alarm-actions <scale-in-policy-arn>\n```\n\n**Fargate Spot interruption handling:** Spot tasks receive a SIGTERM 2 minutes before termination. Catch it in your application for graceful shutdown. For SQS consumers, call `ChangeMessageVisibility` on in-flight messages so they return to the queue rather than timing out.\n\n### Auto Scaling\n\n```bash\n# Register scalable target\naws application-autoscaling register-scalable-target \\\n  --service-namespace ecs \\\n  --resource-id service/my-cluster/web-service \\\n  --scalable-dimension ecs:service:DesiredCount \\\n  --min-capacity 2 \\\n  --max-capacity 10\n\n# Target tracking policy\naws application-autoscaling put-scaling-policy \\\n  --service-namespace ecs \\\n  --resource-id service/my-cluster/web-service \\\n  --scalable-dimension ecs:service:DesiredCount \\\n  --policy-name cpu-target-tracking \\\n  --policy-type TargetTrackingScaling \\\n  --target-tracking-scaling-policy-configuration '{\n    \"TargetValue\": 70.0,\n    \"PredefinedMetricSpecification\": {\n      \"PredefinedMetricType\": \"ECSServiceAverageCPUUtilization\"\n    },\n    \"ScaleOutCooldown\": 60,\n    \"ScaleInCooldown\": 120\n  }'\n```\n\n## CLI Reference\n\n### Cluster Management\n\n| Command | Description |\n|---------|-------------|\n| `aws ecs create-cluster` | Create cluster |\n| `aws ecs describe-clusters` | Get cluster details |\n| `aws ecs list-clusters` | List clusters |\n| `aws ecs delete-cluster` | Delete cluster |\n\n### Task Definitions\n\n| Command | Description |\n|---------|-------------|\n| `aws ecs register-task-definition` | Create task definition |\n| `aws ecs describe-task-definition` | Get task definition |\n| `aws ecs list-task-definitions` | List task definitions |\n| `aws ecs deregister-task-definition` | Deregister version |\n\n### Services\n\n| Command | Description |\n|---------|-------------|\n| `aws ecs create-service` | Create service |\n| `aws ecs update-service` | Update service |\n| `aws ecs describe-services` | Get service details |\n| `aws ecs delete-service` | Delete service |\n\n### Tasks\n\n| Command | Description |\n|---------|-------------|\n| `aws ecs run-task` | Run standalone task |\n| `aws ecs stop-task` | Stop running task |\n| `aws ecs describe-tasks` | Get task details |\n| `aws ecs list-tasks` | List tasks |\n\n## Best Practices\n\n### Security\n\n- **Use task roles** for AWS API access (not access keys)\n- **Use execution roles** for ECR/Secrets access\n- **Store secrets in Secrets Manager** or Parameter Store\n- **Use private subnets** with NAT gateway\n- **Enable CloudTrail** for API auditing\n\n### Performance\n\n- **Right-size CPU/memory** — monitor and adjust\n- **Use Fargate Spot** for fault-tolerant workloads (70% savings)\n- **Enable container insights** for monitoring\n- **Use service discovery** for internal communication\n\n### Reliability\n\n- **Deploy across multiple AZs**\n- **Configure health checks** properly\n- **Set appropriate deregistration delay**\n- **Use circuit breaker** for deployments\n\n```bash\naws ecs update-service \\\n  --cluster my-cluster \\\n  --service web-service \\\n  --deployment-configuration '{\n    \"deploymentCircuitBreaker\": {\n      \"enable\": true,\n      \"rollback\": true\n    }\n  }'\n```\n\n### Cost Optimization\n\n- **Use Fargate Spot** for batch workloads\n- **Right-size task resources**\n- **Scale to zero** when not needed\n- **Use capacity providers** for mixed Fargate/Spot\n\n## Troubleshooting\n\n### Task Fails to Start\n\n**Check:**\n\n```bash\n# View stopped tasks\naws ecs describe-tasks \\\n  --cluster my-cluster \\\n  --tasks $(aws ecs list-tasks --cluster my-cluster --desired-status STOPPED --query 'taskArns[0]' --output text)\n```\n\n**Common causes:**\n- Image not found (ECR permissions)\n- Secrets access denied\n- Network configuration (subnets, security groups)\n- Resource limits exceeded\n\n### Container Keeps Restarting\n\n**Debug:**\n\n```bash\n# Check CloudWatch logs\naws logs get-log-events \\\n  --log-group-name /ecs/web-app \\\n  --log-stream-name \"ecs/web/abc123\"\n\n# Check task details\naws ecs describe-tasks \\\n  --cluster my-cluster \\\n  --tasks task-arn \\\n  --query 'tasks[0].containers[0].{reason:reason,exitCode:exitCode}'\n```\n\n**Causes:**\n- Health check failing\n- Application crashing\n- Out of memory\n\n### Live Debugging with ECS Exec\n\nConnect directly to a running container without SSH. Requires `enableExecuteCommand: true` on the service and the SSM agent in your container image (included in most base images).\n\n```bash\n# Enable on existing service\naws ecs update-service \\\n  --cluster my-cluster \\\n  --service web-service \\\n  --enable-execute-command\n\n# Get a shell in a running task\nTASK_ARN=$(aws ecs list-tasks --cluster my-cluster --service-name web-service \\\n  --query 'taskArns[0]' --output text)\n\naws ecs execute-command \\\n  --cluster my-cluster \\\n  --task $TASK_ARN \\\n  --container web \\\n  --interactive \\\n  --command \"/bin/sh\"\n```\n\n**Requirements:** Task role must have `ssmmessages:CreateControlChannel`, `ssmmessages:CreateDataChannel`, `ssmmessages:OpenControlChannel`, `ssmmessages:OpenDataChannel` permissions.\n\n### Service Stuck Deploying\n\n```bash\n# Check deployment status\naws ecs describe-services \\\n  --cluster my-cluster \\\n  --services web-service \\\n  --query 'services[0].deployments'\n\n# Check events\naws ecs describe-services \\\n  --cluster my-cluster \\\n  --services web-service \\\n  --query 'services[0].events[:5]'\n```\n\n**Causes:**\n- Health check failing on new tasks\n- Not enough capacity\n- Target group health checks failing\n\n### Cannot Pull Image from ECR\n\n**Check execution role has:**\n\n```json\n{\n  \"Effect\": \"Allow\",\n  \"Action\": [\n    \"ecr:GetAuthorizationToken\",\n    \"ecr:BatchCheckLayerAvailability\",\n    \"ecr:GetDownloadUrlForLayer\",\n    \"ecr:BatchGetImage\"\n  ],\n  \"Resource\": \"*\"\n}\n```\n\n**Also check:**\n- VPC endpoint for ECR (if private subnet)\n- NAT gateway (if private subnet)\n- Security group allows HTTPS outbound\n\n## References\n\n- [ECS Developer Guide](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/)\n- [ECS API Reference](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/)\n- [ECS CLI Reference](https://docs.aws.amazon.com/cli/latest/reference/ecs/)\n- [boto3 ECS](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ecs.html)","author":"@itsmostafa","ownerProfile":null,"authorContacts":null,"sourceUrl":"https://github.com/itsmostafa/aws-agent-skills/tree/main/skills/ecs","license":"MIT","category":"devops","lang":"en","tokens":3085,"stars":0,"calls30d":2,"claimed":false,"visibility":"public","origin":"crawler","version":"0.1.0","createdAt":"2026-08-22","updatedAt":"2026-08-22","files":[{"path":"task-definitions.md","size":8770,"sha256":"9899a4f7a7e45a959491a42c777a5f68ec7f7411acd639c12d2ef20a9312c068"}],"requires":{"mcp":[],"tools":[]},"safety":{"flags":[],"scannedAt":"2026-08-22","hasScripts":false,"networkEndpoints":["boto3.amazonaws.com","docs.aws.amazon.com"]}}