Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
VGSources
Blog

How to Run Python Apps on a LAMP Server with Ubuntu

Learn how to run a Python WSGI app beside PHP on an Ubuntu LAMP server using Apache, mod_wsgi, a matching virtual environment, daemon mode, and a correctly mapped WSGI callable.
Length10 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Yes—Apache on Ubuntu can serve a Python WSGI application and PHP from the same LAMP server. The supported path is Apache 2 with Ubuntu’s libapache2-mod-wsgi-py3 package, a project-owned virtual environment, and an Apache virtual host that maps a URL to a WSGI callable. Put the Python app behind a daemon-mode mod_wsgi process group, leave PHP on its existing handler, and serve static files directly from Apache.

This guide shows the complete setup for Flask or Django, explains where every file belongs, and covers the limits that matter in production: the Python version compiled into mod_wsgi, permissions, static assets, HTTPS, logs, and ASGI frameworks such as FastAPI.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What the finished architecture looks like

Apache is the public HTTP server. It can continue handling PHP requests through the PHP module while mod_wsgi handles a separate URL prefix for Python. For example, https://example.com/ can serve a PHP site and https://example.com/myapp/ can be mapped to a Flask or Django application.

For a normal deployment, use mod_wsgi daemon mode. Apache loads the WSGI module, then sends matching requests to a dedicated process group. The group has its own virtual-environment package path and is not mixed with unrelated Apache modules. WSGIScriptAlias performs the URL-to-WSGI-script mapping; the script must expose a callable named application.

#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter | 4Pack Type C Female to A Male Cable Converter for Apple Duo 17 16 15 14 Plus,iWatch Watch 12 11 10,iPad 9 8 Air,Airpods 5 4
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
Component Role Typical location
Apache Accepts HTTP and HTTPS requests and selects a virtual host /etc/apache2/
mod_wsgi Embeds Python and invokes the WSGI callable Ubuntu package libapache2-mod-wsgi-py3
Virtual environment Isolates the application’s Python packages /srv/myapp/.venv
WSGI entry file Imports the application as application /srv/myapp/myapp.wsgi or a framework-generated wsgi.py
PHP handler Continues serving PHP routes on the same Apache instance Existing LAMP configuration

Before you start

You need an Ubuntu server with administrative access, a hostname pointed at it if the app will be public, and a Python project that supports WSGI. Keep the application in a path Apache can traverse, such as /srv/myapp, rather than inside a private home directory that the www-data user cannot enter.

  • Use a supported Ubuntu release and apply updates before installing services.
  • Know the Python interpreter your Ubuntu mod_wsgi package uses. A virtual environment made with a different Python installation cannot change the Python version embedded in mod_wsgi.
  • Have a dependency lock or pinned requirements.txt so the server installs the same package versions as development.
  • Back up the existing Apache virtual-host files before changing a server that already hosts PHP.

The examples below use the project name myapp, the path /srv/myapp, and the URL prefix /myapp. Replace those values consistently.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Install Apache and Ubuntu’s mod_wsgi package

  1. Update the package index and install Apache:

    sudo apt update
    sudo apt install apache2
  2. Install the distribution WSGI module:

    sudo apt install libapache2-mod-wsgi-py3

    Ubuntu enables the module automatically in the usual package installation. If it was disabled previously, enable it explicitly:

    sudo a2enmod wsgi
  3. Restart Apache after a module change:

    sudo systemctl restart apache2

Do not install a second mod_wsgi module over the Ubuntu package without a specific reason. Apache loads one mod_wsgi module, and that module is linked to one Python library. The package choice therefore determines which Python major/minor line that Apache instance can load.

Create the application and its virtual environment

Create a directory owned by your deployment account, with read and execute access for Apache. The exact ownership policy depends on your deployment process; the important requirement is that www-data can traverse the directories and read the code and virtual environment without being given unnecessary write access.

  1. Create the project directory and enter it:

    sudo mkdir -p /srv/myapp
    sudo chown -R "$USER":"$USER" /srv/myapp
    cd /srv/myapp
  2. Create a virtual environment with the same Python installation used to build the installed mod_wsgi module:

    What’s actually slowing this PC down?

    Pick the symptom - the matching free tool is one click away.

    Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
    python3 -m venv .venv

    If Ubuntu reports that the venv module is missing, install the matching distribution package for your Python version, then rerun the command.

    Rank #2
    Sale
    Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter | USB C Dongle with 90W Max Power Delivery, 3×5Gbps USB A Data Ports, for MacBook, Dell, and More (Charger Not Included)
    • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
    • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
    • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
    • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
    • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
  3. Activate the environment and install pinned dependencies:

    source /srv/myapp/.venv/bin/activate
    python -m pip install --upgrade pip
    python -m pip install -r requirements.txt
  4. Leave the environment when finished:

    deactivate

The virtual environment isolates packages; it does not let one Apache process use an arbitrary Python runtime. For example, an environment created with Python 3.12 cannot make a mod_wsgi module compiled for Python 3.10 load Python 3.12 code. Check the interpreter used to create the environment and the interpreter associated with the Ubuntu module before troubleshooting import errors.

Expose a WSGI callable

mod_wsgi does not look for a framework-specific launch command. It imports a script or module and expects an object named application that follows the WSGI interface.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Flask entry file

Suppose the Flask instance is called app in /srv/myapp/myapp.py. Create /srv/myapp/myapp.wsgi:

import sys

sys.path.insert(0, '/srv/myapp')
from myapp import app as application

The alias is significant: app is Flask’s object, while application is the name mod_wsgi imports. If your package layout differs, insert the project’s parent directory and import the real module instead.

Django entry file

Django normally generates a WSGI module inside the project package. If the project package is config, the generated file commonly contains:

import os
from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
application = get_wsgi_application()

You can point Apache directly at /srv/myapp/config/wsgi.py, or create a small wrapper at /srv/myapp/myapp.wsgi that imports it. Set Django’s allowed hosts and production settings for the hostname before exposing the site.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter | 85W Max PD, 2 USB 3.0 & 1 USBC Data Ports, SD/TF Card Reader, for Laptops/Mac and Other Type C Devices (Charger Not Included)
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Configure an Apache virtual host in daemon mode

Create a site file under /etc/apache2/sites-available/:

sudo nano /etc/apache2/sites-available/myapp.conf

A Flask-oriented example is:

<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com

    WSGIDaemonProcess myapp 
        python-home=/srv/myapp/.venv 
        python-path=/srv/myapp
    WSGIProcessGroup myapp
    WSGIApplicationGroup %{GLOBAL}

    WSGIScriptAlias /myapp /srv/myapp/myapp.wsgi

    <Directory /srv/myapp>
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/myapp_error.log
    CustomLog ${APACHE_LOG_DIR}/myapp_access.log combined
</VirtualHost>

Replace example.com and the script path. python-home selects the virtual environment, while python-path adds the project directory to Python’s import path. The WSGIProcessGroup line assigns requests to the daemon group. WSGIApplicationGroup %{GLOBAL} is useful for packages that do not work correctly in a sub-interpreter; omit it only when you know the application and dependencies do not need it.

The broad Require all granted rule above is convenient for a dedicated application directory, but do not use it to expose secrets, deployment files, or writable upload directories. A tighter layout places only the WSGI file and importable package in the application directory and gives static files their own read-only directory.

Map a subpath or use a separate hostname

WSGIScriptAlias /myapp ... makes the Python app available below /myapp. If the app should own the entire hostname, map the root path instead:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
WSGIScriptAlias / /srv/myapp/myapp.wsgi

Using a separate hostname, such as python.example.com, often avoids collisions with an existing PHP site. A path-based deployment is still valid, but configure the framework’s URL-prefix or script-name settings when it generates links.

Serve static files directly from Apache

Static assets should normally bypass Python. Build or collect them into a directory such as /srv/myapp/static, then add an alias before the WSGI mapping:

Alias /myapp/static/ /srv/myapp/static/

<Directory /srv/myapp/static>
    Require all granted
</Directory>

For Django, run the project’s configured static-file collection command inside the virtual environment, then point the alias at the resulting directory. Keep user uploads separate from source code and apply an upload policy that prevents executable files from being interpreted as scripts.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray | Data transfer & Fast charging for MacBook, iPhone 17/16/15, iPad, Samsung Galaxy, Apple Watch
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Enable the site, validate it, and reload Apache

  1. Enable the new virtual host:

    sudo a2ensite myapp.conf
  2. Check the complete Apache configuration before reloading:

    Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
    sudo apache2ctl configtest

    Proceed only when the result is Syntax OK. A missing module, typo in a directive, or invalid path must be fixed first.

  3. Reload Apache so existing connections are handled gracefully:

    sudo systemctl reload apache2

    Use a full restart after changing a loaded module or when a reload does not replace stale worker processes.

  4. Open the mapped URL, for example http://example.com/myapp/. Confirm that the response is generated by the Python app and that an existing PHP URL still works.

    Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

If Apache selects the wrong virtual host, verify ServerName, DNS, and the enabled-site list. A request made directly to an IP address may match the default host rather than the new named host.

Make Python and PHP coexist safely

Apache chooses a handler based on the request and the virtual-host configuration. PHP requests can continue using the server’s existing PHP handler while the Python prefix is claimed by WSGIScriptAlias. Keep the mappings distinct: do not place the WSGI alias over a directory that contains the PHP application unless you deliberately want Python to receive those requests.

Best Value
Sale
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display | 85W Max PD, 1 Powered USB-C 5Gbps & 2 Powered USB-A 3.0 5Gbps Data Ports, for MacBook Pro, MacBook Air, Dell and More (Black)
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

A practical split is:

  • / or /shop for the existing PHP site;
  • /myapp for the WSGI application;
  • /myapp/static/ for Apache-served assets;
  • a separate log file for the Python virtual host or daemon group.

Both applications still share Apache’s host resources. Set sensible process counts and timeouts for the Python daemon group, monitor memory use, and avoid running development servers exposed to the network.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Read the right logs when the browser shows HTTP 500

A generic 500 response means the failure happened before a usable application response was returned. Check the application-specific Apache error log first, then the system journal and the application’s own logging output.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo tail -f /var/log/apache2/myapp_error.log
sudo journalctl -u apache2 -f
  • “No module named …”: confirm the package is installed in /srv/myapp/.venv, that python-home points there, and that python-path contains the project’s import root.
  • Permission denied: check every parent directory with namei -l /srv/myapp/myapp.wsgi. Apache needs execute permission on directories and read permission on code and the environment.
  • WSGI script cannot be loaded: verify the file exists, is readable, and defines application at import time.
  • Immediate worker exits: look for a Python-version mismatch or a native dependency that cannot load in the interpreter linked to mod_wsgi.
  • Blank or incorrect URL paths: check whether the framework knows it is mounted below /myapp and whether the WSGI alias has a trailing-slash policy that matches your routes.
  • Apache will not reload: run sudo apache2ctl configtest and correct the first syntax error reported rather than debugging the application.

Do not expose stack traces to visitors. Keep debug mode disabled and send diagnostic detail to a protected log.

Understand Python-version and mod_wsgi limits

Every Apache instance loads one copy of mod_wsgi, and that module has one Python library linked into it. Separate virtual environments can isolate Flask, Django, and their package versions, but they cannot make the same Apache process run applications requiring different linked Python versions.

Requirement Suitable design Important limitation
Several apps on the same Python line One Apache instance, separate virtual environments, separate daemon process groups Each environment must be compatible with the Python used by mod_wsgi
Apps requiring different Python minor versions Separate mod_wsgi-express instances, with a front-end Apache proxying to each Each instance must be built for its own Python; this is more operationally complex
One conventional Flask or Django app Ubuntu’s libapache2-mod-wsgi-py3 package and daemon mode All apps in that Apache share the module’s linked Python version

A PyPI-built mod_wsgi can be appropriate when the distribution module does not support the required Python build, but compiling and maintaining it becomes your responsibility. Do not assume that creating a new virtual environment changes the module’s ABI or Python version.

Know when mod_wsgi is the wrong server interface

WSGI is designed for synchronous WSGI applications such as traditional Flask and Django deployments. FastAPI and Starlette are ASGI frameworks; they do not natively run on a WSGI server. Run an ASGI-compatible server for those applications and place Apache in front as a reverse proxy, or use another front-end architecture that supports ASGI directly.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The boundary is important: forcing an ASGI application through a WSGI adapter can remove streaming, WebSocket, and other ASGI capabilities. Choose the serving interface before writing the Apache configuration.

Add HTTPS before public exposure

Do not treat an HTTP-only virtual host as a finished production deployment. Ubuntu documents Apache’s SSL module and a default SSL virtual-host configuration. Enable HTTPS with a certificate obtained through a separately verified certificate workflow, then redirect ordinary HTTP requests to the HTTPS host.

After TLS is working, review cookies, secure session settings, proxy headers, allowed hosts, and any absolute URLs generated by Flask or Django. Keep certificate renewal under monitoring and test renewal before the existing certificate expires.

Deployment checklist

  • Ubuntu packages are updated and Apache is running.
  • libapache2-mod-wsgi-py3 is installed and the wsgi module is enabled.
  • The virtual environment was created with the Python installation compatible with mod_wsgi.
  • Dependencies are pinned and installed inside that environment.
  • The WSGI entry file exposes application.
  • The application and environment are readable and traversable by Apache without giving Apache unnecessary write access.
  • The virtual host defines ServerName, a daemon process group, and WSGIScriptAlias.
  • Static files use an Apache Alias where appropriate.
  • apache2ctl configtest returns Syntax OK before every reload.
  • Application and Apache error logs are accessible to the operator.
  • Existing PHP routes still resolve to PHP and are not covered by the WSGI alias.
  • HTTPS, secure framework settings, backups, and monitoring are in place before public launch.

Quick decision guide

Your situation Recommended approach
Flask or Django, one Ubuntu Python line, Apache already serves PHP Install the Ubuntu mod_wsgi package, create a matching virtual environment, and use a daemon-mode WSGI virtual host under a dedicated path or hostname.
Several Flask/Django apps using compatible Python versions Use one daemon process group and one virtual environment per app; keep each WSGI alias and log separate.
Applications require different Python minor versions Use separate mod_wsgi-express instances and proxy from a front-end Apache, rather than trying to solve the mismatch with virtual environments.
FastAPI or Starlette Use an ASGI server and reverse-proxy design; mod_wsgi alone is not the native interface.

The Bottom Line

For a Flask or Django app on Ubuntu, install Apache and libapache2-mod-wsgi-py3, create a virtual environment with the matching Python installation, expose an application callable, and map it with WSGIScriptAlias in a daemon-mode virtual host. PHP can remain on the same Apache server, but applications needing another Python version or an ASGI interface require a separate serving design.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.