Docker compose 端口映射,主机端口 != 容器端口

标签 docker docker-compose docker-networking

我该如何制作 curl http://barfoo:8002从 foobar-container 工作,而不更改 docker 文件?

我有以下撰写文件:

version: '3'
services:
  foobar:
    build:
      context: ./foobar
    ports:
      - 8001:80
    depends_on:
      - barfoo
  barfoo:
    build:
      context: ./barfoo
    ports:
      - 8002:80

我将以下内容添加到我计算机上的主机文件中
127.0.0.1     foobar
127.0.0.1     barfoo

现在我用 docker-compose up 开始这个项目.

当我在终端上执行以下操作时,这在逻辑上可以正常工作:curl http://barfoo:8002
当我从 foobar 容器( docker-compose exec foobar /bin/bash )中的 Bash 执行相同操作时,我得到 Failed to connect to barfoo port 8002: Connection refused , 如果我使用 curl http://barfoo:80有用。

原因是我想模拟类似生产的情况,在生产中不需要端口,因为它们使用不同的主机名,并且都可以直接使用端口 80

最佳答案

How can I make curl http://barfoo:8002 work from the foobar-container, without making changes to the docker file?



简单的解决方案是将主机端口 8002 映射到 barfoo端口 8002。但这可能不是您想要的。
barfoo是在内部 docker dns 中注册的服务名称,只能由运行时创建的同一 docker 网络中的服务( foobar )访问 docker-compose up
8002 是映射到 docker 主机的端口。

所以当你运行 curl http://barfoo:8002来自 foobar您尝试连接到服务的容器 barfoo到端口 8002。但是 barfoo监听容器内的端口 80 而不是 8002。

另一种解决方案:

您可以添加 network_mode: hostbarfoofoobar .
  foobar:
    build:
      context: ./foobar
    network_mode: host
    ports:
      - 8001:80
    depends_on:
      - barfoo
  barfoo:
    build:
      context: ./barfoo
    network_mode: host
    ports:
      - 8002:80

但随后 foobar需要使用 localhost:8002 连接

The reason why is that I want to simulate a production like situation, where in production there is no port needed since they use a different hostname and both can use port 80 directly



如果这确实是您想要的,更好的选择是使用 docker stack。

您的服务将是 docker swarm服务:

您可以使用以下方法部署它们:
docker deploy --compose-file path_to_compose_file
然后foobar将连接到 barfoo使用服务名称和端口 barfoo:80

关于Docker compose 端口映射,主机端口 != 容器端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58692640/

相关文章:

php - 如何使用 Docker 连接 php-apache 和 MySQL?

ruby-on-rails - 构建期间 dockerized rails 应用程序中的私有(private) Github 存储库

docker - Pa11y的最佳Docker实例

mongodb - 更改Mongo-Express的8081端口

windows - 如何在 docker-compose.yml 中包含 Docker 主机的 IP?

docker - 使用 docker 将 mule 应用程序部署到 mule 集群

用于引用 bitnami 图像的容器 docker-compose.yml 的 azure webapp

node.js - 从另一个 Docker 容器运行 Zalenium 的 Selenium 命令

通过主机名发现 Docker 容器不起作用

python - Windows 客户端无法与在 linux docker 容器中运行的服务器通信