How to Install Flask on Ubuntu 24.04
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.
Update the server's package index.
console$ sudo apt update
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
View the installed Pip version.
console$ pip --version
Output:
pip 24.0 from /usr/lib/python3/dist-packages/pip (python 3.12)
Install the
venv
Python virtual environment module.console$ sudo apt install python3-venv -y
Create a new directory for your Flask project.
console$ mkdir flask_project
Switch to the Flask project directory.
console$ cd flask_project
Create a new
flaskenv
virtual environment.console$ python3 -m venv flaskenv
The above
python3 -m venv flaskenv
command creates a new isolatedflaskenv
environment to install and manage Python packages on the server.Activate the
flaskenv
virtual environment.console$ source flaskenv/bin/activate
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.
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
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.
Create a new
flask_app.py
Python application file using a text editor such asnano
.console$ nano flask_app.py
Add the following contents to the file.
pythonfrom 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 addresses0.0.0.0
and displays aHello World! Greetings from Vultr!
prompt when accessed.Allow connections to the TCP port
5000
through the default firewall.console$ sudo ufw allow 5000/tcp
Reload UFW to apply the firewall configuration changes.
console$ sudo ufw reload
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
Access port
5000
using your server's IP address in a web browser such as Chrome.http://SERVER-IP:5000
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.
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
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
Create a new
gunicorn_conf.py
file.console$ sudo nano gunicorn_conf.py
Add the following configurations to the
gunicorn_conf.py
file. Replace/home/linuxuser/flask_project
with your actual project path.inifrom 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.
Create a new
flask_app.service
systemd service file.console$ sudo nano /etc/systemd/system/flask_app.service
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.
Reload the systemd daemon to apply the service configuration changes.
console$ sudo systemctl daemon-reload
Enable the
flask_app
service to start at boot.console$ sudo systemctl enable flask_app
Start the
flask_app
service.console$ sudo systemctl start flask_app
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)................
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.
Deactivate the
flaskenv
virtual environment.console$ deactivate
Install Nginx.
console$ sudo apt install nginx -y
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
Add the following configuration to the file. Replace
flask.example.com
with your domain and/home/linuxuser/flask_project
with your actual project path.nginxserver { 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.
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
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
Restart Nginx to apply the configuration changes.
console$ sudo systemctl restart nginx
View the firewall status.
console$ sudo ufw status
Remove the Flask application port
5000
rule from the firewall configuration.console$ sudo ufw delete allow 5000/tcp
Allow the
Nginx Full
profile through the firewall to enable HTTP and HTTPS connections.console$ sudo ufw allow 'Nginx Full'
Reload UFW to apply the firewall configuration changes.
console$ sudo ufw reload
Change your user's home directory permissions mode to
775
to enable read privileges for all users on the server. Replacelinuxuser
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.
Install the Certbot Let's Encrypt client using Snap.
console$ sudo snap install --classic certbot
Generate a new SSL certificate using your
flask.example.com
domain. Replaceflask.example.com
with your domain anduser@example.com
with your actual email.console$ sudo certbot --nginx -d flask.example.com -m user@example.com --agree-tos
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) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Restart Nginx to apply the SSL configuration changes.
console$ sudo systemctl restart nginx
Access your domain in a new web browser window and verify that your Flask web application displays.
https://flask.example.com
Uninstall Flask on Ubuntu 24.04
Follow the steps below to uninstall flask on Ubuntu 24.04 if necessary.
Deactivate your project's virtual environment.
console$ deactivate
Delete the Flask project directory.
console$ rm -rf ~/flask_project
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.