使用 GitHub Copilot 的容器基礎架構
容器化不再是與基礎建設分開的議題。 當你的應用程式在 Kubernetes 上執行時,Dockerfile、Kubernetes 清單和底層的 Azure 基礎設施都會屬於同一個 IaC 資產。 它們共用相同的版本控制、相同的 CI/CD 流程,以及相同的審查流程。
GitHub Copilot 非常適合容器基礎架構,因為 Dockerfile 語法和 Kubernetes YAML 結構化且模式豐富。 這些特性與使 Bicep 產生有效的特質相同。 大多數容器化模式常見於開源專案中,讓 Copilot 能充分涵蓋最佳實務。
使用 GitHub Copilot 產生 Dockerfile
良好 Dockerfile 提示詞的結構
有效的 Dockerfile 提示字元會指定應用程式類型、基礎映像、執行時需求及安全要求。 缺少這些核心容器元件,副駕駛會預設使用較簡單但安全性較低的模式。
一個簡單但有問題的提示:
Create a Dockerfile for a Node.js app.
Copilot 可能會產生單一階段 Dockerfile,以根執行、包含開發相依性,並使用未固定的基礎映像標籤。 這些因素都涉及安全或效率。
更好的題目:
Generate a production-grade multi-stage Dockerfile for a Node.js Express application.
Requirements:
- Build stage: node:20-alpine, install all dependencies, no build step needed (pure JS)
- Runtime stage: node:20-alpine
- Copy only node_modules and application files to the runtime stage
- Do not include devDependencies in the runtime image
- Create a non-root user with UID 1001 and run the process as that user
- Set NODE_ENV=production
- Expose port 3000
- Add a HEALTHCHECK that polls GET /health every 30 seconds
- Pin the base image to a specific digest for reproducibility
多階段建置
單階段 Dockerfile 會將所有資料複製到最終映像檔,包括建置工具、開發相依、測試檔案及原始碼映射。 這種做法可能會膨脹影像大小並增加攻擊面。 多階段建置將建置環境與執行環境分開。 只有執行應用程式所需的產物會被複製到最終映像中。
# Stage 1: Build
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
# Stage 2: Runtime
FROM node:20-alpine AS runtime
WORKDIR /app
# Create non-root user
RUN addgroup -S appgroup && adduser -S appuser -G appgroup -u 1001
# Copy only what is needed from the build stage
COPY --from=builder --chown=appuser:appgroup /app/node_modules ./node_modules
COPY --from=builder --chown=appuser:appgroup /app/package.json ./
COPY --from=builder --chown=appuser:appgroup /app/server.js ./
COPY --from=builder --chown=appuser:appgroup /app/routes ./routes
ENV NODE_ENV=production
USER appuser
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
CMD wget -qO- http://localhost:3000/health || exit 1
CMD ["node", "server.js"]
使用 Copilot 作為安全審查員
產生 Dockerfile 後,請 Copilot 審查:
Review this Dockerfile for security vulnerabilities and best practices.
Check for:
1. Processes running as root
2. Sensitive files or environment variables that might be copied into the image
3. Unpinned or mutable image tags (e.g., "latest")
4. Unnecessary packages or capabilities included in the runtime image
5. Missing HEALTHCHECK instruction
6. Layer caching inefficiencies that could expose secrets in build history
Copilot 會標示特定的線號並解釋每個問題。 這個檢閱提示適用於任何 Dockerfile,不僅限於由 Copilot 產生的 Dockerfile。
使用 GitHub Copilot 生成 Kubernetes 清單
Kubernetes 提示詞中應包含哪些內容
Kubernetes 清單與叢集特定資源互動:入口控制器、儲存類別、命名空間及身份系統。 一個好的 Kubernetes 提示應明確指出:
- 所需的資源類型(部署、服務、入口、ConfigMap 等等)
- 應用程式的埠與協定
- 資源請求與限制
- 健康探測器端點
- 環境變數及其來源(ConfigMap、Secret 或直接值)
- 命名空間
- 如果適用,請提供入口類別名稱
產生完整部署堆疊
Generate Kubernetes YAML manifests for a Node.js API application on AKS.
Include the following resources separated by ---:
Deployment:
- 3 replicas
- Image: iaclab-api:v1 (from a private ACR registry acr-iaclab.azurecr.io)
- Resource requests: 100m CPU, 128Mi memory
- Resource limits: 500m CPU, 512Mi memory
- Liveness probe: GET /health on port 3000, initialDelaySeconds 10, periodSeconds 15
- Readiness probe: GET /ready on port 3000, initialDelaySeconds 5, periodSeconds 10
- Environment variable APP_ENV sourced from a ConfigMap named "iaclab-config"
- Pod anti-affinity: prefer to spread replicas across different nodes
(preferredDuringSchedulingIgnoredDuringExecution)
Service:
- ClusterIP type
- Port 80 mapping to container port 3000
Ingress:
- Ingress class: nginx
- Host: iaclab.training.azure.com
- Path: / (prefix)
- TLS: reference a secret named "iaclab-tls"
ConfigMap:
- Name: iaclab-config
- Key APP_ENV with value "staging"
Apply namespace: iaclab to all resources.
了解健全狀態探查
Kubernetes 使用兩種探測器來管理容器生命週期。
活度探針 回答了這個問題:這個容器是活的嗎? 如果存活探測反覆失敗,Kubernetes 會終止容器並啟動新容器。 用它來偵測應用程式何時進入無法恢復的狀態,例如死結或崩潰迴圈。
準備探測 器回答了這個問題:這個容器是否準備好接收流量? 如果準備度探測失敗,Kubernetes 會將該 pod 從服務端點清單中移除。 流量會停止流向它,直到探測器恢復。 用它來通知應用程式何時啟動完成或暫時過載。
要新增啟動探針:
Add a startupProbe to the Deployment container spec. The startup probe should
call GET /health on port 3000, with a failureThreshold of 30 and
periodSeconds of 10. This gives the container up to 5 minutes to start before
liveness probes begin checking.
使用安全性內容強化
預設情況下,Kubernetes 容器會以超出必要的權限執行。 Pod 和容器層級的 securityContext 會限制容器可執行的操作。
Add security contexts to the Deployment in this manifest:
Pod-level securityContext:
- runAsNonRoot: true
- seccompProfile type: RuntimeDefault
Container-level securityContext:
- runAsUser: 1001
- runAsGroup: 1001
- readOnlyRootFilesystem: true
- allowPrivilegeEscalation: false
- capabilities: drop ALL
Also add an emptyDir volume mounted at /tmp so the application can write
temporary files despite the read-only root filesystem.
Copilot 產生更新後的清單後,請它解釋每個設定:
Explain each field in the securityContext in plain language.
For each setting, describe what attack or misuse it prevents.
這種模式非常適合團隊學習。 用 Copilot 來產生,再用 Copilot 來解釋。
AKS 專屬的圖案
AKS 引入了標準 Kubernetes 清單無法涵蓋的 Azure 專屬概念。 Copilot 非常熟悉這些模式。
工作負載識別:
Add Azure Workload Identity annotations to the Deployment and ServiceAccount.
The workload should use a managed identity with client ID
"00000000-0000-0000-0000-000000000000".
Add the required azure.workload.identity/client-id annotation to the
ServiceAccount and the azure.workload.identity/use: "true" label to the pod spec.
Azure 磁碟持久性磁碟區:
Add a PersistentVolumeClaim for 10Gi using the managed-csi storage class
(Azure Disk). Mount it at /data in the container with ReadWriteOnce access mode.
Pod 中斷預算:
Add a PodDisruptionBudget for the Deployment that ensures at least 2 replicas
are always available during voluntary disruptions (node drains, upgrades).
檢視現有清單
將任何 Kubernetes 資訊清單貼入 Copilot Chat,並要求它進行檢閱:
Review this Kubernetes manifest for:
1. Security issues (missing security context, running as root, privileged containers)
2. Missing resource requests or limits
3. Missing health probes
4. Configurations that would cause problems in a production AKS cluster
5. Any deprecated API versions (e.g., apps/v1beta is deprecated)
For each issue, identify the line, explain the risk, and provide the corrected YAML.
這個審查提示對於累積清單、想要提升到最新標準,而不想手動審核每個檔案的團隊非常有用。
Helm Chart 支架
對於可重複使用的應用程式封裝,Copilot 可以建立 Helm Chart 結構的支架。 使用一個提示,指定圖表名稱、應包含的資源、參數化的值,以及任何 AKS 特定的需求,如入口類別或工作負載身份。 Copilot 會依預期的目錄結構產生 Chart.yaml、values.yaml 以及範本檔案。 請仔細檢查產生的 values.yaml,以確保敏感的預設值不會提交到原始碼版本控制中。