Angular和Docker:环境感知配置

Mat*_*ler 14 docker angular

我们现在正在使用Angular 4建立一个SPA,在Azure上使用Docker托管它.通常,如果我们使用Angular-CLI构建命令,则使用Environment-Configs在Angular中设置环境(Prod,Development,Testing).这很棒,但Docker的工作流程有点不同:

  1. 构建Angular应用程序
  2. 初始化Docker容器
  3. 设置Docker Container环境变量
  4. 启动Docker容器

这意味着我们有一个计时问题,因为在编译时,我们不能说,应用程序将在哪个环境中运行.对于服务器(.net核心),这没有问题,因为我们可以使用ASPNETCORE_ENVIRONMENT变量,但我们没有找到使App知道环境类型的解决方案.我几乎可以肯定我们并不是唯一一个遇到这个问题的人,但到目前为止我找不到合适的解决方案.是否有一些我们不知道的可能性?

Mat*_*ler 7

由于我的主要目标是不为每个环境创建一个Container,而是使整个构建过程与环境无关,因此我提出了以下解决方案:我正在使用docker-stack文件添加命令(我的Docker映像为NGinx ):

command: /bin/bash -c "cp /usr/share/nginx/html/assets/app-settings/appsettings.__EnvironmentName__.json /usr/share/nginx/html/assets/app-settings/appsettings.json && find "/usr/share/nginx/html/assets/app-settings/" -type f -name "*.json" -not -name "appsettings.json" -exec rm {} ';' && exec nginx -g 'daemon off;'"
Run Code Online (Sandbox Code Playgroud)

该命令执行三件事:

  1. 将特定于环境的appsettings.json(如下所示)复制为appsettings.json
  2. Remove all appsettings.xxx.json except appsettings.json
  3. Start nginx

The release process also replaces EnvironmentName with the specific environment it is deploying to. This means, each container has now an appsettings.json in place with the environment-specific data. On the angular code, I'm using the environment-files just for compile-time, environment-agnostic, information:

export const environment = { production: false };

The appsettings are saved as assets:

在此处输入图片说明

To read the runtime information of appsettings.json, I've created a appsettings provider service, using a local http call:

@Injectable()
export class AppSettingsProviderService {
  private appSettings: AppSettings;

  public constructor(private http: LocalHttpService) {
  }

  public async provideAppSettingsAsync(): Promise<AppSettings> {
    if (this.appSettings) {
      return Promise.resolve(this.appSettings);
    }

    // This path needs to be relative to the files in the dist-folder
    this.appSettings = await this.http.getAsync<AppSettings>('./assets/app-settings/appsettings.json');
    return this.appSettings;
  }
}
Run Code Online (Sandbox Code Playgroud)

This works also during development, since just the appsettings.json is used in this case and even with ng serve, the code is compiled into dist, meaning the relative path is still correct.

  • 总体而言,感谢您的Matthias!我真的只是在这里简化了您的解决方案,只是更改了docker-compose文件以将所需的配置复制到appconfig.production.json文件上。例如-&gt;命令:sh -c“ cp /usr/share/nginx/html/assets/appconfig.staging.json /usr/share/nginx/html/assets/appconfig.production.json &amp;&amp; exec nginx -g' daemon off;'“,因为我们在每个文件中都有每个不同的配置。这样就完美了! (2认同)

归档时间:

查看次数:

2822 次

最近记录:

7 年,5 月 前