Deploying Flask on cPanel with Passenger
This guide demonstrates how to deploy a Flask application on a cPanel hosting environment using Phusion Passenger. Many modern cPanel hosts use Passenger to manage Python (and Node.js/Ruby) applications, making deployment relatively straightforward compared to traditional CGI.
Prerequisites
- cPanel Hosting: Your hosting provider must support "Setup Python App" (CloudLinux/Passenger).
- Access: Access to cPanel and File Manager (or SSH).
Step 1: Create Python App in cPanel
- Log in to cPanel.
- Find the Software section and click Setup Python App.
- Click Create Application.
- Python Version: Select a recommended version (e.g., 3.9 or newer).
- Application Root: The folder where your app files will live (e.g.,
myapp). - Application URL: The domain or path where the app will be accessible (e.g.,
mydomain.com/app). - Application Startup File: Leave blank or set to
passenger_wsgi.py. - Application Entry Point: Leave blank or set to
application. - Click Create.
cPanel will create the directory and a virtual environment. It usually gives you a command to enter the virtual environment (e.g., source /home/user/virtualenv/myapp/3.9/bin/activate).
Step 2: The Flask Application
Create a file named app.py inside your Application Root folder (e.g., myapp).
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Hello from Flask on cPanel!"
if __name__ == "__main__":
app.run()
Step 3: The Passenger Entry Point
Passenger looks for a file named passenger_wsgi.py. This file tells the server how to run your app. Create or edit passenger_wsgi.py in your Application Root.
import sys
import os
# 1. Add the current directory to sys.path so Python can find your app
sys.path.insert(0, os.path.dirname(__file__))
# 2. Import the Flask app
# 'from app' refers to app.py
# 'import app as application' is crucial because Passenger looks for an object named 'application'
from app import app as application
Step 4: Install Dependencies
-
Create a
requirements.txtfile in your Application Root:Flask -
Install via cPanel UI:
- Go back to Setup Python App in cPanel.
- Click Edit on your app.
- Scroll down to "Configuration files", enter
requirements.txt, and click Add. - Click Run Pip Install.
Step 5: Restart the Application
Whenever you make changes to the code, you must restart the app for Passenger to reload it.
- Go to Setup Python App in cPanel.
- Click the Restart button next to your application.
Visit your URL, and you should see "Hello from Flask on cPanel!".