简体   繁体   English

GET 请求在 docker 容器中没有响应

[英]GET request not responding in docker container

I have a fastapi app running in a docker container that is connected to a PostgreSQL DB which is running as a container too.我有一个在 docker 容器中运行的fastapi应用程序,该容器连接到也作为容器运行的 PostgreSQL 数据库。 I have both the infos in the docker-compose.yml file.我在docker-compose.yml文件中都有这两个信息。

In the app, I have a POST endpoint that is requesting data from an external API ( https://restcountries.com/v2/all ) using the requests library.在应用程序中,我有一个POST端点,它使用requests库从外部 API ( https://restcountries.com/v2/all ) 请求数据。 Once the data is extracted, I am trying to save it in a table in the DB.提取数据后,我试图将其保存在数据库中的表中。 When I trigger the endpoint from docker container, it takes forever and the data is not being extracted from the API.当我从 docker 容器触发端点时,它需要很长时间,并且不会从 API 中提取数据。 But at the same time, when I run the same code outside the docker container, it gets executed instantly and the data is received.但同时,当我在 docker 容器外运行相同的代码时,它会立即执行并接收数据。

The docker-compose.yml file: docker-compose.yml文件:

version: "3.6"

services:
  backend-api:
    build:
      context: .
      dockerfile: docker/Dockerfile.api
    volumes:
      - ./:/srv/recruiting/
    command: uvicorn --reload --reload-dir "/srv/recruiting/backend" --host 0.0.0.0 --port 8080 --log-level "debug" "backend.main:app"
    ports:
      - "8080:8080"
    networks:
      - backend_network
    depends_on:
      - postgres

  postgres:
    image: "postgres:13"
    volumes:
      - postgres_data:/var/lib/postgresql/data/pgdata:delegated
    environment:
      - PGDATA=/var/lib/postgresql/data/pgdata
      - POSTGRES_PASSWORD=pgpw12
    expose:
      - "5432"
    ports:
      - "5432:5432"
    networks:
      - backend_network

volumes:
  postgres_data: {}

networks:
  backend_network: {}

The code that is making the request:发出请求的代码:

req = requests.get('https://restcountries.com/v2/all')
json_data = req.json()

Am I missing something or doing something wrong?我错过了什么或做错了什么?

I often use python requests inside my python containers, and have come across this problem a couple of times.我经常在我的 python 容器中使用 python 请求,并且遇到过几次这个问题。 I haven't found a proper solution, but restarting Docker Desktop (entirely restarting it, not just restarting your container) seems to work every time.我还没有找到合适的解决方案,但重新启动 Docker Desktop(完全重新启动它,而不仅仅是重新启动容器)似乎每次都有效。 What I have found helpful in the past, is to specify a timeout period in the invocation of the HTTP call:我过去发现有帮助的是在调用 HTTP 调用时指定超时时间:

requests.request(method="POST", url=url, json=data, headers=headers, timeout=2)

When the server does not send data within the timeout period, an exception will be raised.当服务器在超时时间内没有发送数据时,会引发异常。 At least you'll be aware of the issue, and will waste less time identifying when this occurs again.至少您会意识到这个问题,并且会浪费更少的时间来确定何时再次发生这种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM