AWS VPC 與 EC2
Vibe Prompt
「幫我用 AWS CDK (TypeScript) 建立:VPC(2 個公有子網、2 個私有子網)、EC2 t3.micro、Security Group(開放 22 和 80 埠)、Elastic IP。」
CDK 程式碼
import * as cdk from 'aws-cdk-lib';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
const vpc = new ec2.Vpc(this, 'MyVpc', {
maxAzs: 2,
subnetConfiguration: [
{ name: 'Public', subnetType: ec2.SubnetType.PUBLIC, cidrMask: 24 },
{ name: 'Private', subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS, cidrMask: 24 },
],
});
const sg = new ec2.SecurityGroup(this, 'WebSG', { vpc });
sg.addIngressRule(ec2.Peer.anyIpv4(), ec2.Port.tcp(80));
sg.addIngressRule(ec2.Peer.anyIpv4(), ec2.Port.tcp(22));
const instance = new ec2.Instance(this, 'WebServer', {
vpc,
instanceType: ec2.InstanceType.of(ec2.InstanceClass.T3, ec2.InstanceSize.MICRO),
machineImage: ec2.MachineImage.latestAmazonLinux2023(),
securityGroup: sg,
keyName: 'my-key-pair',
});
new cdk.CfnOutput(this, 'PublicIP', { value: instance.instancePublicIp });
AWS CLI
aws ec2 describe-instances
aws ec2 stop-instances --instance-ids i-123456
aws ec2 start-instances --instance-ids i-123456
關鍵要點
VPC 架構
- ✅ VPC = 你的私有雲端網路,可自訂 IP 範圍 (CIDR)
- ✅ 公有子網:可連 Internet(透過 IGW)
- ✅ 私有子網:不可連 Internet(安全隔離)
- ✅ NAT Gateway:讓私有子網可以發出請求(但不能被連入)
- ✅ Security Group vs NACL:SG 是狀態化,NACL 是無狀態化
EC2 關鍵
- ✅ 選擇 AMI (Amazon Machine Image) 決定作業系統
- ✅ Instance Type 決定 CPU/記憶體 (t2.micro 免費)
- ✅ Key Pair 是 SSH 登入的唯一憑證
- ✅ User Data 可在首次啟動時執行腳本
- ✅ 搭配 Auto Scaling 實現自動擴縮
安全最佳實踐
# 最小權限原則:只開放需要的 Port
# SG:只允許特定 IP 訪問 SSH (22)
aws ec2 authorize-security-group-ingress \
--group-id sg-xxx \
--protocol tcp --port 22 \
--cidr 你的IP/32
# 使用 IAM Role 而非存取金鑰
aws ec2 associate-iam-instance-profile \
--instance-id i-xxx \
--iam-instance-profile Name=YourRole
常見錯誤
程式碼範例
VPC:你的 AWS 私有網路
VPC(Virtual Private Cloud)是你在 AWS 上的私有網路。它隔離了你的資源和網際網路——沒有正確的 VPC 設定,你的資料庫就直接暴露在公開網路上了。
VPC 的核心元件
| 元件 | 用途 | 常見錯誤 | |:----|:----|:--------| | Subnet(子網) | 劃分公有/私有區域 | 所有服務都放在公有子網 | | Route Table(路由表) | 決定流量去向 | 私有子網沒設 NAT 無法更新套件 | | Internet Gateway(IGW) | 連上網際網路 | 忘記 attach 到 VPC | | NAT Gateway | 私有子網連外網 | 成本昂貴(每小時 $0.045)| | | Security Group(安全群組) | 執行個體防火牆 | 開放了所有埠(0.0.0.0/0) | | NACL | 子網層級的防火牆 | 不知道比 Security Group 更底層 |
EC2 的成本最佳化
| 類型 | 使用方式 | 節省幅度 | |:----|:--------|:--------| | On-Demand | 按小時計費 | 0% | | Reserved Instance | 預付 1-3 年 | 40-60% | | Spot Instance | 競價模式(可被打斷) | 60-90% | | Savings Plan | 承諾每小時花費 | 30-50% |
對於 production 服務,RI 或 Savings Plan 是標準選擇。對於批次處理或測試,Spot 可以大幅降低成本。
下一章預告:ECS 與 EKS
學會了 VPC 和 EC2 之後,下一章將進入容器編排——ECS 和 EKS。你會學到如何用 Docker 包裝應用、如何在 AWS 上管理 Container 叢集。