Skip to content

42 kubernetes环境下.netcore mvc的部署方式.md

Jinxin Chen edited this page Dec 11, 2019 · 1 revision

本文介绍如何在kubernetes环境下部署 .netcore mvc app

之前有写过一篇文章asp.net core mvc集成CI-CD时,update-database的时机选择,基于docker环境。

当部署到kubernetes集群环境下时,需要做一些调整,思路如下:

  1. 在部署app之前,单独部署job来执行更新数据库的动作
  2. 等待数据库更新完成
  3. 部署app

部署更新数据库job

调整代码

调整代码,根据环境变量来判断是否是更新数据库的job:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime appLifetime,
            Context dbContext)
        {
            if (System.Environment.GetEnvironmentVariable("UPDATE_DB") == "true")
            {
                dbContext.Database.Migrate();
                appLifetime.StopApplication();
            }

创建job yaml档案

apiVersion: batch/v1
kind: Job
metadata:
  name: app-updatedb
spec:
  template:
    spec:
      containers:
      - name: app-updatedb
        image: app:latest
        env:
        - name: ASPNETCORE_ENVIRONMENT
          valueFrom:
            configMapKeyRef:
              name: app
              key: ASPNETCORE_ENVIRONMENT
        - name: UPDATE_DB
          value: "true"
      restartPolicy: Never
  backoffLimit: 1

通过config map来获取当前运行环境:

apiVersion: v1
kind: ConfigMap
data:
  ASPNETCORE_ENVIRONMENT: Stage
metadata:
  name: app

部署脚本

在部署脚本中插入更新数据库部分

echo "update database"
if [ -n "`kubectl get pods --selector=job-name=app-updatedb`" ]; then
    kubectl delete -f ./k8s/k8s-app-update-db.yaml --namespace=default
fi
kubectl create -f ./k8s/k8s-app-update-db.yaml --namespace=default

for i in {1..20}
do
    echo "wait database update result $i"
    if [ "Succeeded" != "`kubectl get pods --selector=job-name=app-updatedb --output=jsonpath={.items..status.phase}`" ]; then
        sleep 1s
    else
        echo "deploy services"
        kubectl patch -f ./k8s/k8s-app.yaml --namespace=default -p "{\"spec\":{\"template\":{\"metadata\":{\"labels\":{\"date\":\"`date +'%s'`\"}}}}}"
        break;
    fi
done
Clone this wiki locally