如何在 Service Fabric 中指定服務的環境變數

本文會示範如何在 Service Fabric 中指定服務或容器的環境變數。

指定服務環境變數的程序

在此範例中,您可以設定容器的環境變數。 本文假設您已有應用程式和服務資訊清單。

  1. 開啟 ServiceManifest.xml 檔案。

  2. CodePackage 元素中,為每個環境變數新增新的 EnvironmentVariables 元素和 EnvironmentVariable 元素。

    <CodePackage Name="MyCode" Version="CodeVersion1">
            ...
            <EnvironmentVariables>
                  <EnvironmentVariable Name="MyEnvVariable" Value="DefaultValue"/>
                  <EnvironmentVariable Name="HttpGatewayPort" Value="19080"/>
            </EnvironmentVariables>
    </CodePackage>
    

    在應用程式資訊清單中可以覆寫環境變數。

  3. 若要在應用程式資訊清單中覆寫環境變數,請使用 EnvironmentOverrides 元素。

      <ServiceManifestImport>
        <ServiceManifestRef ServiceManifestName="Guest1Pkg" ServiceManifestVersion="1.0.0" />
        <EnvironmentOverrides CodePackageRef="MyCode">
          <EnvironmentVariable Name="MyEnvVariable" Value="OverrideValue"/>
        </EnvironmentOverrides>
      </ServiceManifestImport>
    

使用 Docker Compose 動態指定環境變數

Service Fabric 支援使用 Docker Compose 進行部署。 撰寫檔案可以 shell 的環境變數為來源。 此行為可用於動態取代所需的環境值:

environment:
  - "hostname:${hostname}"

下一步

若要深入了解這篇文章所討論的某些核心概念,請參閱管理多個環境發行項的應用程式

如需 Visual Studio 中其他可用的應用程式管理功能的相關資訊,請參閱 在 Visual Studio 中管理 Service Fabric 應用程式