docker - Docker:为什么我的Rest API和Web APP无法通信?

标签 docker networking containers

两个应用程序都在Docker容器上运行
收到此错误后,我决定进行调查:

App listening at http://localhost:3000
(node:1) UnhandledPromiseRejectionWarning: FetchError: request to http://localhost:5000/auth failed, reason: connect ECONNREFUSED 127.0.0.1:5000
    at ClientRequest.<anonymous> (/app/node_modules/node-fetch/lib/index.js:1461:11)
    at ClientRequest.emit (events.js:314:20)
    at Socket.socketErrorListener (_http_client.js:428:9)
    at Socket.emit (events.js:314:20)
    at emitErrorNT (internal/streams/destroy.js:92:8)
    at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
    at processTicksAndRejections (internal/process/task_queues.js:84:21)
(node:1) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:1) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
运行docker inspect app1||app2(虚拟命令),两个容器都不在同一网桥中。我试图在docker run中创建添加网络参数...
docker run -d -p 3000:3000 --network=bridge --name app1 nodejs
docker run -d -p 5000:5000 --network=bridge --name app2 python
我也尝试--link:
docker run -d -p 3000:3000 --link=app2 --name app1 nodejs 
但是他们都不起作用。有没有办法在我的应用程序之间创建此网络?我要去哪里错了?

最佳答案

这里有两个问题。
首先,不要使用--link。它仅适用于默认的网桥网络,它非常脆弱,不建议使用。
第二,localhost引用“此容器”。由于您的应用程序在两个不同的容器中运行,因此您将无法通过localhost获得服务。
您要做的是首先创建一个新的用户定义网络:

docker network create mynetwork
在该网络中启动容器:
docker run -d -p 3000:3000 --network=mynetwork --name app1 nodejs
docker run -d -p 5000:5000 --network=mynetwork --name app2 python
通过这两个更改,您的容器可以按名称相互引用:在容器app1内,您可以连接到http://app2:5000,而在容器app2中,您可以连接到http://app1:3000(好吧,假设两者都在提供http服务)。

您真正想做的是开始使用docker-compose而不是手动完成所有操作。 Docker-compose将自动为您设置一个用户定义的网络,从而使您不必键入冗长的docker run命令行。

关于docker - Docker:为什么我的Rest API和Web APP无法通信?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64344150/

相关文章:

docker - Docker DNS错误

windows - 带符号链接(symbolic link)的 Git init

windows - WinSock 最佳 accept() 实践

css - 响应式设计中的容器/图像定位

docker - Docker挂载点是如何决定的?

java - 如何在 docker 卷中保存 java.util.logging 输出

php - 使用 Docker 容器中的 PHP sendmail 通过主机 Postfix 发送

c++ - 是否有将主​​机字节顺序转换为网络字节顺序的 std::streambuf 版本?

c++ - 获取远程主机IP地址QTcpServer

html - 如何将内容保留在容器内具有 2 种背景颜色的 2 列布局中?