简体   繁体   English

将来自docker-compose的env变量注入Angular4 app

[英]Inject env variables from docker-compose into Angular4 app

I build a simple Angular4 app which get its data from a REST-API. 我构建了一个简单的Angular4应用程序,它从REST-API获取数据。

I deploy the app with docker-compose but before I need to set the URL/Hostname to the API manually in my service module. 我使用docker-compose部署应用程序,但之前我需要在服务模块中手动设置API /主机名。 During the dev I simply used 'localhost' and it does the job. 在开发期间,我只使用'localhost'并完成工作。

In the API I'am able inject the correct hostname via docker-compose (section environment ) since it runs on the server but this is not possible for angular. 在API中,我能够通过docker-compose(节环境 )注入正确的主机名,因为它在服务器上运行,但这对于角度来说是不可能的。

Are there any best practices / guides for injecting the hostname / URL into a angular-cli app from docker-compose? 是否有任何最佳实践/指南将主机名/ URL注入docker-compose的angular-cli应用程序?

One way to achieve this is to extract all configuration into a separate angular service that is responsible of serving configuration. 实现此目的的一种方法是将所有配置提取到负责服务配置的单独角度服务中。 Inside this new service hardcode these values to env placeholders. 在这个新服务中,将这些值硬编码到env占位符。 For example: 例如:

apiUrl = $API_URL

Now change the CMD inside your DockerFile to run a script startup.sh . 现在更改DockerFile中的CMD以运行脚本startup.sh

Create this script and add it into the Docker Image using ADD startup.sh startup.sh . 创建此脚本并使用ADD startup.sh startup.sh将其添加到Docker镜像中。

Inside startup.sh you can envoke envsubst < "path-to-service-file" > "path-to-service-file" to substitute the placeholder with the env variable value. 在startup.sh中,您可以使用envsubst < "path-to-service-file" > "path-to-service-file"来替换占位符和env变量值。 After envsubst command start your angular application 在envsubst命令启动你的角度应用程序之后

Thank you yamenK for you solution with the bash script and Tarun for a similar solution. 感谢yamenK为您解决bash脚本和Tarun的类似解决方案。

I found another way to avoid the need of the information about the Api Url in the angular app. 我找到了另一种方法来避免在角度应用程序中需要有关Api Url的信息。 I added an nginx web server to my docker-compose and link it to my api and the app. 我在我的docker-compose中添加了一个nginx web服务器,并将其链接到我的api和app。

nginx:
build: ./nginx
...
links:
  - app
  - api

In the nginx default.conf I use multiple locations to route the requests. 在nginx default.conf中,我使用多个位置来路由请求。

location /api {
proxy_pass http://api:6000/api;
....
}
location / {
proxy_pass http://angular:4200/;
...
}

Then in the angular app I use relative urls. 然后在角应用程序中我使用相对网址。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM