Docker容器之间不使用fastapi和windows上的请求模块进行通信



我有两个应用程序-app1和app2。当我使用fast API调用app1时,它通过fast API调用app2,并将响应从app2返回到app1。然后app1返回它从app2得到的响应。没有docker,两个应用程序都可以正常工作。当我使用docker compose将两个应用程序容器化时,它们无法通信,但都在运行。但我可以使用它们的API访问这两个容器。我也试过关闭我的防火墙,但仍然无法工作。我在windows 10上使用docker桌面。有人能告诉我/给我修一下吗?尝试不同的修复方法让我筋疲力尽。提前谢谢。

以下是我的代码:

<blockquote\>App1:

#App1
from fastapi import FastAPI, UploadFile,File, Form
from fastapi.responses import FileResponse
import requests
import uvicorn
app = FastAPI()

@app.get("/")
def read_root():

response = requests.get('http://localhost:81/')
#f = urllib.request.urlopen('http://localhost:81/')
return {"response from app2":response.text}

App1 Dockerfile:

FROM python:3.7
WORKDIR /testset
COPY main.py .
COPY . .
RUN pip install fastapi uvicorn requests

App2:

#App2 
from fastapi import FastAPI, File, UploadFile, HTTPException
import uvicorn
app = FastAPI()
@app.get('/')
def prediction_route():
f=2*5

return f

App2 Dockerfile:

FROM python:3.7
WORKDIR /var/www/html
COPY main.py .
COPY . .
RUN pip install fastapi uvicorn requests 

docker-compose.yml

version: '3'
services:
app1:
container_name: App1_tx
build: ./app1/
restart: always
volumes:
- .:/testset
ports:
- "80:80"
command: uvicorn app1.main:app --reload --host 0.0.0.0 --port 80
depends_on:
- app2

app2:
container_name: App2_rx
build: ./app2/
restart: always
volumes:
- .:/var/www/html
ports:
- "81:81"
command: uvicorn app2.main:app --reload --host 0.0.0.0 --port 81

我得到的错误响应:

INFO:     Will watch for changes in these directories: ['/testset']
INFO:     172.18.0.1:39980 - "GET / HTTP/1.1" 500 Internal Server Error
INFO:     172.18.0.1:39976 - "GET /favicon.ico HTTP/1.1" 404 Not Found
INFO:     Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit)
INFO:     Started reloader process [1] using statreload
INFO:     Started server process [8]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
ERROR:    Exception in ASGI application
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/urllib3/connection.py", line 175, in _new_conn
(self._dns_host, self.port), self.timeout, **extra_kw
File "/usr/local/lib/python3.7/site-packages/urllib3/util/connection.py", line 96, in create_connection
raise err
File "/usr/local/lib/python3.7/site-packages/urllib3/util/connection.py", line 86, in create_connection
sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused

During handling of the above exception, another exception occurred:

使用docker-compose服务时,请使用其服务名称,而不是localhost

因此,将app1中的行从:更改为

response = requests.get('http://localhost:81/')

至:

response = requests.get('http://app2:81/')

最新更新