本文介绍了在特定于Docker容器环境中配置Angular 2 Webpack App的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们想使用 Docker镜像在不同的环境(阶段/测试,生产等)中部署 Angular 2 应用

We want to deploy our Angular 2 app using Docker images in different environments (staging/test, production, ...)

在本地开发时,我们通过 http://localhost:8080 连接到后端REST API,但是当我们在我们想要使用相同Docker映像并连接到不同的REST API端点的不同环境.

When developing locally we are connecting to the backend REST API via http://localhost:8080 but when we deploy in the different environments we want to use the same Docker image and connect to a different REST API endpoint.

在运行时配置注入 Docker容器的首选方式是什么?

What would be the preferred way to inject this configuration into the Docker container at runtime?

是否可以通过环境变量来做到这一点?

Is there a way to do this via environment variables?

我们可以通过包含以下内容的纯文本文件来做到这一点吗?

Can we do this via a plain text file containing something like

{
    "BASE_URL": "https://api.test.example.com"
}

推荐答案

在本文和Twitter上进行了一些讨论之后,似乎没有简单的方法可以通过Webpack实现我想要的东西.这些文件仅在运行时用作静态文件,并且无法在构建时排除文件并在运行时将其包括在内.

After having some discussions in this post and on twitter it looks like there is no easy way to achieve what I want via Webpack. The files are only served as static files at runtime and it is not possible to exclude a file at build time and include it at runtime.

因此,我决定采用我想到的解决方案/变通办法:在启动Docker容器时更改静态文件.

So I decided to go with the solution/workaround I had in mind: changing the static files when starting up the docker container.

我通过这样做来创建我的docker映像

I create my docker image by doing

npm run build:prod
docker build -t angularapp .

我正在使用官方的nginx docker映像作为我的基本映像,并且Dockerfile看起来像

I am using the official nginx docker image as my base image and the Dockerfile looks like

FROM nginx:1.11.1

COPY dist /usr/share/nginx/html
COPY run.sh /run.sh

CMD ["bash", "/run.sh"]

run.sh用于通过sed修改配置文件并随后启动nginx:

The run.sh is used to modify the config file via sed and to start nginx afterwards:

#!/bin/sh

/bin/sed -i "s|http://localhost:8080|${BASE_URL}|" /usr/share/nginx/html/api.config.chunk.js

nginx -g 'daemon off;'

这允许我通过环境variabel在我的docker-compose.yml文件中(简化)配置BASE_URL:

This allows me to configure the BASE_URL via environment variabel in my docker-compose.yml file (simplified):

version: '2'

services:
  api:
    image: restapi
  frontend:
    image: angularapp
    environment:
      BASE_URL: https://api.test.example.com

通过此解决方案/解决方法,我可以通过配置启动docker容器时通过环境变量使用的REST API端点,来将我的jenkins作业创建的docker映像部署到我所有环境(开发,登台,生产)中部署的特定版本.

With this solution/workaround I can deploy the docker image created by my jenkins job for a specific version deploy in all my environments (development, staging, production) by configuring the REST API endpoint used via environment variable when starting the docker container.

这篇关于在特定于Docker容器环境中配置Angular 2 Webpack App的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 06:55