docker aiohttp 服务无法连接到另一个 docker fastapi 服务

docker aiohttp service cannot connect to another docker fastapi service

我有两个服务,第一个是 FastAPI,另一个是每 X 秒调用一次此服务的服务。

FastAPI:

app = FastApi()
@app.post("/accounts/", status_code=status.HTTP_200_OK)
async def account_split():
    return {"details": "Accounts updated."}

aiohttp:

async def process():
    while True:
        for i in range(10):
            await asyncio.sleep(delay)

            async with ClientSession() as session:
                try:
                    async with session.post("http://0.0.0.0:8080/accounts/", json=json.dumps({"i": i}), ssl=False) as response:
                        response = await response.read()
                        print(response)
                except ClientConnectionError as e:
                    print('Connection Error', str(e))


if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(process())
    loop.run_forever()

docker-撰写:

version: "3.9"
services:
  aio:
    build: ./aio
    container_name: aio
    networks:
      - default
    restart: on-failure
    depends_on:
      - api
    command: ["python", "./aio/main.py"]

  api:
    build: ./api
    container_name: api
    networks:
      - default
    ports:
      - "8080:8080"
    restart: on-failure
    command: ["uvicorn", "api.main:app", "--host", "0.0.0.0", "--port", "8080"]

networks:
  default: {}

我仍然收到此错误

Cannot connect to host 0.0.0.0:8080 ssl:False [Connect call failed ('0.0.0.0', 8080)]

不知道是什么原因,有什么想法吗? 谢谢

根据 Docker Compose documentation,使用 api 配置创建的容器以名称 api 加入默认网络。因此你应该使用它而不是 0.0.0.0,就像 http://api:8080/accounts/.

此外,应该考虑到,depends_on 在启动依赖项之前不会等待容器“准备好” - 直到它已经启动。