链接的 docker-compose 容器发出 http 请求 [英] Linked docker-compose containers making http requests
问题描述
我已经在网上找了一段时间,但没有找到解决我的问题的方法,这类似于 StackOverflow 问题 容器之间的 Docker HTTP 请求.但是这个答案已经是我在我的电脑上所做的.我正在提供我的 docker-compose 文件
I've been looking on the web for a while and haven't found a solution to my problem which is similar to this StackOverflow question Docker HTTP-requests between containers. But this answer is already what I'm doing in my computer. I'm providing my docker-compose file
version: "3"
services:
web:
image: ecdavis15/tsn-web-server
ports:
- "3000:3000"
links:
- app
app:
image: ecdavis15/tsn-app-server
ports:
- "3030:3030"
links:
- mongo
mongo:
image: mongo
ports:
- "27017:27017"
volumes:
- ./data/db:/data/db
在我的 Web 容器中,我向 http://app:3030/history
或者 http://app:3030/rules
发出了一个 http get 请求,但我没有看到请求找到了通往应用程序容器的路.我在浏览器控制台中看到的是此错误消息 net::ERR_NAME_NOT_RESOLVED
.我不确定为什么 http 请求没有进入应用程序容器,因为它已链接到 Web 容器.有什么想法吗?
In my web container I make an http get request to http://app:3030/history
or maybe http://app:3030/rules
but I'm not seeing the request find its way to the app container. What I'm seeing in the browser console is this error message net::ERR_NAME_NOT_RESOLVED
. I'm not sure why the http request isn't getting into the app container since it's linked to the web container. Any ideas?
推荐答案
由于您进行了 Ajax 调用,因此它将由客户端而非服务器端的浏览器发送.因此,当您从 <IP>:3000
调用 API 到 app:3030
时,您的浏览器不知道什么是应用程序.所以你能做的事情很少
Since you make an Ajax call it will be sent by the browser which is client side and not server side. So when you make a call from <IP>:3000
to app:3030
for API, your browser has no idea what app is. So you have few things you can do
/etc/hosts
<IP> app
然后当你使用app:3000
浏览应用时,app:3030
会自动指向正确的地址.
Then when you browse app using app:3000
, app:3030
will automatically point to the correct address.
您可以使用 javascript 来获取您应该用于 api 的 url
You can use javascript to get the url that you should be using for api
document.location.scheme + "://" + document.location.hostname + ":3030"
使用nginx
可以创建nginx反向代理
Using nginx
You can create nginx reverse proxy
location / {
proxy_pass http://localhost:3000;
location /api {
proxy_pass http://localhost:3030;
}
}
这将需要对您的代码文件进行一些更改,以便您使用 /api
This will require some change in your code file so that you use /api
这篇关于链接的 docker-compose 容器发出 http 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!