Docker Error: ERR_CONNECTION_REFUSED using FastAPI

Viewed 652

I am trying to deploy an API with docker-compose. I am using FastAPI and I keep getting this error when I try to access the localhost page. If I don't use the docker-compose it works flawless. All my files are in the same directory.

Here is the Dockerfile

FROM python:3.9-slim

WORKDIR /usr/app

RUN python -m pip install --upgrade pip

COPY ./ ./

RUN pip install --no-cache-dir --upgrade -r requirements.txt

EXPOSE 8000

CMD [ "uvicorn", "main:app", "--reload" ]

And here is the docker-compose.yml

version: '2.2'

services:
  api:
    build: ./
    volumes:
      - './requirements.txt:/app'

And this is the error message I get on the browser:

ERR_CONNECTION_REFUSED

1 Answers

Exposing a port does not means that it is published to your host.

The EXPOSE instruction does not actually publish the port. It functions as a type of documentation between the person who builds the image and the person who runs the container, about which ports are intended to be published. To actually publish the port when running the container, use the -p flag on docker run to publish and map one or more ports, or the -P flag to publish all exposed ports and map them to high-order ports.

Source: https://docs.docker.com/engine/reference/builder/#expose

So, you also need to publish it in your docker-compose.yml:

version: '2.2'

services:
  api:
    build: .
    volumes:
      - ./requirements.txt:/app
    ports: 
      - 8000:8000
Related