You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Docker环境下能否通过容器名称:端口实现跨容器API调用?

回答:Docker容器间能否通过「容器名称:端口」调用API?

Absolutely! You can definitely call another container's API using the 容器名称:端口 format in Docker, and in your specific Docker Compose setup, Service-a can successfully call Service-b via http://service_b:5000 (or even the Compose service name http://service-b:5000). Here's why this works:

1. 自定义网络的DNS解析支持

Both of your services are attached to the same custom network mynetwork (which is named aaa-network in practice). Docker provides a built-in DNS service for custom networks that automatically resolves:

  • Container names (like service_b in your config)
  • Compose service names (like service-b, the key under services in your YAML)

to the corresponding container's internal IP address. This means Service-a can resolve service_b directly without needing to know its actual IP.

2. 注意使用容器内部端口,而非主机映射端口

In your Compose config, Service-b has:

ports:
  - '5004:5000'

The 5004 is the port mapped to your host machine, but container-to-container communication uses the internal port 5000 (the port the service is actually listening on inside the container). So your API call should target http://service_b:5000, not http://service_b:5004.

3. 额外小提示:优先使用Compose服务名更灵活

While using the container name (service_b) works, using the Compose service name (service-b) is often better. If you ever restart the container, scale the service to multiple instances, or update your config without changing the service name, Docker's DNS will automatically route traffic to the correct container(s) — no need to update your API calls.


内容的提问来源于stack exchange,提问作者dinosaur

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 19:12:38