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

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

问题描述

我有一个完全在MacBook本地运行的Webapp。

I have a Webapp running completely locally on my MacBook.

该Webapp有一个前端(Angular / Javascript)和一个后端(Python / Django),它们实现了RESTful API。

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.

现在我需要对前端进行Docker化。但是,如果我在本地主机上运行了这两个docker容器,如何获取FE将HTTP请求发送到BE? 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

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.

话虽如此,我想您的前端是只提供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天全站免登陆