Deploying FastAPI on shared hosting using cPanel can be a bit tricky since shared hosting generally supports WSGI applications, while FastAPI is ASGI-based. However, using the right setup and workarounds, you can successfully run FastAPI apps on shared servers.
Prerequisites
- A shared hosting account with cPanel access
- Python app support in cPanel (usually with Passenger)
- Your FastAPI project (a main.py file with an app instance)
I am going to deploy the project in the domain fastapi.manishdev.com. First, let's create a new subdomain. To do that, I am going to follow these steps.
1. Create a Subdomain first.
- Go to domains
- Click Create a new domain
- In the form, fill the correct subdomain name and click save, this will create a new directory (e.g., fastapi.manish.dev)
- You will be taken to a list of domains available, which you can see below.
2. Upload the project using ftp or a file manager
These are my two project files that I will be uploading.
- Go to the file manager and select your project directory (e.g., fastapi.manish.dev). Then upload your project files. After uploading your project files, the project directory should look like this.
3. Create a Python App in cPanel
- Log in to cPanel.
- Go to Software > Setup Python App.
- Click Create Application and configure:
Choose an Appropriate Python version (e.g., 3.12.10), Set Application root as required (e.g., fastapi.manish.dev), Set Application URL and domain (e.g, fastapi.manish.dev), and click create
Copy the command to access the application’s virtual environment from the place pointed by the arrow, and click Stop App
4. Install dependencies and run FastAPI in the terminal
- Open Terminal in cPanel and run these commands one by one.
source /path/to/virtualenv/fastapi.manishdev.com/3.12/bin/activate && cd /path/to/fastapi.manishdev.com
pip install -r requirements.txt
uvicorn main:app --host 0.0.0.0 --port 8001
- Paste and run the command you copied in the above step to enable the virtual environment and cd into the project directory. Then install packages with Pip here. Then run Uvicorn with this command.
I am running uvicorn on port 8001 as 8000 is not available, you can use 8000 as well if it's available.
4. Update .htaccess
Lastly, let's add/update the .htaccess file. Copy the content from below and paste it into your .htaccess file located in the project directory.
RewriteEngine On
# Force HTTPS
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
# Reverse Proxy
RewriteRule ^(.*)$ http://fastapi.manishdev.com:8001/$1 [P,L]
5. Finally when I visit url I get json response as below.
I have created this post taking reference from this blog post from lucidgen
Top comments (1)
Hey bro, I accidentally closed the terminal. How can I stop the FastAPI app now?