Rag*_*hav 6 environment-variables docker-compose angular angularbuild
我有一个 Angular 应用程序,我试图从应用程序外部(即从 docker compose 文件)设置环境变量。
我指的是下面的文章
https://codinglatte.com/posts/angular/using-os-environment-variables-in-angular-with-docker/
docker-compose.yml
version: '3'
services:
tomcat-server:
image: "tomcat:latest"
ports:
- "8071:8080"
environment:
- API_URL=http://demo-production.com
Run Code Online (Sandbox Code Playgroud)
当我执行以下命令时,我什至可以看到环境变量设置
docker exec -it <dockerName> sh
env
Run Code Online (Sandbox Code Playgroud)
但不知何故,Angular 应用程序没有收到该值,下面是我的 Angular 应用程序代码,按照上面的文章
环境.产品.ts
export const environment = {
production: true,
API_URL: $ENV.API_URL,
TEST_ENV: 'testing'
// API_URL: 'http://production.com'
};
Run Code Online (Sandbox Code Playgroud)
打字.d.ts
declare var $ENV: Env;
interface Env {
API_URL: string
}
Run Code Online (Sandbox Code Playgroud)
自定义-webpack.config.js
const webpack = require('webpack');
module.exports = {
plugins: [
new webpack.DefinePlugin({
$ENV: {
API_URL: JSON.stringify(process.env.API_URL)
}
})
]
};
Run Code Online (Sandbox Code Playgroud)
我用来创建构建的命令
ng build --configuration=production --base-href=/demoapp/
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚这里的问题,因为 docker 文件中设置的环境值没有反映在我的应用程序中。
我可以在这里得到一些帮助吗?
问题是您混淆了构建时间和运行时间。您需要的是在构建时传递的变量。您可以在构建命令中传递它们:
docker build -t my_image --build-arg API_URL=http://demo-production.com .
Run Code Online (Sandbox Code Playgroud)
最后.
给出context
,在本例中为当前目录。它将期望找到一个名为Dockerfile
此处的 dockerfile。在您发布的链接中,您可以在底部找到一个 dockerfile,在那里您还可以看到按预期定义的环境变量。在该文件中,他们首先使用节点映像使用环境变量构建应用程序,然后在部署阶段将输出复制到 nginx 容器内的正确位置。
您在 docker-compose 文件中指定一个 tomcat 容器。该容器不会构建任何东西。即使您正确地传递了参数,它也无法知道如何处理它。
你可能应该做的是:
docker run --name my-container-name -p "8071:8080" my-image
Run Code Online (Sandbox Code Playgroud)
这是假设在 dockerfile 的第二阶段您使用 tomcat,它使用您正在映射的端口 8080。如果你想使用 docker compose,它可能看起来像:
version: '3'
services:
tomcat-server:
build:
context: .
args:
API_URL=http://demo-production.com
ports:
- "8071:8080"
Run Code Online (Sandbox Code Playgroud)
然后,这将为您调用 docker build 和 run 命令,因此您显然仍然需要 dockerfile。
如果您有兴趣在运行时将环境变量传递给 Angular,那是另一回事。如果您愿意,您可以在我写的博客中阅读相关内容。
归档时间: |
|
查看次数: |
16657 次 |
最近记录: |