如何让 Docker 容器在本地主机上运行时相互通信? [英] How to get Docker containers to talk to each other while running on my local host?

查看:79
本文介绍了如何让 Docker 容器在本地主机上运行时相互通信?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 MacBook 上有一个完全在本地运行的 Web 应用程序.

I have a Webapp running completely locally on my MacBook.

Web 应用程序有一个前端(Angular/Javascript)和一个实现 RESTful API 的后端(Python/Django).

The Webapp has a Front End (Angular/Javascript) and a Back End (Python/Django) which implements a RESTful API.

我对后端进行了 Docker 化,使其完全独立于 Docker 容器中并公开端口 8000.我将此端口本地映射到 4026.

I have Dockerized the Back End so that it is completely self-contained in a Docker Container and exposes port 8000. I map this port locally to 4026.

现在我需要 Dockerize 前端.但是如果我的本地主机上运行着这两个 docker 容器,我怎样才能让 FE 向 BE 发送 HTTP 请求呢?FE 容器不会知道任何存在于它之外的东西.对吗?

Now I need to Dockerize the Front End. But if I have these two docker containers running on my localhost, how can I get the FE to send HTTP requests to the BE? The FE container won't know anything that exists outside of it. Right?

这就是我运行 FE 的方式:

This is how I run the FE:

$ http-server
Starting up http-server, serving ./
Available on:
  http://127.0.0.1:8080
  http://192.168.1.16:8080
Hit CTRL-C to stop the server

请提供参考资料,解释我如何实现这一目标.

Please provide references explaining how I can achieve this.

推荐答案

今天的做法是Docker Networking,另一个答案简要提到.

The way to do this is today Docker Networking, which another answer briefly mentioned.

简短的版本是您可以运行 docker network ls 来获取您的网络列表.默认情况下,您应该有一个名为 bridge 的.您可以创建一个新容器,也可以通过在创建容器时传递 --net=bridge 来使用它.从那里,在同一网络上启动的容器可以通过暴露的端口相互通信.

The short version is that you can run docker network ls to get a listing of your networks. By default, you should have one called bridge. You can either create a new one or use this one by passing --net=bridge when creating your container. From there, containers launched with the same network can communicate with each other over exposed ports.

如果您使用 Docker Compose 如前所述,它将为您创建桥接网络您运行 docker-compose up 并使用与项目文件夹匹配的名称并附加 _default .Compose 文件中定义的每个图像都会自动在该网络中启动.

If you use Docker Compose as has been mentioned, it will create a bridge network for you when you run docker-compose up with a name matching the folder of your project and _default appended. Each image defined in the Compose file will get launched in this network automatically.

综上所述,我猜您的前端是一个 Web 服务器,它只提供 HTML/JS/CSS,而这些页面访问后端服务.如果这是准确的,那么在这种情况下,您实际上并不需要容器到容器的通信……两者都需要暴露给主机,因为连接源自客户端系统.

With all that said, I'm guessing your frontend is a webserver that just serves up the HTML/JS/CSS and those pages access the backend service. If that's accurate, you don't really need container-to-container communication in this case anyway... both need to be exposed to the host since connections originate from the client system.

这篇关于如何让 Docker 容器在本地主机上运行时相互通信?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆