Best practices
1 - Security
1.1 Principle of least privilege
// Task Role - Permissions minimales
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:GetObject"
],
"Resource": "arn:aws:s3:::mon-bucket/data/*"
}
]
}
1.2 Secrets Management
// Utiliser Secrets Manager
{
"secrets": [
{
"name": "DB_PASSWORD",
"valueFrom": "arn:aws:secretsmanager:eu-west-1:123456789:secret:db-creds:password::"
}
]
}
To avoid:
// NE PAS faire ça
{
"environment": [
{"name": "DB_PASSWORD", "value": "mon-mot-de-passe"}
]
}
1.3 Secure images
# Utiliser des images de base officielles
FROM public.ecr.aws/docker/library/node:18-alpine
# Créer un utilisateur non-root
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
USER appuser
# Scanner les vulnérabilités avec ECR
1.4 Network isolation
# Tasks dans des subnets privés
NetworkConfiguration:
AwsvpcConfiguration:
Subnets:
- !Ref PrivateSubnet1
- !Ref PrivateSubnet2
AssignPublicIp: DISABLED
SecurityGroups:
- !Ref RestrictiveSecurityGroup
2 - High availability
2.1 Multi-AZ
# Distribuer sur plusieurs AZ
ECSService:
Properties:
NetworkConfiguration:
AwsvpcConfiguration:
Subnets:
- !Ref PrivateSubnetAZ1
- !Ref PrivateSubnetAZ2
- !Ref PrivateSubnetAZ3
PlacementStrategies:
- Type: spread
Field: attribute:ecs.availability-zone
2.2 Minimum number of tasks
# Au moins 2 tasks pour HA
ScalableTarget:
Properties:
MinCapacity: 2
MaxCapacity: 10
2.3 Health checks
// Container health check
{
"healthCheck": {
"command": ["CMD-SHELL", "curl -f http://localhost:8080/health || exit 1"],
"interval": 30,
"timeout": 5,
"retries": 3,
"startPeriod": 60
}
}
# ALB health check
TargetGroup:
Properties:
HealthCheckPath: /health
HealthCheckIntervalSeconds: 30
HealthyThresholdCount: 2
UnhealthyThresholdCount: 3
3 - Performance
3.1 Right-sizing
| Workload | CPU | Memory |
|---|---|---|
| Lightweight API | 256 | 512 |
| Standard API | 512 | 1024 |
| Worker | 1024 | 2048 |
| Data processing | 2048+ | 4096+ |
3.2 Connection pooling
// Node.js - Pool de connexions DB
const pool = new Pool({
max: 10,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000
});
3.3 Graceful shutdown
// Gérer SIGTERM pour Fargate Spot
process.on('SIGTERM', async () => {
console.log('SIGTERM received, shutting down gracefully');
// Arrêter d'accepter les nouvelles requêtes
server.close();
// Terminer les requêtes en cours
await finishPendingRequests();
// Fermer les connexions DB
await pool.end();
process.exit(0);
});
4 - Deployments
4.1 Circuit breaker
DeploymentConfiguration:
DeploymentCircuitBreaker:
Enable: true
Rollback: true
MinimumHealthyPercent: 100
MaximumPercent: 200
4.2 Cautious rolling update
# Pas de downtime
DeploymentConfiguration:
MinimumHealthyPercent: 100
MaximumPercent: 200
HealthCheckGracePeriodSeconds: 120
4.3 Blue/Green for major changes
DeploymentController:
Type: CODE_DEPLOY
5 - Cost
5.1 Fargate Spot
# 70% d'économies sur les workloads tolérants
CapacityProviderStrategy:
- CapacityProvider: FARGATE
Base: 2
Weight: 1
- CapacityProvider: FARGATE_SPOT
Weight: 4
5.2 ARM64
{
"runtimePlatform": {
"cpuArchitecture": "ARM64"
}
}
5.3 Right-sizing with Container Insights
-- Identifier les tasks sur-provisionnées
SELECT ServiceName,
avg(CpuUtilized) as avg_cpu,
avg(CpuReserved) as reserved_cpu,
avg(CpuUtilized) / avg(CpuReserved) * 100 as cpu_efficiency
FROM "ContainerInsights"
GROUP BY ServiceName
HAVING avg(CpuUtilized) / avg(CpuReserved) < 0.5
5.4 Scheduled scaling
# Scale-in la nuit
ScheduledActions:
- ScheduledActionName: NightScaleIn
Schedule: "cron(0 22 * * ? *)"
ScalableTargetAction:
MinCapacity: 1
MaxCapacity: 2
6 - Logging
6.1 Structured format
// JSON logging
console.log(JSON.stringify({
timestamp: new Date().toISOString(),
level: 'INFO',
message: 'Request processed',
requestId: req.id,
duration: 45,
statusCode: 200
}));
6.2 Log retention
LogGroup:
Type: AWS::Logs::LogGroup
Properties:
RetentionInDays: 30 # Adapter selon les besoins
6.3 Non-blocking logs
{
"logConfiguration": {
"options": {
"mode": "non-blocking",
"max-buffer-size": "25m"
}
}
}
7 - Production checklist
Before deployment
- Images scanned for vulnerabilities
- Secrets in Secrets Manager
- IAM roles with least privilege
- Health checks configured
- Structured logs
- Metrics and alerts
- Circuit breaker enabled
Infrastructure
- Multi-AZ
- VPC endpoints configured
- Restrictive security groups
- ALB with HTTPS
- Auto scaling configured
Monitoring
- Container Insights enabled
- CPU/Memory alerts
- CloudWatch dashboard
- Logs Insights queries
8 - Reference architecture
Summary
In this chapter, we covered:
- Security best practices
- Configuration for high availability
- Performance optimization
- Deployment strategies
- Cost optimization
- Structured logging
- A production checklist
Next step
In the next chapter, we will put things into practice with Exercises and Projects.
→ Next chapter: Exercises and Projects