Best practice to run FastAPI on Cloud Run with server port as $PORT
See original GitHub issueFirst Check
- I added a very descriptive title to this issue.
- I used the GitHub search to find a similar issue and didn’t find it.
- I searched the FastAPI documentation, with the integrated search.
- I already searched in Google “How to X in FastAPI” and didn’t find any information.
- I already read and followed all the tutorial in the docs and didn’t find an answer.
- I already checked if it is not related to FastAPI but to Pydantic.
- I already checked if it is not related to FastAPI but to Swagger UI.
- I already checked if it is not related to FastAPI but to ReDoc.
Commit to Help
- I commit to help with one of those options 👆
Example Code
"""
A sample Hello World server.
"""
import uvicorn
import os
from fastapi import FastAPI, Request
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
@app.route('/')
def hello(request: Request):
"""Return a friendly HTTP greeting."""
message = "It's running!"
"""Get Cloud Run environment variables."""
service = os.environ.get('K_SERVICE', 'Unknown service')
revision = os.environ.get('K_REVISION', 'Unknown revision')
return templates.TemplateResponse('index.html', context={
"request": request,
"message": message,
"Service": service,
"Revision": revision})
if __name__ == "__main__":
uvicorn.run("main:app", host="0.0.0.0", port=int(os.environ.get('PORT', 8000)), log_level="info")
Description
I’ve been using Google Cloud Code in VSCode and PyCharm and the example they have for Python is a Flask app. I’ve been trying to rewrite the example app but with FastAPI. To have it running on Cloud Run you have to start the server with the port binded to an OS env variable called PORT. My question is:
- Should I start uvicorn programmaticaly like in the example or,
- Should I have a “normal” FastAPI app main.py file and use the CMD or ENTRYPOINT to bind the $PORT variable?
Note: ENTRYPOINT ["uvicorn", "main:app", "-port", "$PORT"]
won’t work because the CMD in exec form won’t substitute the variable to its value, as documented here. It must be in shell form ENTRYPOINT uvicorn main:app --port $PORT
Operating System
Linux
Operating System Details
No response
FastAPI Version
0.78.0
Python Version
Python 3.10.4
Additional Context
The Cloud Code Flask sample code: https://github.com/GoogleCloudPlatform/cloud-code-samples/tree/v1/python/cloud-run-python-hello-world
Issue Analytics
- State:
- Created a year ago
- Comments:11 (5 by maintainers)
Top Results From Across the Web
Deploy a Dockerized FastAPI App to Google Cloud Platform
In this article, we will show how to deploy a FastAPI application to GCP Cloud Run. We'll use Docker, GCP Cloud Build and...
Read more >FastAPI: Deploy Containerized Apps On Google Cloud Run
1. Setting up FastAPI. The first step to building with FastAPI is to install the library on our local machine. Running the command...
Read more >Run a Server Manually - Uvicorn - FastAPI
These examples run the server program (e.g Uvicorn), starting a single process, listening on all the IPs ( 0.0.0.0 ) on a predefined...
Read more >Building a FastAPI Application and Deploying it with Okteto ...
The port 8080 is chosen since Okteto applications run on port 8080 by default, the reload value is set to True to avoid...
Read more >Deploy ML with FastAPI, Docker, and Cloud Run - Syndicai
What is great about FastAPI is that it generates the documentation on the go when you are developing the API which is the...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Having multiple ways to achieve the same goal can be more confusing than helpful. 😅
From the FastAPI documentation:
My question is about how should I pass the $PORT variable to the server (uvicorn/gunicorn) not about the server itself to use.