我是 docker 容器的新手,我遇到了以下问题。我正在开发一个向公开的 api 发出请求的网页。它们都发布在通过网络链接的不同容器上。 这是我的 docker-compose.yml 文件:
version: '2'
services:
api:
image: my/api
networks:
- api
ports:
- "8080:5000"
container_name: api
web:
build:
context: ./DockerWeb
networks:
- api
ports:
- "80:5000"
container_name: web
networks:
api:
driver: bridge
我注意到,如果我附加到运行我的网页的容器,我可以使用 ping api
当尝试对 api 容器进行任何网络服务调用时,问题就出现了。我正在尝试初始化一个 HttpClient 对象,但是必须将此类对象的 BaseAddress 属性设置为有效的 Uri。
_client = new HttpClient();
_client.BaseAddress = new Uri(config.ApiUrl); //config.ApiUrl = "api"
这会引发以下错误
UriFormatException: Invalid URI: The format of the URI could not be determined.
有没有办法 a) 以不同的方式公开容器名称,或者 b) 在不需要使用 URI 的情况下调用 Web 服务? 我怎样才能做到这一点?
更新
我已经更新了 ApiUrl 以包含值 http:api:8080
,但是现在我在执行调用时遇到异常
System.AggregateException: One or more errors occurred. (An error occurred while sending the request.) ---> System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.Http.CurlException: Couldn't connect to server
我还尝试使用 wget 直接从我的 Web 容器调用 api 端点
wget http://api:8080/
但是我仍然收到一个错误:
Connecting to api (api)|172.24.0.4|:8080... failed: Connection refused
这可能是 API 配置错误吗?
最佳答案
api
只是主机名。 URI 将为 http://api:8080
(如果您设置了 SSL/TLS,则为 https://api:someotherport
。)
关于c# - 网络 docker 容器上的 HttpClient 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42915782/