Home > Net >  Unable to requests FastAPI running in docker-compose
Unable to requests FastAPI running in docker-compose

Time:01-27

I have a Dockerfile which exposes an API on port 8000:

# ..

EXPOSE 8000
ENV PYTHONPATH="src/."
CMD ["gunicorn", "-b :8000", "-k", "uvicorn.workers.UvicornWorker", "fingerprinter.api.server:app"]

It's just a simple FastAPI server with a simple endpoint:

@app.get("/health")
def health():
    return "OK"

This is the relevant part of the docker-compose.yaml:

version: "3.7"

services:

  fprint-api:
    container_name: fprint-api-v2
    image: "fprint-api:v0.0.1"
    depends_on:
      - fprint-db
      - fprint-svc

    network_mode: "host"
    extra_hosts:
      - "host.docker.internal:host-gateway"
    expose:
      - "8000"

    build:
      context: ../.
      dockerfile: docker/Dockerfile.fprint-api

However, I am not able to reach the endpoints.

CodePudding user response:

Expose in Dockerfile does not really publish the port Dockerfile - EXPOSE. It is more like a 'documentation' for a reader of Dockerfile, it shows that the port is intended to be published.

In docker-compose.yml you map port from docker container to host system by using port, Docker compose - ports. In docker-compose.yml keyword expose exposes port only for the linked services, it does not publish the port to the host machine Docker compose - expose

So your docker-compose.yml file should look like this:

version: "3.7"

services:

  fprint-api:
    container_name: fprint-api-v2
    image: "fprint-api:v0.0.1"
    depends_on:
      - fprint-db
      - fprint-svc

    # network_mode: "host"
    extra_hosts:
      - "host.docker.internal:host-gateway"
    ports:
      - "8000:8000"

    build:
      context: ../.
      dockerfile: docker/Dockerfile.fprint-api
  • Related