Website Vidya
Cloud & DevOpsStep-by-Step Guide

How to Install Flask on Ubuntu 24.04 LTS: Step-by-Step

Learn how to install flask on ubuntu 24.04 LTS with Python 3.12, venv virtual environments, Gunicorn WSGI server, systemd service, and Nginx reverse proxy.

RR
Rajesh RayLead Systems Educator
Published:
5 min read
PDF Cheat Sheet
How to Install Flask on Ubuntu 24.04 LTS: Step-by-Step
AI Executive SummaryWebsiteVidya AI

5 min read

Learn how to install flask on ubuntu 24.04 LTS with Python 3.12, venv virtual environments, Gunicorn WSGI server, systemd service, and Nginx reverse proxy.

Key Highlights
  • Prerequisites and Supported Releases
  • Step 1: Installing Python 3, venv, and Development Dependencies
  • Step 2: Creating an Isolated Project Directory and Virtual Environment
Grounded in full engineering runbookWebsiteVidya AI Engine

Interactive Builder for this Guide

Build your custom nginx syntax (How to Install Flask on Ubuntu 24.04 LTS: Step-by-Step)

Generated Config Output
server {
    listen 80;
    listen [::]:80;
    server_name app.example.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name app.example.com;

    ssl_certificate /etc/letsencrypt/live/app.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/app.example.com/privkey.pem;

    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;

    gzip on;
    gzip_types text/plain text/css application/json application/javascript application/xml;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}
Production Nginx reverse proxy -> 127.0.0.1:3000 for app.example.com.
Flag-by-Flag Breakdown
server_nameBinds this virtual host to app.example.com
return 301 https://...Redirects all plain HTTP requests permanently to TLS/HTTPS
proxy_pass http://127.0.0.1:3000Forwards HTTP + WebSocket requests to local application server
X-Content-Type-Options / X-Frame-OptionsProtects users against MIME sniffing and clickjacking

Flask is a lightweight, extensible Python micro web framework engineered for simplicity, flexibility, and rapid web application development.

Unlike heavyweight frameworks like Django, Flask does not enforce rigid directory hierarchies or require specific database abstraction layers; instead, it provides essential routing, request dispatching, and Jinja2 templating, allowing developers to choose their preferred libraries.

Ubuntu 24.04 LTS (Noble Numbat) ships with Python 3.12, providing an ultra-fast runtime environment for Python web applications when deployed alongside production WSGI servers like Gunicorn and Nginx.

In this guide, we walk through how to install flask on ubuntu 24.04 LTS, establish isolated virtual environments, run a test application, configure Gunicorn as a systemd background daemon, and secure it behind Nginx.

Advertisement

Prerequisites and Supported Releases

This guide is thoroughly verified on Ubuntu 24.04 LTS (Noble Numbat) & Ubuntu 22.04 LTS. The instructions apply cleanly to cloud instances (AWS EC2, Google Compute Engine, DigitalOcean, Hetzner), bare-metal servers, and local virtual machines.

Before proceeding, ensure you have the following requirements satisfied:

  • A server or computer running Ubuntu 24.04 LTS or Ubuntu 22.04 LTS.
  • A non-root user account with sudo administrative privileges.
  • Basic familiarity with the Linux terminal and Python programming.
  • An optional domain name pointing to your server's public IP address.

Step 1: Installing Python 3, venv, and Development Dependencies

Ubuntu 24.04 includes Python 3.12 by default, but developer header packages and the virtual environment module are packaged separately.

Advertisement

Under modern PEP 668 packaging standards, installing third-party Python packages globally via pip is restricted to protect operating system utilities.

Install python3-venv, python3-pip, and standard compilation tools via APT:

# Update APT package lists:
sudo apt update

# Install Python virtual environment and build tools:
sudo apt install -y python3-venv python3-pip python3-dev build-essential

# Verify Python 3 interpreter version:
python3 --version
# Expected output confirms: Python 3.12.x

Step 2: Creating an Isolated Project Directory and Virtual Environment

Always create a dedicated project directory and an isolated virtual environment for each Python application.

This ensures that your application dependencies remain strictly self-contained and prevents package version conflicts.

Advertisement

Create a workspace named myflaskapp and initialize a virtual environment:

# Create project directory:
mkdir -p ~/myflaskapp && cd ~/myflaskapp

# Create an isolated virtual environment named .venv:
python3 -m venv .venv

# Activate the virtual environment:
source .venv/bin/activate
# Notice shell prompt changes to: (.venv) user@host:~/myflaskapp$

Step 3: Installing Flask and Gunicorn via pip

With the virtual environment activated, install flask and gunicorn using pip.

Gunicorn (Green Unicorn) is a battle-tested Python WSGI HTTP server designed for handling concurrent production traffic:

Execute the pip installation command:

# Install Flask and Gunicorn inside the active virtual environment:
pip install --upgrade pip
pip install flask gunicorn

# Verify installed package versions:
pip list | grep -E "(Flask|gunicorn)"

Step 4: Creating a Sample Flask Application

Create a sample entrypoint file named app.py inside your project directory.

This script initializes a basic Flask instance and returns a welcoming JSON response when queried:

Create the application file using cat:

# ~/myflaskapp/app.py
from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/')
def home():
    return jsonify({
        "status": "success",
        "message": "Welcome to Flask running on Ubuntu 24.04 LTS!",
        "framework": "Flask 3.x",
        "python_version": "3.12"
    })

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

Testing the Application with Gunicorn

Verify that Gunicorn can serve your application successfully:

Run Gunicorn binding to loopback port 5000:

# Test WSGI execution with Gunicorn:
gunicorn --bind 127.0.0.1:5000 app:app

# In another terminal window, verify HTTP response:
curl http://127.0.0.1:5000/
# Output confirms JSON payload.

# Press Ctrl+C in the Gunicorn terminal to stop testing.

Step 5: Configuring a systemd Service for Gunicorn

In production environments, your application should run continuously in the background and restart automatically upon system reboot or unexpected crashes.

Create a systemd unit file at /etc/systemd/system/myflaskapp.service:

Define the service configuration, replacing username with your actual Ubuntu username:

# /etc/systemd/system/myflaskapp.service
[Unit]
Description=Gunicorn instance to serve myflaskapp
After=network.target

[Service]
User=username
Group=www-data
WorkingDirectory=/home/username/myflaskapp
Environment="PATH=/home/username/myflaskapp/.venv/bin"
ExecStart=/home/username/myflaskapp/.venv/bin/gunicorn --workers 3 --bind 127.0.0.1:5000 app:app
Restart=always

[Install]
WantedBy=multi-user.target

Starting and Enabling the Flask Service

Reload systemd, enable the service to start on boot, and verify its active status:

Check the background service using systemctl:

# Reload systemd daemon:
sudo systemctl daemon-reload

# Enable and start myflaskapp:
sudo systemctl enable --now myflaskapp

# Verify active status:
sudo systemctl status myflaskapp
# Output confirms: Active: active (running)

Step 6: Setting Up Nginx as a Reverse Proxy

Gunicorn is designed to serve Python WSGI requests, not public web traffic directly.

Nginx acts as a high-performance reverse proxy in front of Gunicorn, terminating SSL, serving static assets, and buffering slow client connections.

Create a new Nginx server block configuration in /etc/nginx/sites-available/myflaskapp:

# /etc/nginx/sites-available/myflaskapp
server {
    listen 80;
    server_name example.com www.example.com;

    location / {
        proxy_pass http://127.0.0.1:5000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

Enabling Nginx Site and Testing Configuration

Enable the server block by creating a symbolic link, test configuration syntax with nginx -t, and reload Nginx:

Allow web traffic through UFW firewall:

# Enable server block:
sudo ln -s /etc/nginx/sites-available/myflaskapp /etc/nginx/sites-enabled/

# Validate Nginx configuration syntax:
sudo nginx -t
# Output confirms: syntax is ok

# Reload Nginx:
sudo systemctl reload nginx

# Open HTTP/HTTPS ports in UFW firewall:
sudo ufw allow 'Nginx Full'

Troubleshooting and Common Errors

When configuring Ubuntu servers, unexpected permission errors, network timeouts, or lock contention can occur. Review these common issues and verified resolutions:

502 Bad Gateway error when accessing domain through Nginx

Cause: The Gunicorn systemd service is not running or listening on the expected port (127.0.0.1:5000).

Resolution: Check Gunicorn service status and logs using sudo systemctl status myflaskapp and journalctl -u myflaskapp -e.

sudo systemctl status myflaskapp

error: externally-managed-environment when installing Flask with pip

Cause: Attempting to install packages into the global system Python environment under PEP 668.

Resolution: Create and activate a virtual environment (python3 -m venv .venv && source .venv/bin/activate).

python3 -m venv .venv && source .venv/bin/activate

ModuleNotFoundError: No module named 'flask' in systemd logs

Cause: The Environment PATH in the systemd service file does not point to the virtual environment's bin folder.

Resolution: Ensure Environment="PATH=/path/to/myflaskapp/.venv/bin" is correctly configured in /etc/systemd/system/myflaskapp.service.

cat /etc/systemd/system/myflaskapp.service

Security Best Practices and Hardening

Never run Flask's built-in development server (flask run) in production; always use an enterprise WSGI server like Gunicorn or uWSGI.

Ensure debug=True is disabled in production to prevent arbitrary code execution via the interactive Werkzeug debugger.

Secure production endpoints with free Let's Encrypt TLS certificates: sudo certbot --nginx -d example.com.

Deepen your Linux system administration skills with our related production-tested guides:

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
Flask's built-in server is designed solely for local development. It is single-threaded, lacks request buffering, and can expose critical security vulnerabilities if debug mode is active. Production setups require a WSGI server like Gunicorn.
A standard industry formula for Gunicorn worker processes is (2 x CPU Cores) + 1. On a 2-core cloud server, configure 5 worker processes.
Activate your virtual environment (source .venv/bin/activate) and run pip install --upgrade flask, then restart the systemd service with sudo systemctl restart myflaskapp.
Yes. Binding Gunicorn to a Unix socket (e.g., myflaskapp.sock) reduces network overhead and offers marginally faster response times than TCP loopback sockets.
RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Cloud & DevOps•

How to Close File Descriptors Above 9 in Dash Shell

Attempting to close a file descriptor above 9 in Dash using exec 10<&- results in a 10: not found error because Dash's POSIX lexer only recognizes single-digit file descriptors (0–9) in redirection operators. This guide explains the exact parser limitation, why FDs 10+ are reserved for internal shell state, and how to safely close inherited file descriptors using close_range, Python, or Perl wrappers.

RR
Rajesh Rai
Read More
Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout