简体   繁体   中英

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. I have both the infos in the docker-compose.yml file.

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. 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. But at the same time, when I run the same code outside the docker container, it gets executed instantly and the data is received.

The docker-compose.yml file:

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. I haven't found a proper solution, but restarting Docker Desktop (entirely restarting it, not just restarting your container) seems to work every time. What I have found helpful in the past, is to specify a timeout period in the invocation of the HTTP call:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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