3

I'm very new to Python.

I'm making a simple web server with fastapi and uvicorn.

When I build my Docker and run it, I have the following:

INFO:     Started server process [1]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:5000 (Press CTRL+C to quit)

My code is:

# Setup FastAPI server
import uvicorn
from fastapi import FastAPI
from fastapi_utils.tasks import repeat_every
from fastapi.middleware.cors import CORSMiddleware
from dotenv import load_dotenv
import os
from pymongo import MongoClient
import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

load_dotenv('env')

# Database
CONNECTION_URL = os.environ['mongoConnectionURL']
DATABASE_NAME = os.environ['mongoDatabaseName']
NEWS_COLLECTION = os.environ['mongodbNewsCollection']

app = FastAPI()

# TODO JS has next function i'm currently unaware of
app.add_middleware(
    CORSMiddleware,
    allow_origins=['*'],
    allow_headers=["Origin, X-Requested-With, Content-Type, Accept"],
)

@app.get('/')
def index():
    return 'See /entries'

@app.get('/entries')
def getEntries():
    client = MongoClient(CONNECTION_URL)
    databaseMongo = client.get_database(DATABASE_NAME)
    collectionMongo = databaseMongo.get_collection(NEWS_COLLECTION)
    result = list(collectionMongo.find())
    for entry in result:
        return {
            'data': result
        }

if __name__ == "__main__":
    uvicorn.run(app, port=int(os.environ['PORT']))

My Dockerfile is:

# Python container
FROM python:3.9.12

# Copy the source code to the container
COPY env /env
COPY main.py /main.py
COPY requirements.txt /requirements.txt

# If container is run in debug mode, we need to add the image folder
RUN mkdir /img

# Install requirements
RUN pip install --upgrade pip && pip install -r requirements.txt

CMD ["python", "main.py"]

I run my docker file as:

docker run memeified-docker-server

When I access the http://127.0.0.1:5000, the browser displays the ERR_CONNECTION_REFUSED page.

cyruslk
  • 839
  • 3
  • 13
  • 25
  • 1
    You haven't shown us how you're running your container, so we are unable to answer your question. Are you publishing the port to your host with the `-p` option to `docker run`? – larsks Jun 16 '22 at 18:56
  • Thanks for the clarification, let me add it now. – cyruslk Jun 16 '22 at 18:57
  • You can't reach your service on `localhost:5000` because you're not publishing the port to your host. You need to `docker run -p 5000:5000 memeified-docker-server` – larsks Jun 16 '22 at 19:55
  • When I run it and access http://127.0.0.1:5000, the same ERR_CONNECTION_REFUSED occurs. Is there anything I need to change? – cyruslk Jun 16 '22 at 20:28
  • did you fixed this issue? @cyruslk – Dolphin Apr 10 '23 at 09:54

1 Answers1

5

Try giving host="0.0.0.0" to uvicorn.run

uvicorn.run(app, host="0.0.0.0", port=int(os.environ['PORT']))

difference between 0.0.0.0 vs 127.0.0.1