Cung cấp nơi lưu trữ Docker image cho backend NestJS monolithic để ECS Fargate có thể kéo image và chạy container. ECR sẽ là registry center cho backend service của VinaShoes e-commerce platform.
🏗️ ECR trong Container Architecture:
Tạo một repository duy nhất để quản lý backend NestJS monolithic service.
Console Steps:
Console Navigation:

📝 CLI Alternative - Quick ECR Access:
# Check ECR service availability in region
aws ecr describe-registry --region ap-southeast-1
# List existing repositories
aws ecr describe-repositories --region ap-southeast-1
# Get ECR usage statistics
aws ecr get-registry-statistics --region ap-southeast-1
Repository Creation Process:
Create Repository:

Basic Configuration:

vinashoes/backend-serviceproject/service-name
📋 Repository Naming Best Practices:
project/service-name hoặc team/applicationvinashoes/backend-service, frontend/web-app, shared/nginxTag Settings:

⚠️ Tag Immutability Impact:
latest tag updates, more flexible but less secureSecurity Scanning:

🔍 Security Scanning Types:
📝 CLI - Configure Scanning:
# Enable scanning on existing repository
aws ecr put-image-scanning-configuration \
--repository-name vinashoes/backend-service \
--image-scanning-configuration scanOnPush=true \
--region ap-southeast-1
# Start manual scan
aws ecr start-image-scan \
--repository-name vinashoes/backend-service \
--image-id imageTag=latest \
--region ap-southeast-1
Data Encryption:

🔐 Encryption Options:
Finalize Creation:


AWS CLI Alternative (để tạo nhanh):
# Create backend service repository
aws ecr create-repository \
--repository-name vinashoes/backend-service \
--image-tag-mutability IMMUTABLE \
--image-scanning-configuration scanOnPush=true \
--region ap-southeast-1
📝 CLI - Advanced Repository Creation:
# Create repository với KMS encryption
aws ecr create-repository \
--repository-name vinashoes/backend-service \
--image-tag-mutability IMMUTABLE \
--image-scanning-configuration scanOnPush=true \
--encryption-configuration encryptionType=KMS,kmsKey=alias/ecr-key \
--region ap-southeast-1
# Verify repository creation
aws ecr describe-repositories \
--repository-names vinashoes/backend-service \
--region ap-southeast-1
# Get repository URI
aws ecr describe-repositories \
--repository-names vinashoes/backend-service \
--query 'repositories[0].repositoryUri' \
--output text \
--region ap-southeast-1
Lifecycle Policy giúp tự động xóa images cũ để tiết kiệm chi phí storage.
💰 Cost Management Importance:
Console Steps:
Repository Management:
vinashoes/backend-service
Policy Configuration:
Start Policy Creation:
Rule 1: Delete Untagged Images
1Delete untagged images after 1 day1 days
2Keep only 10 most recent tagged images10
Policy Finalization:
Review Rules:
Save Policy:

📝 CLI - Advanced Lifecycle Policies:
# Create comprehensive lifecycle policy
cat > lifecycle-policy.json << EOF
{
"rules": [
{
"rulePriority": 1,
"description": "Keep only 1 untagged image",
"selection": {
"tagStatus": "untagged",
"countType": "imageCountMoreThan",
"countNumber": 1
},
"action": {
"type": "expire"
}
},
{
"rulePriority": 2,
"description": "Keep last 10 production images",
"selection": {
"tagStatus": "tagged",
"tagPrefixList": ["v", "prod"],
"countType": "imageCountMoreThan",
"countNumber": 10
},
"action": {
"type": "expire"
}
},
{
"rulePriority": 3,
"description": "Delete dev images older than 7 days",
"selection": {
"tagStatus": "tagged",
"tagPrefixList": ["dev", "feature"],
"countType": "sinceImagePushed",
"countUnit": "days",
"countNumber": 7
},
"action": {
"type": "expire"
}
}
]
}
EOF
# Apply lifecycle policy
aws ecr put-lifecycle-policy \
--repository-name vinashoes/backend-service \
--lifecycle-policy-text file://lifecycle-policy.json \
--region ap-southeast-1
# Preview lifecycle policy actions
aws ecr preview-lifecycle-policy \
--repository-name vinashoes/backend-service \
--lifecycle-policy-text file://lifecycle-policy.json \
--region ap-southeast-1
Development Setup:
Dockerfile Configuration:
Dockerfile cho Backend Service:
# Multi-stage build for optimization
FROM node:18-alpine AS builder
# Set working directory
WORKDIR /app
# Copy package files first (for better caching)
COPY package*.json ./
COPY tsconfig*.json ./
# Install dependencies
RUN npm ci --only=production && npm cache clean --force
# Copy source code
COPY src/ ./src/
# Build the application
RUN npm run build
# Production stage
FROM node:18-alpine AS production
# Set working directory
WORKDIR /app
# Create non-root user for security
RUN addgroup -g 1001 -S nodejs && \
adduser -S nestjs -u 1001
# Copy built application from builder stage
COPY --from=builder --chown=nestjs:nodejs /app/dist ./dist
COPY --from=builder --chown=nestjs:nodejs /app/node_modules ./node_modules
COPY --chown=nestjs:nodejs package*.json ./
# Switch to non-root user
USER nestjs
# Expose application port
EXPOSE 3000
# Add health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD curl -f http://localhost:3000/health || exit 1
# Start the application
CMD ["node", "dist/main.js"]
🏗️ Multi-stage Build Benefits:
Create .dockerignore:
# Dependencies
node_modules
# Logs
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Build output
dist
# Environment files
.env
.env.local
.env.production
# Git
.git
.gitignore
# IDE
.vscode
.idea
# OS generated files
.DS_Store
Thumbs.db
# Coverage reports
coverage
.nyc_output
# Testing
.cache
📦 Docker Build Optimization:
# Build với BuildKit cho faster builds
DOCKER_BUILDKIT=1 docker build -t vinashoes/backend-service:latest .
# Build với build arguments
docker build \
--build-arg NODE_ENV=production \
--build-arg API_VERSION=v1.0.0 \
-t vinashoes/backend-service:v1.0.0 .
# Multi-platform build
docker buildx build \
--platform linux/amd64,linux/arm64 \
-t vinashoes/backend-service:latest .
# Build với cache mount
docker build \
--mount=type=cache,target=/root/.npm \
-t vinashoes/backend-service:latest .
Local Build Process:
Build Backend Service:
# Navigate to Backend Service directory
cd backend-service
# Build Docker image với multiple tags
docker build -t vinashoes/backend-service:latest .
docker build -t vinashoes/backend-service:v1.0.0 .
# Verify image was created
docker images | grep vinashoes/backend-service
Test Image Locally:
# Test Backend Service container
docker run -d -p 3000:3000 --name test-backend vinashoes/backend-service:latest
# Test health endpoint
curl http://localhost:3000/health
# Test API endpoints
curl http://localhost:3000/api/users
curl http://localhost:3000/api/products
curl http://localhost:3000/api/orders
# Check logs
docker logs test-backend
# Cleanup
docker stop test-backend && docker rm test-backend
🔍 Local Testing Best Practices:
Authentication Setup:
AWS CLI Setup:
# Configure AWS CLI (if not already done)
aws configure
# AWS Access Key ID: [Your Access Key]
# AWS Secret Access Key: [Your Secret Key]
# Default region name: ap-southeast-1
# Default output format: json
# Verify AWS CLI is working
aws sts get-caller-identity
📝 AWS CLI Advanced Configuration:
# Configure multiple profiles
aws configure --profile production
aws configure --profile development
# Use specific profile
aws ecr describe-repositories --profile production --region ap-southeast-1
# Configure with environment variables
export AWS_ACCESS_KEY_ID=your-access-key
export AWS_SECRET_ACCESS_KEY=your-secret-key
export AWS_DEFAULT_REGION=ap-southeast-1
# Verify permissions
aws iam get-user
aws sts get-caller-identity
# Check ECR permissions specifically
aws ecr describe-registry --region ap-southeast-1
ECR Authentication:
Console Method:

CLI Method:
# Get ECR login token và authenticate Docker
aws ecr get-login-password --region ap-southeast-1 | \
docker login --username AWS --password-stdin <account-id>.dkr.ecr.ap-southeast-1.amazonaws.com
# Verify login successful
echo "Login Succeeded"
🔐 ECR Authentication Important Notes:
📝 CLI - Authentication Troubleshooting:
# Check if Docker is running
docker version
# Clear Docker credentials
docker logout <account-id>.dkr.ecr.ap-southeast-1.amazonaws.com
# Re-authenticate với detailed output
aws ecr get-login-password --region ap-southeast-1 | \
docker login --username AWS --password-stdin \
<account-id>.dkr.ecr.ap-southeast-1.amazonaws.com
# Test authentication
docker pull alpine:latest
docker tag alpine:latest <account-id>.dkr.ecr.ap-southeast-1.amazonaws.com/test:latest

Image Push Process:
Repository Information:
# Get AWS Account ID
export AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
# Set ECR registry URL
export ECR_REGISTRY=${AWS_ACCOUNT_ID}.dkr.ecr.ap-southeast-1.amazonaws.com
echo "ECR Registry: $ECR_REGISTRY"
🏷️ Image Tagging Strategies:
📝 CLI - Advanced Tagging:
# Get current git commit hash
export GIT_HASH=$(git rev-parse --short HEAD)
export BUILD_DATE=$(date +%Y%m%d)
# Tag với multiple strategies
docker tag vinashoes/backend-service:latest \
${ECR_REGISTRY}/vinashoes/backend-service:latest
docker tag vinashoes/backend-service:latest \
${ECR_REGISTRY}/vinashoes/backend-service:${GIT_HASH}
docker tag vinashoes/backend-service:latest \
${ECR_REGISTRY}/vinashoes/backend-service:${BUILD_DATE}
docker tag vinashoes/backend-service:latest \
${ECR_REGISTRY}/vinashoes/backend-service:prod-${BUILD_DATE}
Image Tagging:
Tag Backend Service:
# Tag local image với ECR repository URL
docker tag vinashoes/backend-service:latest \
${ECR_REGISTRY}/vinashoes/backend-service:latest
docker tag vinashoes/backend-service:v1.0.0 \
${ECR_REGISTRY}/vinashoes/backend-service:v1.0.0
Push Process:
Push Backend Service:
# Push both tags
docker push ${ECR_REGISTRY}/vinashoes/backend-service:latest
docker push ${ECR_REGISTRY}/vinashoes/backend-service:v1.0.0
🚀 Push Optimization:
# Push với parallel uploads (faster)
docker push --all-tags ${ECR_REGISTRY}/vinashoes/backend-service
# Monitor push progress
docker push ${ECR_REGISTRY}/vinashoes/backend-service:latest 2>&1 | \
grep -E "(Pushed|Layer already exists)"
# Verify push success
aws ecr list-images \
--repository-name vinashoes/backend-service \
--region ap-southeast-1
# Get image digest
aws ecr batch-get-image \
--repository-name vinashoes/backend-service \
--image-ids imageTag=latest \
--query 'images[0].imageManifest' \
--output text | sha256sum

Console Verification:


Security Assessment:
Scan Results Review:


Security Actions:
Review Critical Vulnerabilities:
Common Remediation Steps:
CLI Method to check scans:
# Check scan results for specific image
aws ecr describe-image-scan-findings \
--repository-name vinashoes/backend-service \
--image-id imageTag=v1.0.0 \
--region ap-southeast-1
IAM Configuration cho ECR Access:
Console Steps:


Policy Attachment:
AmazonECSTaskExecutionRolePolicy (managed policy)AmazonEC2ContainerRegistryReadOnly (managed policy)
ecsTaskExecutionRole
CLI Alternative:
# Create trust policy document
cat > ecs-trust-policy.json << EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "ecs-tasks.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
EOF
# Create IAM role
aws iam create-role \
--role-name ecsTaskExecutionRole \
--assume-role-policy-document file://ecs-trust-policy.json
# Attach managed policies
aws iam attach-role-policy \
--role-name ecsTaskExecutionRole \
--policy-arn arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy
aws iam attach-role-policy \
--role-name ecsTaskExecutionRole \
--policy-arn arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly
Permission Testing:
Permission Verification:
# Test ECR access with IAM role
aws ecr list-images \
--repository-name vinashoes/backend-service \
--region ap-southeast-1
# Test image pull capability
docker pull ${ECR_REGISTRY}/vinashoes/backend-service:latest

Functionality Testing:
Pull Test:
# Clean local images first
docker rmi ${ECR_REGISTRY}/vinashoes/backend-service:latest
# Test pull from ECR
docker pull ${ECR_REGISTRY}/vinashoes/backend-service:latest
# Verify image pulled successfully
docker images | grep vinashoes
Container Test:
# Run container from ECR image
docker run -d -p 3000:3000 --name test-ecr-backend \
${ECR_REGISTRY}/vinashoes/backend-service:latest
# Test application health
curl http://localhost:3000/health
# Test API endpoints
curl http://localhost:3000/api/users
curl http://localhost:3000/api/products
curl http://localhost:3000/api/orders
# Check container logs
docker logs test-ecr-backend
# Cleanup
docker stop test-ecr-backend && docker rm test-ecr-backend

Complete System Check:
Verification Checklist:
vinashoes/backend-service (single repository cho monolithic backend)latest và v1.0.0🔍 Security Validation CLI:
# Check scan status and results
aws ecr describe-image-scan-findings \
--repository-name vinashoes/backend-service \
--image-id imageTag=latest \
--region ap-southeast-1
# Get security findings summary
aws ecr describe-image-scan-findings \
--repository-name vinashoes/backend-service \
--image-id imageTag=latest \
--query 'imageScanFindingsSummary.findingCounts' \
--region ap-southeast-1
# Check image encryption status
aws ecr describe-repositories \
--repository-names vinashoes/backend-service \
--query 'repositories[0].encryptionConfiguration' \
--region ap-southeast-1
🛡️ IAM Permission Validation:
# Test ECR access with current credentials
aws ecr describe-repositories --region ap-southeast-1
# Check specific repository permissions
aws ecr describe-repository-permissions \
--repository-name vinashoes/backend-service \
--region ap-southeast-1
# Test image pull permissions
aws ecr batch-get-image \
--repository-name vinashoes/backend-service \
--image-ids imageTag=latest \
--region ap-southeast-1
# Validate task execution role
aws iam get-role \
--role-name ecsTaskExecutionRole \
--query 'Role.AssumeRolePolicyDocument'
🧪 Production Testing Checklist:
# Test image pull from different environments
docker pull ${ECR_REGISTRY}/vinashoes/backend-service:latest
# Verify image integrity
docker inspect ${ECR_REGISTRY}/vinashoes/backend-service:latest \
--format='{{.Id}}'
# Test container startup and health
docker run -d --name test-backend \
-p 3000:3000 \
${ECR_REGISTRY}/vinashoes/backend-service:latest
# Check container logs
docker logs test-backend
# Verify API endpoints
curl -f http://localhost:3000/health || echo "Health check failed"
# Cleanup test container
docker stop test-backend && docker rm test-backend
Chuẩn bị cho Task 9 - ECS Fargate:
Với ECR repository và image đã ready, Task 9 sẽ:
Quick Verification Command:
# Ensure image is ready for ECS deployment
aws ecr describe-images \
--repository-name vinashoes/backend-service \
--query 'imageDetails[0].[imageTags[0],imageSizeInBytes,imagePushedAt]' \
--output table \
--region ap-southeast-1
Authentication Failures:
aws ecr get-login-password commandPush Failures:
Scan Failures:
Permission Denied:
AWS CLI Commands:
# List all images in the repository
aws ecr list-images --repository-name vinashoes/backend-service --region ap-southeast-1
# Delete all images in the repository
aws ecr batch-delete-image --repository-name vinashoes/backend-service --image-ids imageTag=latest imageTag=v1.0.0 --region ap-southeast-1
# Delete the repository
aws ecr delete-repository --repository-name vinashoes/backend-service --force --region ap-southeast-1
AWS CLI Commands:
# Detach policies from the role
aws iam detach-role-policy --role-name ecsTaskExecutionRole --policy-arn arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy
aws iam detach-role-policy --role-name ecsTaskExecutionRole --policy-arn arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly
# Delete the role
aws iam delete-role --role-name ecsTaskExecutionRole
AWS CLI Commands:
# Delete lifecycle policy
aws ecr delete-lifecycle-policy --repository-name vinashoes/backend-service --region ap-southeast-1
Verification Commands:
# Verify repository deleted
aws ecr describe-repositories --region ap-southeast-1 | grep vinashoes/backend-service || echo "Repository deleted"
# Verify role deleted
aws iam get-role --role-name ecsTaskExecutionRole || echo "Role deleted"
| Dịch vụ | Chi phí | Mô tả |
|---|---|---|
| Lưu trữ | $0.10/GB/tháng | Lưu trữ Docker images |
| Transfer dữ liệu | Miễn phí trong region | Transfer trong cùng region ap-southeast-1 |
| Quét lỗ hổng | Miễn phí (Basic) | Quét bảo mật cơ bản |
| Quét nâng cao | $0.09/GB | Quét bảo mật chi tiết (tùy chọn) |
Chi phí hàng tháng ước tính:
Lợi ích của ECR:
Tính toán ROI:
AWS Cost Explorer Commands:
# Get ECR costs for last month
aws ce get-cost-and-usage \
--time-period Start=2024-01-01,End=2024-02-01 \
--granularity MONTHLY \
--metrics BlendedCost \
--group-by Type=DIMENSION,Key=SERVICE \
--filter '{
"Dimensions": {
"Key": "SERVICE",
"Values": ["Amazon Elastic Container Registry"]
}
}' \
--region us-east-1
CloudWatch Monitoring:
# Monitor ECR storage usage
aws cloudwatch get-metric-statistics \
--namespace AWS/ECR \
--metric-name RepositorySize \
--dimensions Name=RepositoryName,Value=vinashoes/backend-service \
--start-time 2024-01-01T00:00:00Z \
--end-time 2024-02-01T00:00:00Z \
--period 86400 \
--statistics Maximum \
--region ap-southeast-1
Lifecycle Policies:
Image Optimization:
Monitoring & Alerts: