我们现在正在使用Angular 4建立一个SPA,在Azure上使用Docker托管它.通常,如果我们使用Angular-CLI构建命令,则使用Environment-Configs在Angular中设置环境(Prod,Development,Testing).这很棒,但Docker的工作流程有点不同:
这意味着我们有一个计时问题,因为在编译时,我们不能说,应用程序将在哪个环境中运行.对于服务器(.net核心),这没有问题,因为我们可以使用ASPNETCORE_ENVIRONMENT变量,但我们没有找到使App知道环境类型的解决方案.我几乎可以肯定我们并不是唯一一个遇到这个问题的人,但到目前为止我找不到合适的解决方案.是否有一些我们不知道的可能性?
由于我的主要目标是不为每个环境创建一个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)
该命令执行三件事:
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.
| 归档时间: |
|
| 查看次数: |
2822 次 |
| 最近记录: |