To run a FastAPI application on a custom port, you need to specify the port number when you start your application. The port number is an integer between
65535 that identifies the network endpoint for your application. The default port for FastAPI is
8000, but you can change it to any available port on your machine.
Running FastAPI on a Custom Port in Development
If you are running your FastAPI app on your local computer, from the command line, you can use the
--port option to set the port number. For example, if you want to run your app on port
3000, you can use this command:
uvicorn main:app --port 3000
If you are running your FastAPI backend from a Python script, you can use the
port argument of the
uvicorn.run function to set the port number. For instance, if you want to run your app on port
10000, you can use this code:
import uvicorn from fastapi import FastAPI app = FastAPI() # your app code here if __name__ == "__main__": uvicorn.run(app, port=10000)
Running FastAPI on Custom Port in Production
If you are deploying your app using a production-ready server like Gunicorn or Hypercorn, you can use the
--bind option to set the host and port for your app. For example, if you want to run your app on port
5000, you can use the command below:
gunicorn -k uvicorn.workers.UvicornWorker -w 4 --bind 0.0.0.0:5000 main:app
Alternatively, you can use environment variables to set the host and port for your app. For instance, if you want to run your app on port
20000, you can use these environment variables:
export HOST=0.0.0.0 export PORT=3000 gunicorn -k uvicorn.workers.UvicornWorker -w 4 main:app
In case you want to learn how to deploy your FastAPI on an Ubuntu server, check this article: Deploying FastAPI on Ubuntu with Nginx and Let’s Encrypt.
In general, running a FastAPI app on a custom port is easy and flexible. You just need to specify the port number when you start the server program or use environment variables to configure it. You can choose any available port on your machine that suits your needs and preferences. This tutorial ends here. Good luck!