Chuyển đến nội dung chính

Terraform: Hướng dẫn triển khai ASP.NET Core lên Azure bằng Docker + Terraform - Part 4

Trong bài này, chúng ta sẽ cùng đi qua toàn bộ quy trình DevOps cơ bản cho một ứng dụng ASP.NET Core, bao gồm:

  1. Tạo project ASP.NET Core
  2. Viết file Dockerfile, build và run image ở local
  3. Push image lên Docker Hub
  4. Tạo các file Terraform (variables.tf, main.tf, outputs.tf) để triển khai container lên Azure Container Instance

Tạo project ASP.NET Core

Mở terminal và chạy

dotnet new webapp -o AspNetCoreGettingStarted
cd AspNetCoreGettingStarted
dotnet run
Ở bước này, bạn chú ý trong folder bin, sẽ có dll là AspNetCoreGettingStarted.dll. Ở bước tạo Dockerfile, chúng ta sẽ sử dụng EntryPoint trỏ tới dll này

Tạo file Dockerfile

Trong thư mục project, tạo file Dockerfile.

Ở đây mình sử dụng Alpine Linux – phiên bản nhẹ, tối ưu cho container.

# syntax=docker/dockerfile:1
# Stage 1: Build application
FROM mcr.microsoft.com/dotnet/sdk:9.0-alpine AS build-env
WORKDIR /app

# Copy csproj and restore as distinct layers
COPY *.csproj ./
RUN dotnet restore

# Copy everything else and build
COPY . ./
RUN dotnet publish -c Release -o out

# Stage 2: Build runtime image
FROM mcr.microsoft.com/dotnet/aspnet:9.0-alpine
WORKDIR /app
COPY --from=build-env /app/out .

# Expose port 80 and define environment variable
ENV ASPNETCORE_URLS=http://+:80
EXPOSE 80

ENTRYPOINT ["dotnet", "AspNetCoreGettingStarted.dll"]

Giải thích

  • alpine: phiên bản Linux siêu nhẹ, lý tưởng cho container.
  • sdk dùng để build, aspnet dùng để chạy app.
  • EXPOSE 80 cho phép truy cập app qua cổng 80.
  • ENTRYPOINT chỉ định file .dll sẽ được thực thi.

Build và chạy container ở local

Bạn cần bật service dockerd hoặc mở Docker Desktop.
Từ thư mục có Dockerfile, bạn gõ:
docker build -t ananhtest/aspnetcore-demo:latest .
docker run -d -p 8080:80 ananhtest/aspnetcore-demo:latest
Truy cập http://localhost:8080 để kiểm tra kết quả

Push image lên Docker Hub

Login vào Docker Hub, ở bước này bạn cần làm theo hướng dẫn trên Command Line.
docker login
...
docker push ananhtest/aspnetcore-demo:latest
Kiểm tra lại repository: https://hub.docker.com/repositories

Tạo các file Terraform

Chúng ta sẽ có cấu trúc thư mục
terraform-aci/
├── main.tf
├── variables.tf
└── outputs.tf
File variables.tf giúp ta tách phần cấu hình linh hoạt — để có thể thay đổi tên resource, image, hoặc vùng triển khai mà không phải chỉnh trong main.tf.
variable "resource_group_name" {
  description = "Name of the Azure Resource Group."
  type        = string
  default     = "resource-group-name"
}

variable "location" {
  description = "Azure region where resources will be deployed."
  type        = string
  default     = "Southeast Asia"
}

variable "container_name" {
  description = "Name of the Azure Container Instance."
  type        = string
  default     = "aspnetcore-demo"
}

variable "docker_image" {
  description = "Full path of the Docker image to deploy (e.g. user/image:tag)."
  type        = string
  default     = "ananhtest/aspnetcore-demo:latest"
}

variable "cpu" {
  description = "Number of CPU cores allocated to the container."
  type        = number
  default     = 1
}

variable "memory" {
  description = "Amount of memory (in GB) allocated to the container."
  type        = number
  default     = 1.5
}
main.tf là nơi chứa logic chính — định nghĩa Resource Group, Container Group, và các cấu hình Azure.
terraform {
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "~> 4.0"
    }
    random = {
      source = "hashicorp/random"
    }
  }
}

provider "azurerm" {
  features {}
  
  subscription_id = "YOUR_AZURE_SUBSCRIPTION_ID"
}

# Create Resource Group
resource "azurerm_resource_group" "rg" {
  name     = var.resource_group_name
  location = var.location
}

# Generate random number for unique DNS
resource "random_integer" "suffix" {
  min = 1000
  max = 9999
}

# Create Azure Container Instance
resource "azurerm_container_group" "app" {
  name                = var.container_name
  location            = azurerm_resource_group.rg.location
  resource_group_name = azurerm_resource_group.rg.name
  os_type             = "Linux"

  container {
    name   = var.container_name
    image  = var.docker_image
    cpu    = var.cpu
    memory = var.memory

    ports {
      port     = 80
      protocol = "TCP"
    }

    environment_variables = {
      ASPNETCORE_URLS = "http://+:80"
    }
  }

  ip_address_type = "Public"
  dns_name_label  = "${var.container_name}-${random_integer.suffix.result}"
  restart_policy  = "Always"

  tags = {
    environment = "demo"
  }
}

Để biết được subscription id, bạn gõ:

az account show
{
  "environmentName": "AzureCloud",
  "id": "3xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
  "isDefault": true,
  "name": "Pay-As-You-Go",
  "tenantId": "1xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
  "user": {
    "name": "you@example.com",
    "type": "user"
  }
}
id trong kết quả trả về Subscription Id.
Hoặc bạn có thể gõ chỉ xuất ra Azure Subscription ID thôi
az account show --query "id"

File outputs.tf giúp Terraform in ra URL, Resource Group, và Container Name sau khi deploy thành công.

output "website_url" {
  description = "Public URL to access the ASP.NET Core web app."
  value       = "http://${azurerm_container_group.app.dns_name_label}.southeastasia.azurecontainer.io"
}

output "resource_group_name" {
  description = "Name of the created Azure Resource Group."
  value       = azurerm_resource_group.rg.name
}

output "container_name" {
  description = "Name of the deployed Azure Container Instance."
  value       = azurerm_container_group.app.name
}

Apply Terraform

Trước khi chạy Terraform, bạn cần đăng nhập Azure:
az login
Sau đó bạn run các lệnh
terraform init
terraform plan
terraform apply -auto-approve
Sau khi hoàn tất, bạn sẽ thấy kết quả:
Outputs:

website_url = "http://aspnetcore-demo-1234.southeastasia.azurecontainer.io"
resource_group_name = "abc"
container_name = "aspnetcore-demo"

Dọn dẹp tài nguyên

Khi không dùng nữa:
terraform destroy -auto-approve

Nhận xét

Bài đăng phổ biến từ blog này

[ASP.NET MVC] Authentication và Authorize

Một trong những vấn đề bảo mật cơ bản nhất là đảm bảo những người dùng hợp lệ truy cập vào hệ thống. ASP.NET đưa ra 2 khái niệm: Authentication và Authorize Authentication xác nhận bạn là ai. Ví dụ: Bạn có thể đăng nhập vào hệ thống bằng username và password hoặc bằng ssh. Authorization xác nhận những gì bạn có thể làm. Ví dụ: Bạn được phép truy cập vào website, đăng thông tin lên diễn đàn nhưng bạn không được phép truy cập vào trang mod và admin.

ASP.NET MVC: Cơ bản về Validation

Validation (chứng thực) là một tính năng quan trọng trong ASP.NET MVC và được phát triển trong một thời gian dài. Validation vắng mặt trong phiên bản đầu tiên của asp.net mvc và thật khó để tích hợp 1 framework validation của một bên thứ 3 vì không có khả năng mở rộng. ASP.NET MVC2 đã hỗ trợ framework validation do Microsoft phát triển, tên là Data Annotations. Và trong phiên bản 3, framework validation đã hỗ trợ tốt hơn việc xác thực phía máy khách, và đây là một xu hướng của việc phát triển ứng dụng web ngày nay.

Tổng hợp một số kiến thức lập trình về Amibroker

Giới thiệu về Amibroker Amibroker theo developer Tomasz Janeczko được xây dựng dựa trên ngôn ngữ C. Vì vậy bộ code Amibroker Formula Language sử dụng có syntax khá tương đồng với C, ví dụ như câu lệnh #include để import hay cách gói các object, hàm trong các block {} và kết thúc câu lệnh bằng dấu “;”. AFL trong Amibroker là ngôn ngữ xử lý mảng (an array processing language). Nó hoạt động dựa trên các mảng (các dòng/vector) số liệu, khá giống với cách hoạt động của spreadsheet trên excel.