How to Install Flask on Ubuntu 24.04

Updated on January 17, 2025
How to Install Flask on Ubuntu 24.04 header image

Introduction

Install Flask on Ubuntu 24.04 to create modern web applications with a lightweight and open-source Python framework. Flask offers core features like routing, request handling, and Jinja2 templating, while allowing developers to enhance functionality through extensions. Its simplicity, scalability, and active community support make it a preferred choice for building applications and APIs, from small prototypes to large-scale solutions.

This article explains how to install Flask on Ubuntu 24.04. You will install all required development packages, set up a virtual environment, and integrate Flask with Gunicorn to run web applications on the server.

Set Up the Flask Project Environment

You can install Flask on Ubuntu as a Python package using Pip. Python and Pip are pre-installed on Ubuntu by default while Flask works with any active version. Follow the steps below to verify the installed Python version and create a new virtual environment on your server.

  1. Update the server's package index.

    console
    $ sudo apt update
    
  2. View the installed Python version.

    console
    $ python3 --version
    

    Run the following command to install Python and Pip if unavailable.

    console
    $ sudo apt install python3 python3-pip -y
    
  3. View the installed Pip version.

    console
    $ pip --version
    

    Output:

    pip 24.0 from /usr/lib/python3/dist-packages/pip (python 3.12)
  4. Install the venv Python virtual environment module.

    console
    $ sudo apt install python3-venv -y
    
  5. Create a new directory for your Flask project.

    console
    $ mkdir flask_project
    
  6. Switch to the Flask project directory.

    console
    $ cd flask_project
    
  7. Create a new flaskenv virtual environment.

    console
    $ python3 -m venv flaskenv
    

    The above python3 -m venv flaskenv command creates a new isolated flaskenv environment to install and manage Python packages on the server.

  8. Activate the flaskenv virtual environment.

    console
    $ source flaskenv/bin/activate
    
  9. Verify that your shell prompt changes to the flaskenv virtual environment.

    console
    (flaskenv) example_user@vultr:/flask_project$
    

Install Flask on Ubuntu 24.04

Follow the steps below to install Flask in the active flaskenv virtual environment on your server.

  1. Install Flask using Pip.

    console
    $ pip install flask
    

    Output:

    Collecting flask
      Downloading flask-3.1.0-py3-none-any.whl.metadata (2.7 kB)
    Collecting Werkzeug>=3.1 (from flask)..........
      Downloading werkzeug-3.1.3-py3-none-any.whl.metadata (3.7 kB)
      Downloading MarkupSafe-3.0.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (4.0 kB)........
    Installing collected packages: MarkupSafe, itsdangerous, click, blinker, Werkzeug, Jinja2, flask
    Successfully installed Jinja2-3.1.4 MarkupSafe-3.0.2 Werkzeug-3.1.3 blinker-1.9.0 click-8.1.7 flask-3.1.0 itsdangerous-2.2.0
    • To install Flask globally on your server without using a virtual environment, run the following command instead.

      console
      $ pip install flask --user
      
  2. View the installed flask version.

    console
    $ flask --version
    

    Output:

    Python 3.12.3
    Flask 3.1.0
    Werkzeug 3.1.3

Create a Basic Flask Application

Follow the steps below to create a basic flask application to test your installation.

  1. Create a new flask_app.py Python application file using a text editor such as nano.

    console
    $ nano flask_app.py
    
  2. Add the following contents to the file.

    python
    from flask import Flask
    
    app = Flask(__name__)
    
    @app.route('/')
    def hello_world():
        return 'Hello World! Greeting from Vultr!'
    
    if __name__ == '__main__':
        app.run(host='0.0.0.0', port=5000)
    

    Save and close the file.

    The above Python application listens for connection requests on port 5000 using all server IP addresses 0.0.0.0 and displays a Hello World! Greetings from Vultr! prompt when accessed.

  3. Allow connections to the TCP port 5000 through the default firewall.

    console
    $ sudo ufw allow 5000/tcp
    
  4. Reload UFW to apply the firewall configuration changes.

    console
    $ sudo ufw reload
    
  5. Run the flask_app.py application using Python.

    console
    $ python3 flask_app.py
    

    Output:

     * Serving Flask app 'flask_app'
     * Debug mode: off
    WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
     * Running on all addresses (0.0.0.0)
     * Running on http://127.0.0.1:5000
     * Running on http://YOUR_SERVER_IP:5000
    Press CTRL+C to quit
  6. Access port 5000 using your server's IP address in a web browser such as Chrome.

    http://SERVER-IP:5000

    Flask Web Application Image

Set Up Gunicorn as a System Service to Serve Flask Applications

Gunicorn is a Python Web Server Gateway Interface (WSGI) used to serve Python web applications running frameworks such as Flask, Django and FastAPI in production environments. Follow the steps below to install Gunicorn and set it up as a system service to serve Flask applications on your server.

  1. Install Gunicorn using Pip.

    console
    $ pip install gunicorn
    

    Output:

    Collecting gunicorn
      Downloading gunicorn-23.0.0-py3-none-any.whl.metadata (4.4 kB)
    Collecting packaging (from gunicorn)
      Downloading packaging-24.2-py3-none-any.whl.metadata (3.2 kB)
    Downloading gunicorn-23.0.0-py3-none-any.whl (85 kB)
       ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 85.0/85.0 kB 7.7 MB/s eta 0:00:00
    Downloading packaging-24.2-py3-none-any.whl (65 kB)
       ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 65.5/65.5 kB 27.9 MB/s eta 0:00:00
    Installing collected packages: packaging, gunicorn
    Successfully installed gunicorn-23.0.0 packaging-24.2
  2. Print your working directory and note the Flask project path.

    console
    $ pwd
    

    Your output should be similar to the one below.

    /home/linuxuser/flask_project
  3. Create a new gunicorn_conf.py file.

    console
    $ sudo nano gunicorn_conf.py
    
  4. Add the following configurations to the gunicorn_conf.py file. Replace /home/linuxuser/flask_project with your actual project path.

    ini
    from multiprocessing import cpu_count
    
    # Socket Path
    bind = 'unix:/home/linuxuser/flask_project/gunicorn.sock'
    
    # Worker Options
    workers = cpu_count() + 1
    worker_class = 'uvicorn.workers.UvicornWorker'
    
    # Logging Options
    loglevel = 'debug'
    accesslog = '/home/linuxuser/flask_project/access_log'
    errorlog =  '/home/linuxuser/flask_project/error_log'
    

    Save and close the file.

    The above Gunicorn configuration sets up a new UNIX socket for communication, dynamically allocates workers based on CPU cores and logs debug-level messages to the Flask project directory.

  5. Create a new flask_app.service systemd service file.

    console
    $ sudo nano /etc/systemd/system/flask_app.service
    
  6. Add the following configurations to the file. Replace linuxuser with your actual user and /home/linuxuser/flask_project with your project path.

    ini
    [Unit]
    Description=Gunicorn instance to serve Flask application
    After=network.target
    
    [Service]
    User=linuxuser
    Group=www-data
    WorkingDirectory=/home/linuxuser/flask_project
    Environment="PATH=/home/linuxuser/flask_project/flaskenv/bin"
    ExecStart=/home/linuxuser/flask_project/flaskenv/bin/gunicorn --workers 3 --bind unix:/home/linuxuser/flask_project/flask_app.sock flask_app:app
    
    [Install]
    WantedBy=multi-user.target
    

    Save and close the file.

  7. Reload the systemd daemon to apply the service configuration changes.

    console
    $ sudo systemctl daemon-reload
    
  8. Enable the flask_app service to start at boot.

    console
    $ sudo systemctl enable flask_app
    
  9. Start the flask_app service.

    console
    $ sudo systemctl start flask_app
    
  10. View the flask_app service status and verify that it's running.

    console
    $ sudo systemctl status flask_app
    

    Output:

    ● flask_app.service - Gunicorn instance to serve Flask application
         Loaded: loaded (/etc/systemd/system/flask_app.service; enabled; preset: enabled)
         Active: active (running) since Wed 2024-12-04 09:35:59 UTC; 17s ago
       Main PID: 15711 (gunicorn)................
  11. Run the Flask application using Gunicorn.

    console
    $ gunicorn --bind 0.0.0.0:5000 flask_app:app
    

Configure Nginx as a Reverse Proxy to Secure the Flask Application

The Flask application is active and accepts connection requests on the TCP port 5000 using all server interfaces based on your earlier configurations. Follow the steps below to install Nginx and set it up as a reverse proxy to securely handle connection requests using the flask.example.com domain on your server.

  1. Deactivate the flaskenv virtual environment.

    console
    $ deactivate
    
  2. Install Nginx.

    console
    $ sudo apt install nginx -y
    
  3. Create a new flask_app Nginx virtual host configuration in the /etc/nginx/sites-available directory.

    console
    $ sudo nano /etc/nginx/sites-available/flask_app
    
  4. Add the following configuration to the file. Replace flask.example.com with your domain and /home/linuxuser/flask_project with your actual project path.

    nginx
    server {
        listen 80;
        server_name flask.example.com;
    
        location / {
            include proxy_params;
            proxy_pass http://unix:/home/linuxuser/flask_project/flask_app.sock;
        }
    }
    

    Save and close the file.

  5. Link the virtual host configuration to the /etc/nginx/sites-enabled to enable it.

    console
    $ sudo ln -s /etc/nginx/sites-available/flask_app /etc/nginx/sites-enabled
    
  6. Test the Nginx configuration for errors.

    console
    $ sudo nginx -t
    

    Output:

    nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
    nginx: configuration file /etc/nginx/nginx.conf test is successful
  7. Restart Nginx to apply the configuration changes.

    console
    $ sudo systemctl restart nginx
    
  8. View the firewall status.

    console
    $ sudo ufw status
    
  9. Remove the Flask application port 5000 rule from the firewall configuration.

    console
    $ sudo ufw delete allow 5000/tcp
    
  10. Allow the Nginx Full profile through the firewall to enable HTTP and HTTPS connections.

    console
    $ sudo ufw allow 'Nginx Full'
    
  11. Reload UFW to apply the firewall configuration changes.

    console
    $ sudo ufw reload
    
  12. Change your user's home directory permissions mode to 775 to enable read privileges for all users on the server. Replace linuxuser with your actual user.

    console
    $ sudo chmod 755 /home/linuxuser/
    

Generate Trusted SSL Certificates

An SSL certificate encrypts the network connection between users and the Flask application server using HTTPS. The Flask web application listens for connection requests using HTTP which is insecure by default. Follow the steps below to generate trusted SSL certificates using Let's Encrypt to secure the flask application on your server.

  1. Install the Certbot Let's Encrypt client using Snap.

    console
    $ sudo snap install --classic certbot
    
  2. Generate a new SSL certificate using your flask.example.com domain. Replace flask.example.com with your domain and user@example.com with your actual email.

    console
    $ sudo certbot --nginx -d flask.example.com -m user@example.com --agree-tos
    
  3. Verify that Certbot auto-renews the SSL certificate every 90 days before it expires.

    console
    $ sudo certbot renew --dry-run
    

    Your output should be similar to the one below.

    Account registered.
    Simulating renewal of an existing certificate for flask.example.com
    
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Congratulations, all simulated renewals succeeded:
      /etc/letsencrypt/live/flask.example.com\/fullchain.pem (success)
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  4. Restart Nginx to apply the SSL configuration changes.

    console
    $ sudo systemctl restart nginx
    
  5. Access your domain in a new web browser window and verify that your Flask web application displays.

    https://flask.example.com

    The Flask Web Application Page

Uninstall Flask on Ubuntu 24.04

Follow the steps below to uninstall flask on Ubuntu 24.04 if necessary.

  1. Deactivate your project's virtual environment.

    console
    $ deactivate
    
  2. Delete the Flask project directory.

    console
    $ rm -rf ~/flask_project
    
  3. Uninstall Flask using Pip if globally installed on the server.

    console
    $ pip uninstall Flask
    

Troubleshooting

Follow the suggested solutions below to troubleshoot common Flask web application errors.

  • Check the Gunicorn logs for detailed errors.

    console
    $ journalctl -u flask_app.service -f
    
  • If you receive a 502 Bad Gateway error.

    • Verify that the Flask service is running.

      console
      $ sudo systemctl status flask_app
      
    • Verify that your user's home directory has atleast 0755 permissions to enable read privileges for all users.

      console
      $ sudo chmod 755 /home/linuxuser/
      
    • Check the Nginx error logs for additional information about the error.

      console
      $ sudo tail -f /var/log/nginx/error.log
      
  • Incase the application does not return the expected output, verify your application configuration and run the Flask application again.

Conclusion

You have installed Flask on Ubuntu 24.04 and created a basic application to serve the application on your server. In addition, you installed Gunicorn to deploy the application and handle connection requests using Nginx as a reverse proxy server. Combining the Flask framework's simplicity and flexibility with the Ubuntu server's reliability, you can build and deliver scalable production web applications. For more information, visit the Flask documentation.