Bỏ qua, tới nội dung chính

Triển khai AWS và Azure: cấu hình, secrets và health check của service .NET

Bài 36: cùng image tới ECS Fargate hoặc Azure Container Apps, phân biệt workload identity với user identity và đi qua migration, readiness, rollout có kiểm soát.

Quản trị viên5 phút đọc

Đây là bài 36 của loạt C# và .NET 10 qua Tới Nơi. Bài 31–38 cùng giải thích code cuối của service tại examples/toi-noi-dotnet/31-38-trip-service, target net10.0.

Thử trước khi đọc

Managed identity của container có tự trở thành danh tính customer trong JWT không?

Xem đáp án

Không. Workload identity và end-user identity có ranh giới, token và quyền khác nhau.

Cùng service, hai đích vận hành

AWS chọn ECS Fargate với RDS PostgreSQL; Azure chọn Container Apps với PostgreSQL Flexible Server. Hai phương án là hướng dẫn cho cùng service/image, không phải là yêu cầu deploy đồng thời lên hai cloud hay nhân đôi dữ liệu.

Repository có task-definition template và Bicep cụ thể để review. Bicep đã compile sang ARM trong môi trường soạn bài; chưa có tài nguyên nào được tạo ở một account hoặc subscription và chưa có phép thử network và identity trên cloud thật.

CPU/memory/replica trong template chỉ là điểm bắt đầu cho lab. Phải load-test, quan sát PostgreSQL connections và latency trước khi chốt capacity hoặc autoscale. Không dùng kết quả microbenchmark của parser ở bài 28 để chọn cỡ tài nguyên cho Fargate.

AWS: execution role khác task role

Execution role cho phép agent pull image, gửi log và lấy secret cần thiết lúc task khởi động. Task role là quyền runtime của ứng dụng nếu nó gọi AWS API. Nhầm hai role có thể khiến cấu hình không chạy được hoặc cấp quyền quá rộng.

Task definition nhận immutable ECR image digest, secret ARN và thông tin identity provider. Secret phải là connection string đầy đủ và hợp lệ với TLS VerifyFull theo kiểm tra production của API, không chỉ riêng password.

ECS service, target group ip, ALB/TLS, VPC/subnet/security group, RDS và DNS là điều kiện tiên quyết nằm ngoài file task definition. Dùng path /health/ready để kiểm tra khả năng nhận traffic; không mở RDS ra Internet để xử lý lỗi private networking.

AWS FargateExecution / task roleCùng image digestMột service contractAzure Container AppsIdentity + Key Vault
Hình 1. Hai đích triển khai của cùng artifact; identity workload không phải principal người dùng.

Azure: identity cho ACR và Key Vault

Bicep nhận managed environment, user-assigned identity và registry đã có. Identity dùng để pull image và đọc đúng secret Key Vault mà URI tham chiếu tới, không ghi password trực tiếp vào parameter thường hoặc source.

Identity đó không tự khiến Npgsql dùng xác thực Entra. Code mẫu vẫn nhận connection string; muốn dùng token cho database thì cần thêm credential, cơ chế làm mới token và ánh xạ database role đúng cách. Tương tự, workload identity không thay JWT của khách/tài xế.

Private endpoint/firewall/DNS và quyền Key Vault/ACR cần kiểm tra riêng. Compile Bicep không chứng minh identity có quyền đọc secret URI hay app tới được PostgreSQL trong mạng của subscription.

Probe và rollout theo trạng thái

Probe live chỉ chứng minh process có thể trả lời; readiness kiểm tra cả database lẫn migration. Startup probe cho ứng dụng một khoảng thời gian khởi động riêng. Không lấy sự cố DB làm lý do khởi động lại mọi replica thông qua một liveness query tới DB.

Release nên review và chạy migration bằng role riêng, triển khai cùng image đã kiểm tra, đợi readiness, chạy smoke test có xác thực và quan sát error/conflict/latency. Secret rotation có thể cần task/revision mới để workload nhận được giá trị mới; đừng mặc định rằng mọi cấu hình đều được nạp lại khi đang chạy (hot reload).

Bài tập: readiness trả 503 trong khi live trả 200 có luôn là bug không? Image rollback có đảm bảo dữ liệu migration quay lại nguyên trạng không?

Xem đáp án

Không: process còn sống nhưng chưa sẵn sàng nhận traffic là trạng thái hữu ích. Rollback code không tự hoàn tác dữ liệu/schema; cần kế hoạch migration tương thích và kế hoạch phục hồi rõ ràng.

Migration gateRole riêng + review SQLRevision / task mớiProbe + smokeQuan sát rolloutTraffic + error + DB
Hình 2. Không tự deploy hoặc rollback migration chỉ vì một file template compile được.

Code và kiểm chứng

Thiết lập TOI_NOI_PG cho database local riêng toi_noi_dotnet_lab theo README bài 21, rồi từ gốc repository:

dotnet test examples/toi-noi-dotnet/31-38-trip-service/Tests

Fixture dùng schema GUID riêng, không xoá database; JWT dùng khoá ngẫu nhiên trong test và vẫn đi qua handler xác thực thật. Test không tự bỏ qua khi thiếu PostgreSQL. Docker/CI/cloud spec xem README service và cloud/README.md để biết phạm vi, điều kiện tiên quyết và phần chưa triển khai thật.

main.bicep — 31-38-trip-service/cloud/main.bicep

targetScope = 'resourceGroup'

param appName string
param location string = resourceGroup().location
param environmentResourceId string
param identityResourceId string
param registryServer string
@description('Immutable registry image reference including @sha256 digest.')
param imageDigest string
@description('Key Vault secret URI for the full PostgreSQL connection string, with TLS VerifyFull.')
param postgresSecretUrl string
param authAuthority string
param authAudience string

resource trips 'Microsoft.App/containerApps@2025-01-01' = {
  name: appName
  location: location
  identity: {
    type: 'UserAssigned'
    userAssignedIdentities: {
      '${identityResourceId}': {}
    }
  }
  properties: {
    managedEnvironmentId: environmentResourceId
    configuration: {
      activeRevisionsMode: 'Single'
      ingress: { external: true, targetPort: 8080, allowInsecure: false }
      registries: [{ server: registryServer, identity: identityResourceId }]
      secrets: [{ name: 'postgres', keyVaultUrl: postgresSecretUrl, identity: identityResourceId }]
    }
    template: {
      scale: { minReplicas: 1, maxReplicas: 3 }
      containers: [{
        name: 'trips'
        image: imageDigest
        resources: { cpu: json('0.5'), memory: '1Gi' }
        env: [
          { name: 'ASPNETCORE_ENVIRONMENT', value: 'Production' }
          { name: 'ASPNETCORE_HTTP_PORTS', value: '8080' }
          { name: 'ConnectionStrings__Trips', secretRef: 'postgres' }
          { name: 'Auth__Authority', value: authAuthority }
          { name: 'Auth__Audience', value: authAudience }
        ]
        probes: [
          { type: 'Startup', httpGet: { path: '/health/live', port: 8080 }, periodSeconds: 2, failureThreshold: 30 }
          { type: 'Liveness', httpGet: { path: '/health/live', port: 8080 }, periodSeconds: 10, failureThreshold: 3 }
          { type: 'Readiness', httpGet: { path: '/health/ready', port: 8080 }, periodSeconds: 10, failureThreshold: 3 }
        ]
      }]
    }
  }
}

output appResourceId string = trips.id
output fqdn string = trips.properties.configuration.ingress.fqdn

aws-task-definition.json.template — 31-38-trip-service/cloud/aws-task-definition.json.template

{
  "family": "toi-noi-trips",
  "networkMode": "awsvpc",
  "requiresCompatibilities": ["FARGATE"],
  "runtimePlatform": { "operatingSystemFamily": "LINUX", "cpuArchitecture": "X86_64" },
  "cpu": "256",
  "memory": "512",
  "executionRoleArn": "${EXECUTION_ROLE_ARN}",
  "taskRoleArn": "${TASK_ROLE_ARN}",
  "containerDefinitions": [{
    "name": "trips",
    "image": "${IMAGE_DIGEST}",
    "essential": true,
    "portMappings": [{ "containerPort": 8080, "protocol": "tcp" }],
    "environment": [
      { "name": "ASPNETCORE_ENVIRONMENT", "value": "Production" },
      { "name": "ASPNETCORE_HTTP_PORTS", "value": "8080" },
      { "name": "Auth__Authority", "value": "${AUTH_AUTHORITY}" },
      { "name": "Auth__Audience", "value": "${AUTH_AUDIENCE}" }
    ],
    "secrets": [{ "name": "ConnectionStrings__Trips", "valueFrom": "${PG_SECRET_ARN}" }],
    "logConfiguration": {
      "logDriver": "awslogs",
      "options": { "awslogs-group": "${LOG_GROUP}", "awslogs-region": "${AWS_REGION}", "awslogs-stream-prefix": "trips" }
    }
  }]
}

Bài trước: bài 35. Bài tiếp: bài 37.

Tài liệu gốc

Bạn thấy bài viết này thế nào?

Chọn một hoặc nhiều cảm xúc. Bấm lần nữa để bỏ chọn.

Bình luận (…)