2 min read

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

  1. cPanel Hosting: Your hosting provider must support "Setup Python App" (CloudLinux/Passenger).
  2. Access: Access to cPanel and File Manager (or SSH).

Step 1: Create Python App in cPanel

  1. Log in to cPanel.
  2. Find the Software section and click Setup Python App.
  3. Click Create Application.
  4. Python Version: Select a recommended version (e.g., 3.9 or newer).
  5. Application Root: The folder where your app files will live (e.g., myapp).
  6. Application URL: The domain or path where the app will be accessible (e.g., mydomain.com/app).
  7. Application Startup File: Leave blank or set to passenger_wsgi.py.
  8. Application Entry Point: Leave blank or set to application.
  9. 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

  1. Create a requirements.txt file in your Application Root:

    Flask
  2. 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.

  1. Go to Setup Python App in cPanel.
  2. Click the Restart button next to your application.

Visit your URL, and you should see "Hello from Flask on cPanel!".

programming/python/python