解鎖環境變量在雲原生應用中各種姿勢

應用程序在某些時刻總是需要一些外掛配置,雲原生應用的實踐是在容器化之前就將應用程序配置保留在代碼之外。

12-Factors App:Store config in the environment

① 外掛配置文件:業務配置 appsettings.json

可以在代碼中要求加載appsetting.serect.json配置文件,但是不加入代碼版本管理==》敏感信息分離。

② 環境變量:

  • 單條業務配置(API_URL_PREFIX)
  • 框架配置(ASPNETCORE_ENVIRONMENT=Production)
  • 部署配置(Tag=v1.2)
  • 敏感信息(AppId,AppAuthIssuer,AppSerect)

環境變量

現代操作系統均支持存儲key-value環境變量,所有程序都能從OS獲取特定環境變量。

ASP.NET Core默認腳手架:環境變量配置在第4位置插入

IConfiguration會拷貝環境變量鍵值對,後續同名配置會覆蓋之前同名配置值,但是環境變量本身不會變化。
public static string? GetEnvironmentVariable(string variable);

環境變量來自三個級別:進程、用戶、系統

 // Specifies the location where an environment variable is stored or retrieved in  a set or get operation
    public enum EnvironmentVariableTarget
    {
        Process = 0,
        User = 1,
        Machine = 2
    }

介紹幾種創建環境變量的方式:

  1. windows:在CMD/Powershell setx命令設置永久環境變量;
    linux:使用export命令設置會話級別環境變量,修改bash_profile文件設置系統級別環境變量

windows電腦還可以在-[我的電腦]-[高級設置]-[環境變量]操作

  1. 在Visual Studio IDE launchsettings.json 設置進程級別環境變量
{
  "profiles": {
    "Gridsum.EAP.Web": {
      "commandName": "Project",
      "launchBrowser": false,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "production"
        "IsAuthEnabled": "true",
      },
      "applicationUrl": "https://localhost:5002;http://localhost:5001/"
    }
  }
}

Visual Studio Code 設置環境變量

{
   "version": "0.1.0",
   "configurations": [
        {
            "name": ".NET Core Launch (web)",
            "type": "coreclr",
            "env": {
                "ASPNETCORE_ENVIRONMENT": "Development"
            }
        }
    ]
}
  1. 若使用IIS託管 ASP.NET CORE,可在IIS[配置編輯器]新增、重寫環境變量

IIS配置會落地到web.config 文件

Docker 環境變量

Docker-Compose有多重方式爲容器設置環境變量,按照優先級如下:

  1. environment配置節寫入
  2. 通過shell傳入環境變量
  3. env_file配置節加載環境變量文件

① 文件中的環境變量並不會自動應用到容器,需要在Compose yml文件中以${}引用
docker-compose命令默認從命令執行的同一目錄尋找.env文件

  1. 在Dockerfile內置環境變量
    ASP.NETCore3.1 Runtime鏡像作爲基礎鏡像的應用, 會發現應用使用Production配置80端口提供服務。

基礎鏡像Dockerfile內置:
ENV ASPNETCORE_ENVIRONMENT=Production
ENV ASPNETCORE_URLS=http://+:80
ENV DOTNET_RUNNING_IN_CONTAINER=true

高優先級會覆蓋低優先級環境變量值。

下面的例子:shell傳遞的環境變量值覆蓋了.env文件同名環境變量。

$ cat .env
TAG=v1.5

$ cat docker-compose.yml
version: '3'
services:
  web:
    image: "webapp:${TAG}"
# 啓動容器,web服務使用 webapp:v1.5的鏡像
$ docker-compose config

version: '3'
services:
  web:
    image: 'webapp:v1.5'
$ export TAG=v2.0
$ docker-compose config

version: '3'
services:
  web:
    image: 'webapp:v2.0'

Kubernetes 環境變量

你可以爲運行在Pod中的容器設置環境變量,利用envenvFrom配置節。

  1. env配置節
apiVersion: v1
kind: Pod
metadata:
  name: envar-demo
  labels:
    purpose: demonstrate-envars
spec:
  containers:
  - name: envar-demo-container
    image: anjia0532/google-samples.node-hello:1.0
    env:
    - name: DEMO_GREETING
      value: "Hello from the environment"
    - name: DEMO_FAREWELL
      value: "Such a sweet sorrow"

進入Pod, 打印環境變量(kubectl exec envar-demo -- printenv):

NODE_VERSION=4.4.2
EXAMPLE_SERVICE_PORT_8080_TCP_ADDR=10.3.245.237
HOSTNAME=envar-demo
...
DEMO_GREETING=Hello from the environment
DEMO_FAREWELL=Such a sweet sorrow

  1. envFrom配置節
    先創建configmap(作爲配置來源)
apiVersion: v1
kind: ConfigMap
metadata:
  name: special-config
  namespace: default
data:
  SPECIAL_LEVEL: very
  SPECIAL_TYPE: charm

kubectl create -f configmap-multikeys.yaml

apiVersion: v1
kind: Pod
metadata:
  name: dapi-test-pod
spec:
  containers:
    - name: test-container
      image: anjia0532/busybox
      command: [ "/bin/sh", "-c", "env" ]
      envFrom:
      - configMapRef:
          name: special-config
  restartPolicy: Never

kubectl create -f pod-configmap-envFrom.yaml

現在Pod的輸出環境變量SPECIAL_LEVEL=very and SPECIAL_TYPE=charm

使用env,envFrom配置節設置的環境變量會覆蓋鏡像內環境變量。

🐂👃


環境變量的變更,需要重啓應用。
環境變量在小範圍內使用很方便,當您具有更復雜的配置方案時,應該選擇其他數據注入方式,例如外掛文件。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章