ec2

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

AWS EC2

AWS EC2

Amazon Elastic Compute Cloud (EC2) provides resizable compute capacity in the cloud. Launch virtual servers, configure networking and security, and manage storage.
亚马逊弹性计算云(EC2)在云中提供可弹性调整大小的计算容量,可用于启动虚拟服务器、配置网络与安全规则、管理存储资源。

Table of Contents

目录

Core Concepts

核心概念

Instance Types

实例类型

CategoryExampleUse Case
General Purposet3, m6iWeb servers, dev environments
Compute Optimizedc6iBatch processing, gaming
Memory Optimizedr6iDatabases, caching
Storage Optimizedi3, d3Data warehousing
Acceleratedp4d, g5ML, graphics
类别示例适用场景
通用型t3, m6iWeb 服务器、开发环境
计算优化型c6i批处理、游戏服务
内存优化型r6i数据库、缓存服务
存储优化型i3, d3数据仓库
加速计算型p4d, g5机器学习、图形处理

Purchasing Options

购买选项

OptionDescription
On-DemandPay by the hour/second
Reserved1-3 year commitment, up to 72% discount
SpotUnused capacity, up to 90% discount
Savings PlansFlexible commitment-based discount
选项说明
按需实例按小时/秒付费
预留实例1-3年使用承诺,最高享受72%折扣
竞价实例使用闲置算力,最高享受90%折扣
节省计划基于灵活使用承诺的折扣方案

AMI (Amazon Machine Image)

AMI (Amazon Machine Image)

Template containing OS, software, and configuration for launching instances.
包含操作系统、预装软件和配置的模板,用于快速启动实例。

Security Groups

安全组

Virtual firewalls controlling inbound and outbound traffic.
控制入站和出站流量的虚拟防火墙。

Common Patterns

常见使用场景

Launch an Instance

启动实例

AWS CLI:
bash
undefined
AWS CLI:
bash
undefined

Create key pair

Create key pair

aws ec2 create-key-pair
--key-name my-key
--query 'KeyMaterial'
--output text > my-key.pem chmod 400 my-key.pem
aws ec2 create-key-pair
--key-name my-key
--query 'KeyMaterial'
--output text > my-key.pem chmod 400 my-key.pem

Create security group

Create security group

aws ec2 create-security-group
--group-name web-server-sg
--description "Web server security group"
--vpc-id vpc-12345678
aws ec2 create-security-group
--group-name web-server-sg
--description "Web server security group"
--vpc-id vpc-12345678

Allow SSH and HTTP

Allow SSH and HTTP

aws ec2 authorize-security-group-ingress
--group-id sg-12345678
--protocol tcp
--port 22
--cidr 10.0.0.0/8
aws ec2 authorize-security-group-ingress
--group-id sg-12345678
--protocol tcp
--port 80
--cidr 0.0.0.0/0
aws ec2 authorize-security-group-ingress
--group-id sg-12345678
--protocol tcp
--port 22
--cidr 10.0.0.0/8
aws ec2 authorize-security-group-ingress
--group-id sg-12345678
--protocol tcp
--port 80
--cidr 0.0.0.0/0

Launch instance

Launch instance

aws ec2 run-instances
--image-id ami-0123456789abcdef0
--instance-type t3.micro
--key-name my-key
--security-group-ids sg-12345678
--subnet-id subnet-12345678
--tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=web-server}]'

**boto3:**

```python
import boto3

ec2 = boto3.resource('ec2')

instances = ec2.create_instances(
    ImageId='ami-0123456789abcdef0',
    InstanceType='t3.micro',
    KeyName='my-key',
    SecurityGroupIds=['sg-12345678'],
    SubnetId='subnet-12345678',
    MinCount=1,
    MaxCount=1,
    TagSpecifications=[{
        'ResourceType': 'instance',
        'Tags': [{'Key': 'Name', 'Value': 'web-server'}]
    }]
)

instance = instances[0]
instance.wait_until_running()
instance.reload()
print(f"Instance ID: {instance.id}")
print(f"Public IP: {instance.public_ip_address}")
aws ec2 run-instances
--image-id ami-0123456789abcdef0
--instance-type t3.micro
--key-name my-key
--security-group-ids sg-12345678
--subnet-id subnet-12345678
--tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=web-server}]'

**boto3:**

```python
import boto3

ec2 = boto3.resource('ec2')

instances = ec2.create_instances(
    ImageId='ami-0123456789abcdef0',
    InstanceType='t3.micro',
    KeyName='my-key',
    SecurityGroupIds=['sg-12345678'],
    SubnetId='subnet-12345678',
    MinCount=1,
    MaxCount=1,
    TagSpecifications=[{
        'ResourceType': 'instance',
        'Tags': [{'Key': 'Name', 'Value': 'web-server'}]
    }]
)

instance = instances[0]
instance.wait_until_running()
instance.reload()
print(f"Instance ID: {instance.id}")
print(f"Public IP: {instance.public_ip_address}")

User Data Script

用户数据脚本

bash
aws ec2 run-instances \
  --image-id ami-0123456789abcdef0 \
  --instance-type t3.micro \
  --key-name my-key \
  --security-group-ids sg-12345678 \
  --subnet-id subnet-12345678 \
  --user-data '#!/bin/bash
    yum update -y
    yum install -y httpd
    systemctl start httpd
    systemctl enable httpd
    echo "<h1>Hello from $(hostname)</h1>" > /var/www/html/index.html
  '
bash
aws ec2 run-instances \
  --image-id ami-0123456789abcdef0 \
  --instance-type t3.micro \
  --key-name my-key \
  --security-group-ids sg-12345678 \
  --subnet-id subnet-12345678 \
  --user-data '#!/bin/bash
    yum update -y
    yum install -y httpd
    systemctl start httpd
    systemctl enable httpd
    echo "<h1>Hello from $(hostname)</h1>" > /var/www/html/index.html
  '

Attach IAM Role

挂载 IAM 角色

bash
undefined
bash
undefined

Create instance profile

Create instance profile

aws iam create-instance-profile
--instance-profile-name web-server-profile
aws iam add-role-to-instance-profile
--instance-profile-name web-server-profile
--role-name web-server-role
aws iam create-instance-profile
--instance-profile-name web-server-profile
aws iam add-role-to-instance-profile
--instance-profile-name web-server-profile
--role-name web-server-role

Launch with profile

Launch with profile

aws ec2 run-instances
--image-id ami-0123456789abcdef0
--instance-type t3.micro
--iam-instance-profile Name=web-server-profile
...
undefined
aws ec2 run-instances
--image-id ami-0123456789abcdef0
--instance-type t3.micro
--iam-instance-profile Name=web-server-profile
...
undefined

Create AMI from Instance

从实例创建 AMI

bash
aws ec2 create-image \
  --instance-id i-1234567890abcdef0 \
  --name "my-custom-ami-$(date +%Y%m%d)" \
  --description "Custom AMI with web server" \
  --no-reboot
bash
aws ec2 create-image \
  --instance-id i-1234567890abcdef0 \
  --name "my-custom-ami-$(date +%Y%m%d)" \
  --description "Custom AMI with web server" \
  --no-reboot

Spot Instance Request

竞价实例请求

bash
aws ec2 request-spot-instances \
  --instance-count 1 \
  --type "one-time" \
  --launch-specification '{
    "ImageId": "ami-0123456789abcdef0",
    "InstanceType": "c5.large",
    "KeyName": "my-key",
    "SecurityGroupIds": ["sg-12345678"],
    "SubnetId": "subnet-12345678"
  }' \
  --spot-price "0.05"
bash
aws ec2 request-spot-instances \
  --instance-count 1 \
  --type "one-time" \
  --launch-specification '{
    "ImageId": "ami-0123456789abcdef0",
    "InstanceType": "c5.large",
    "KeyName": "my-key",
    "SecurityGroupIds": ["sg-12345678"],
    "SubnetId": "subnet-12345678"
  }' \
  --spot-price "0.05"

EBS Volume Management

EBS 卷管理

bash
undefined
bash
undefined

Create volume

Create volume

aws ec2 create-volume
--availability-zone us-east-1a
--size 100
--volume-type gp3
--iops 3000
--throughput 125
--encrypted
aws ec2 create-volume
--availability-zone us-east-1a
--size 100
--volume-type gp3
--iops 3000
--throughput 125
--encrypted

Attach to instance

Attach to instance

aws ec2 attach-volume
--volume-id vol-12345678
--instance-id i-1234567890abcdef0
--device /dev/sdf
aws ec2 attach-volume
--volume-id vol-12345678
--instance-id i-1234567890abcdef0
--device /dev/sdf

Create snapshot

Create snapshot

aws ec2 create-snapshot
--volume-id vol-12345678
--description "Daily backup"
undefined
aws ec2 create-snapshot
--volume-id vol-12345678
--description "Daily backup"
undefined

CLI Reference

CLI 参考

Instance Management

实例管理

CommandDescription
aws ec2 run-instances
Launch instances
aws ec2 describe-instances
List instances
aws ec2 start-instances
Start stopped instances
aws ec2 stop-instances
Stop running instances
aws ec2 reboot-instances
Reboot instances
aws ec2 terminate-instances
Terminate instances
aws ec2 modify-instance-attribute
Modify instance settings
命令说明
aws ec2 run-instances
启动实例
aws ec2 describe-instances
查询实例列表
aws ec2 start-instances
启动已停止的实例
aws ec2 stop-instances
停止运行中的实例
aws ec2 reboot-instances
重启实例
aws ec2 terminate-instances
销毁实例
aws ec2 modify-instance-attribute
修改实例配置

Security Groups

安全组

CommandDescription
aws ec2 create-security-group
Create security group
aws ec2 describe-security-groups
List security groups
aws ec2 authorize-security-group-ingress
Add inbound rule
aws ec2 revoke-security-group-ingress
Remove inbound rule
aws ec2 authorize-security-group-egress
Add outbound rule
命令说明
aws ec2 create-security-group
创建安全组
aws ec2 describe-security-groups
查询安全组列表
aws ec2 authorize-security-group-ingress
添加入站规则
aws ec2 revoke-security-group-ingress
移除入站规则
aws ec2 authorize-security-group-egress
添加出站规则

AMIs

AMIs

CommandDescription
aws ec2 describe-images
List AMIs
aws ec2 create-image
Create AMI from instance
aws ec2 copy-image
Copy AMI to another region
aws ec2 deregister-image
Delete AMI
命令说明
aws ec2 describe-images
查询 AMI 列表
aws ec2 create-image
从实例创建 AMI
aws ec2 copy-image
复制 AMI 到其他区域
aws ec2 deregister-image
删除 AMI

EBS Volumes

EBS 卷

CommandDescription
aws ec2 create-volume
Create EBS volume
aws ec2 attach-volume
Attach to instance
aws ec2 detach-volume
Detach from instance
aws ec2 create-snapshot
Create snapshot
aws ec2 modify-volume
Resize/modify volume
命令说明
aws ec2 create-volume
创建 EBS 卷
aws ec2 attach-volume
挂载到实例
aws ec2 detach-volume
从实例卸载
aws ec2 create-snapshot
创建快照
aws ec2 modify-volume
调整容量/修改卷配置

Best Practices

最佳实践

Security

安全

  • Use IAM roles instead of access keys on instances
  • Restrict security groups — principle of least privilege
  • Use private subnets for backend instances
  • Enable IMDSv2 to prevent SSRF attacks
  • Encrypt EBS volumes at rest
bash
undefined
  • 优先使用 IAM 角色,不要在实例中存储访问密钥
  • 严格限制安全组权限,遵循最小权限原则
  • 后端实例部署在私有子网
  • 启用 IMDSv2 防范 SSRF 攻击
  • 开启 EBS 卷静态加密
bash
undefined

Require IMDSv2

Require IMDSv2

aws ec2 modify-instance-metadata-options
--instance-id i-1234567890abcdef0
--http-tokens required
--http-endpoint enabled
undefined
aws ec2 modify-instance-metadata-options
--instance-id i-1234567890abcdef0
--http-tokens required
--http-endpoint enabled
undefined

Performance

性能

  • Right-size instances — monitor and adjust
  • Use EBS-optimized instances
  • Choose appropriate EBS volume type
  • Use placement groups for low-latency networking
  • 合理匹配实例规格,持续监控并调整配置
  • 使用 EBS 优化实例
  • 选择匹配业务场景的 EBS 卷类型
  • 使用置放群组实现低延迟网络通信

Cost Optimization

成本优化

  • Use Spot Instances for fault-tolerant workloads
  • Stop/terminate unused instances
  • Use Reserved Instances for steady-state workloads
  • Delete unused EBS volumes and snapshots
  • 容错型工作负载使用竞价实例
  • 及时停止/销毁闲置实例
  • 稳态负载使用预留实例
  • 删除闲置的 EBS 卷和快照

Reliability

可靠性

  • Use Auto Scaling Groups for high availability
  • Deploy across multiple AZs
  • Use Elastic Load Balancer for traffic distribution
  • Implement health checks
  • 使用自动伸缩组保障高可用
  • 跨多个可用区部署
  • 使用弹性负载均衡器分发流量
  • 配置健康检查机制

Troubleshooting

问题排查

Cannot SSH to Instance

无法 SSH 连接实例

Checklist:
  1. Security group allows SSH (port 22) from your IP
  2. Instance has public IP or use bastion/SSM
  3. Key pair matches instance
  4. Instance is running
  5. Network ACL allows traffic
bash
undefined
检查清单:
  1. 安全组放行了你的IP对22端口的访问权限
  2. 实例有公网IP,或通过堡垒机/SSM访问
  3. 使用的密钥对和实例匹配
  4. 实例处于运行状态
  5. 网络ACL允许对应流量通行
bash
undefined

Check security group

Check security group

aws ec2 describe-security-groups --group-ids sg-12345678
aws ec2 describe-security-groups --group-ids sg-12345678

Check instance state

Check instance state

aws ec2 describe-instances
--instance-ids i-1234567890abcdef0
--query "Reservations[].Instances[].{State:State.Name,PublicIP:PublicIpAddress}"

**Use Session Manager instead:**

```bash
aws ssm start-session --target i-1234567890abcdef0
aws ec2 describe-instances
--instance-ids i-1234567890abcdef0
--query "Reservations[].Instances[].{State:State.Name,PublicIP:PublicIpAddress}"

**可使用会话管理器替代SSH:**

```bash
aws ssm start-session --target i-1234567890abcdef0

Instance Won't Start

实例无法启动

Causes:
  • Reached instance limits
  • Insufficient capacity in AZ
  • EBS volume issue
  • Invalid AMI
bash
undefined
常见原因:
  • 达到实例配额上限
  • 可用区算力不足
  • EBS 卷异常
  • AMI 无效
bash
undefined

Check instance state reason

Check instance state reason

aws ec2 describe-instances
--instance-ids i-1234567890abcdef0
--query "Reservations[].Instances[].StateReason"
undefined
aws ec2 describe-instances
--instance-ids i-1234567890abcdef0
--query "Reservations[].Instances[].StateReason"
undefined

Instance Unreachable

实例不可访问

Debug:
bash
undefined
调试步骤:
bash
undefined

Check instance status

Check instance status

aws ec2 describe-instance-status
--instance-ids i-1234567890abcdef0
aws ec2 describe-instance-status
--instance-ids i-1234567890abcdef0

Get console output

Get console output

aws ec2 get-console-output
--instance-id i-1234567890abcdef0
aws ec2 get-console-output
--instance-id i-1234567890abcdef0

Get screenshot (for Windows/GUI issues)

Get screenshot (for Windows/GUI issues)

aws ec2 get-console-screenshot
--instance-id i-1234567890abcdef0
undefined
aws ec2 get-console-screenshot
--instance-id i-1234567890abcdef0
undefined

High CPU/Memory

CPU/内存使用率过高

bash
undefined
bash
undefined

Enable detailed monitoring

Enable detailed monitoring

aws ec2 monitor-instances
--instance-ids i-1234567890abcdef0
aws ec2 monitor-instances
--instance-ids i-1234567890abcdef0

Check CloudWatch metrics

Check CloudWatch metrics

aws cloudwatch get-metric-statistics
--namespace AWS/EC2
--metric-name CPUUtilization
--dimensions Name=InstanceId,Value=i-1234567890abcdef0
--start-time $(date -d '1 hour ago' -u +%Y-%m-%dT%H:%M:%SZ)
--end-time $(date -u +%Y-%m-%dT%H:%M:%SZ)
--period 300
--statistics Average
undefined
aws cloudwatch get-metric-statistics
--namespace AWS/EC2
--metric-name CPUUtilization
--dimensions Name=InstanceId,Value=i-1234567890abcdef0
--start-time $(date -d '1 hour ago' -u +%Y-%m-%dT%H:%M:%SZ)
--end-time $(date -u +%Y-%m-%dT%H:%M:%SZ)
--period 300
--statistics Average
undefined

References

参考资料