AWS新手求助:用CloudFormation部署ECS容器化应用至EC2并实现Web访问
Hey there! I totally get how overwhelming AWS docs can feel when you're just starting out—so let's cut through the noise with a practical, beginner-friendly CloudFormation template that sets up ECS on EC2 and gets your containerized app accessible via the web.
Step-by-Step ECS on EC2 CloudFormation Setup
This template will create all the core resources you need: an ECS cluster with EC2 instances, IAM roles for permissions, a secure network setup, and your containerized app running as an ECS service.
CloudFormation Template (YAML)
Save this as ecs-ec2-webapp.yml, then replace YOUR_CONTAINER_IMAGE with your actual container image (e.g., nginx:latest for a test, or your custom app image from Docker Hub/ECR):
AWSTemplateFormatVersion: '2010-09-09' Description: ECS Cluster on EC2 with web-accessible container app Resources: # IAM Role for ECS EC2 Instances ECSInstanceRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Principal: Service: ec2.amazonaws.com Action: sts:AssumeRole ManagedPolicyArns: - arn:aws:iam::aws:policy/service-role/AmazonEC2ContainerServiceforEC2Role # IAM Instance Profile for ECS Instances ECSInstanceProfile: Type: AWS::IAM::InstanceProfile Properties: Roles: - !Ref ECSInstanceRole # ECS Task Execution Role (for pulling images, logging) ECSTaskExecutionRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Principal: Service: ecs-tasks.amazonaws.com Action: sts:AssumeRole ManagedPolicyArns: - arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy # ECS Cluster ECSCluster: Type: AWS::ECS::Cluster Properties: ClusterName: EC2WebAppCluster # Security Group for ECS EC2 Instances (allow HTTP access) EC2SecurityGroup: Type: AWS::EC2::SecurityGroup Properties: GroupDescription: Allow HTTP inbound and all outbound traffic SecurityGroupIngress: - IpProtocol: tcp FromPort: 80 ToPort: 80 CidrIp: 0.0.0.0/0 SecurityGroupEgress: - IpProtocol: -1 CidrIp: 0.0.0.0/0 # Launch Template for ECS EC2 Instances ECSLaunchTemplate: Type: AWS::EC2::LaunchTemplate Properties: LaunchTemplateName: ECSWebAppLaunchTemplate LaunchTemplateData: ImageId: !FindInMap [AWSRegionToAMI, !Ref 'AWS::Region', AMIID] InstanceType: t2.micro IamInstanceProfile: Name: !Ref ECSInstanceProfile SecurityGroupIds: - !Ref EC2SecurityGroup UserData: Fn::Base64: !Sub | #!/bin/bash echo ECS_CLUSTER=${ECSCluster} >> /etc/ecs/ecs.config # Auto Scaling Group to maintain EC2 instances in the cluster EC2AutoScalingGroup: Type: AWS::AutoScaling::AutoScalingGroup Properties: MinSize: 1 MaxSize: 1 DesiredCapacity: 1 LaunchTemplate: LaunchTemplateId: !Ref ECSLaunchTemplate Version: !GetAtt ECSLaunchTemplate.LatestVersionNumber VPCZoneIdentifier: !Split [",", !Ref 'AWS::NoValue'] # Uses default VPC subnets # ECS Task Definition (defines your container) WebAppTaskDefinition: Type: AWS::ECS::TaskDefinition Properties: Family: web-app-task NetworkMode: bridge RequiresCompatibilities: - EC2 Cpu: '256' Memory: '512' ExecutionRoleArn: !Ref ECSTaskExecutionRole ContainerDefinitions: - Name: web-app-container Image: YOUR_CONTAINER_IMAGE PortMappings: - ContainerPort: 80 HostPort: 80 LogConfiguration: LogDriver: awslogs Options: awslogs-group: !Ref LogGroup awslogs-region: !Ref 'AWS::Region' awslogs-stream-prefix: ecs # CloudWatch Log Group for container logs LogGroup: Type: AWS::Logs::LogGroup Properties: LogGroupName: /ecs/web-app-logs RetentionInDays: 7 # ECS Service to run and maintain your task WebAppService: Type: AWS::ECS::Service Properties: Cluster: !Ref ECSCluster ServiceName: web-app-service TaskDefinition: !Ref WebAppTaskDefinition DesiredCount: 1 LaunchType: EC2 # Mapping for ECS-Optimized AMIs (region-specific) Mappings: AWSRegionToAMI: us-east-1: AMIID: ami-0c55b159cbfafe1f0 us-west-2: AMIID: ami-0d5eff06f840b45e9 eu-west-1: AMIID: ami-08c40ec9ead489470 ap-southeast-1: AMIID: ami-0f9ae750e8274075b
How to Use This Template
- Replace the Image: Swap
YOUR_CONTAINER_IMAGEwith your container's image URL (e.g.,my-dockerhub-user/my-app:v1or123456789012.dkr.ecr.us-east-1.amazonaws.com/my-app:latestfor ECR). - Create the Stack:
- AWS Console: Go to CloudFormation → Create stack → Upload template file → Select your
ecs-ec2-webapp.yml→ Follow the prompts. - AWS CLI: Run this command (make sure you're authenticated):
aws cloudformation create-stack --stack-name ecs-ec2-webapp --template-body file://ecs-ec2-webapp.yml --capabilities CAPABILITY_IAM
- AWS Console: Go to CloudFormation → Create stack → Upload template file → Select your
- Access Your App: Once the stack is fully created, go to the EC2 console, find the instance in your cluster, copy its public IP, and visit
http://<your-ec2-public-ip>in your browser.
Key Notes for Beginners
- Port Mapping: The template maps container port 80 to host port 80—make sure your app is listening on port 80 (adjust both values if your app uses a different port).
- ECR Images: If you're using Amazon ECR for your image, the
ECSTaskExecutionRolealready has permissions to pull images, so no extra setup needed. - Scaling: You can adjust
MinSize,MaxSize, andDesiredCapacityin the Auto Scaling Group if you need more instances later. - Production Improvements: For production, add an Application Load Balancer (ALB) to distribute traffic and avoid direct EC2 IP access—but this template keeps things simple for getting started.
内容的提问来源于stack exchange,提问作者Mugetsu
相关产品推荐
相关产品推荐

