首先,我是Docker容器的新手,我对它们的运行方式了解不多,但是我有以下设置:
可通过https://localhost:44384/api/weatherforecast访问该API
可通过https://localhost:4200访问容器化的 Angular 应用程序
如果我在没有docker的情况下运行angular应用,则在使用代理解决了CORS问题之后,我可以连接到https://localhost:44384/api/weatherforecast。但是,当我运行dockerized版本时,出现以下错误:
Failed to load resource: the server responded with a status of 504 (Gateway Timeout)
在VS控制台中,我看到此错误:
clearance_1 | [HPM] Error occurred while trying to proxy request /api/weatherforecast from loccoalhost:4200 to https://localhost:44384 (ECONNREFUSED) (https://nodejs.org/api/errors.html#errors_common_system_errors)
这似乎是一个连通性问题,因此我在互联网上进行了一些研究,并尝试将这两个容器置于同一网络下。
步骤如下:
1.创建网桥“测试”网络
docker network create test
docker 网络连接测试[容器ID 1]
docker 网络连接测试[容器ID 2]
其他潜在有用的东西:
docker-compose.yml:
version: "3.7"
services:
clearance:
build:
# network: host
context: .
dockerfile: DockerFileLocal
ports:
- 4200:4200
volumes:
- /app/node_modules
- .:/app
proxy.conf.json
{
"/api/*": {
"target": "https://localhost:44384",
"secure": false,
"logLevel": "debug",
"changeOrigin": true
}
}
我想念什么?
最佳答案
我在Angt_strong和单独的Docker容器中运行的 Angular 应用程序和API遇到了类似的问题。
通过以下设置,两个应用程序均可正常运行:
在http://localhost:4200上运行的Angular
在http://localhost:8080上运行的API
问题
Angular应用无法访问API。
以下代码始终为我提供与网络相关的错误。
this.http.get('http://localhost:8080').subscribe(console.log);
解
Links
Link to containers in another service. Either specify both the service name and a link alias (SERVICE:ALIAS), or just the service name. Containers for the linked service are reachable at a hostname identical to the alias, or the service name if no alias was specified.
当一个容器需要通过网络到达另一个容器时,我们需要创建一个链接。
我最终在
api
的angular
服务定义中创建了指向docker-compose.yml
服务的链接version: "2"
services:
api:
build:
context: .
dockerfile: ./api/Dockerfile
volumes:
- ./api:/usr/src/app
ports:
- "8080:8080"
angular:
build:
context: .
dockerfile: ./angular/Dockerfile
volumes:
- ./angular:/usr/src/app
ports:
- "4200:4200"
links:
- api
然后,我通过在Angular应用程序中将
localhost
替换为api
来解决网络错误。this.http.get('http://api:8080').subscribe(console.log);
您不需要代理。但是,您可能需要调整配置以使其起作用。
关于angular - 无法在本地主机上的Docker容器之间进行通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60649639/