Bonnes pratiques
1 - Sécurité
1.1 Principe du moindre privilège
// 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::"
}
]
}
À éviter :
// NE PAS faire ça
{
"environment": [
{"name": "DB_PASSWORD", "value": "mon-mot-de-passe"}
]
}
1.3 Images sécurisées
# 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 - Haute disponibilité
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 de 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 |
|---|---|---|
| API légère | 256 | 512 |
| API standard | 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 - Déploiements
4.1 Circuit breaker
DeploymentConfiguration:
DeploymentCircuitBreaker:
Enable: true
Rollback: true
MinimumHealthyPercent: 100
MaximumPercent: 200
4.2 Rolling update prudent
# Pas de downtime
DeploymentConfiguration:
MinimumHealthyPercent: 100
MaximumPercent: 200
HealthCheckGracePeriodSeconds: 120
4.3 Blue/Green pour les changements majeurs
DeploymentController:
Type: CODE_DEPLOY
5 - Coûts
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 avec 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 Format structuré
// JSON logging
console.log(JSON.stringify({
timestamp: new Date().toISOString(),
level: 'INFO',
message: 'Request processed',
requestId: req.id,
duration: 45,
statusCode: 200
}));
6.2 Retention des logs
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 - Checklist de production
Avant le déploiement
- Images scannées pour vulnérabilités
- Secrets dans Secrets Manager
- IAM roles avec least privilege
- Health checks configurés
- Logs structurés
- Métriques et alertes
- Circuit breaker activé
Infrastructure
- Multi-AZ
- VPC endpoints configurés
- Security groups restrictifs
- ALB avec HTTPS
- Auto scaling configuré
Monitoring
- Container Insights activé
- Alertes CPU/Memory
- Dashboard CloudWatch
- Logs Insights queries
8 - Architecture de référence
Résumé
Dans ce chapitre, nous avons couvert :
- Les bonnes pratiques de sécurité
- La configuration pour la haute disponibilité
- L'optimisation des performances
- Les stratégies de déploiement
- L'optimisation des coûts
- Le logging structuré
- Une checklist de production
Prochaine étape
Dans le prochain chapitre, nous mettrons en pratique avec des Exercices et Projets.
→ Chapitre suivant : Exercices et Projets