This tutorial exists for these OS versions
- Ubuntu 22.04 (Jammy Jellyfish)
- Ubuntu 20.04 (Focal Fossa)
On this page
Flask is a micro web framework written in Python developed by Armin Ronacher. It is called microframework because it does not require any tools or libraries. Flask is a Python module and has a small and easy-to-extend core that helps you to develop web applications easily.
In this tutorial, we will learn how to deploy Flask application with Uwsgi and Nginx on Ubuntu 20.04.
Prerequisites
- A server running Ubuntu 20.04.
- A valid domain name pointed with your server IP.
- A root password is configured the server.
Getting Started
First, it is recommended to update your system packages with the latest version. You can update them by running the following command:
apt-get update -y
Once all the packages are updated, you can proceed to the next step.
Install Required Dependencies
Next, you will need to install some dependencies required to deploy flask application. You can install all of them with the following command:
apt-get install nginx python3-pip python3-dev python3-venv build-essential libssl-dev libffi-dev python3-setuptools -y
Once all the packages are installed, you can proceed to the next step.
Create a Virtual Environment
Next, you will need to create a virtual environment for your Flask application. The virtual environment is a very useful tool used to create isolated Python environments. It helps you to install a specific version of Python for your project.
First, create a directory for your Flask application with the following command:
mkdir /var/www/html/myapp
Next, change the directory to myapp and create a new Python virtual environment with the following command:
cd /var/www/html/myapp
python3.8 -m venv myappenv
Next, activate the virtual environment with the following command:
source myappenv/bin/activate
Set Up a Flask Application
At this point, Python virtual environment is ready for deploying Flask application. Next, you will need to set up a Flask app within your virtual environment.
First, install Flask and uWSGI with the following command:
pip install uwsgi flask
Next, create a sample application named myapp.py with the following command:
nano /var/www/html/myapp/myapp.py
Add the following lines:
from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "<h1 style='color:blue'>Hi This is My Flask Application</h1>" if __name__ == "__main__": app.run(host='0.0.0.0')
Save and close the file when you are finished. Next, run your Flask application with the following command:
python /var/www/html/myapp/myapp.py
You should see the following output:
* Serving Flask app "myapp" (lazy loading) * Environment: production Use a production WSGI server instead. * Debug mode: off * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
Now, open your web browser and access your Flask application using the URL http://your-server-ip:5000. You should see the following screen:
Now, press CTRL + C in your terminal to stop the Flask application.
Configure uWSGI
First, create a WSGI entry point to tell your uWSGI server how to interact with it.
nano /var/www/html/myapp/wsgi.py
Add the following lines to import your Flask instance from your application:
from myapp import app if __name__ == "__main__": app.run()
Save and close the file when you are finished then test uWSGI whether it can serve the application using the following command:
uwsgi --socket 0.0.0.0:5000 --protocol=http -w wsgi:app
Now, access your application again using the URL http://your-server-ip:5000. You should see the following screen:
Now, press CTRL + C to stop the application.
Next, run the following command to exit from your Virtual environment:
deactivate
Configure uWSGI
At this point, uWSGI is able to serve your application. Now, create a uWSGI configuration file with the following command:
nano /var/www/html/myapp/myapp.ini
Add the following lines:
[uwsgi] module = wsgi:app master = true processes = 5 socket = myapp.sock chmod-socket = 660 vacuum = true die-on-term = true
Save and close the file when you are finished.
Create a Systemd Service File
Next, you will need to create a systemd service file to manage the uWSGI service. You can create it with the following command:
nano /etc/systemd/system/myapp.service
Add the following lines:
[Unit] Description=uWSGI instance to serve myapp After=network.target [Service] User=www-data Group=www-data WorkingDirectory=/var/www/html/myapp Environment="PATH=/var/www/html/myapp/myappenv/bin" ExecStart=/var/www/html/myapp/myappenv/bin/uwsgi --ini myapp.ini [Install] WantedBy=multi-user.target
Save and close the file when you are finished then reload the systemd daemon with the following command:
systemctl daemon-reload
Next, change the ownership of your application to www-data and set proper permission with the following command:
chown -R www-data:www-data /var/www/html/myapp
chmod -R 775 /var/www/html/myapp
Next, start your application and enable it to start at system reboot with the following command:
systemctl start myapp
systemctl enable myapp
You can also check the status of your application with the following command:
systemctl status myapp
You should get the following output:
? myapp.service - uWSGI instance to serve myapp Loaded: loaded (/etc/systemd/system/myapp.service; disabled; vendor preset: enabled) Active: active (running) since Sun 2020-09-13 08:38:08 UTC; 1min 53s ago Main PID: 662796 (uwsgi) Tasks: 6 (limit: 4691) Memory: 21.8M CGroup: /system.slice/myapp.service ??662796 /var/www/html/myapp/myappenv/bin/uwsgi --ini myapp.ini ??662808 /var/www/html/myapp/myappenv/bin/uwsgi --ini myapp.ini ??662809 /var/www/html/myapp/myappenv/bin/uwsgi --ini myapp.ini ??662810 /var/www/html/myapp/myappenv/bin/uwsgi --ini myapp.ini ??662811 /var/www/html/myapp/myappenv/bin/uwsgi --ini myapp.ini ??662812 /var/www/html/myapp/myappenv/bin/uwsgi --ini myapp.ini Sep 13 08:38:08 ubuntu2004 uwsgi[662796]: WSGI app 0 (mountpoint='') ready in 0 seconds on interpreter 0x55e207e7a510 pid: 662796 (default app) Sep 13 08:38:08 ubuntu2004 uwsgi[662796]: *** uWSGI is running in multiple interpreter mode *** Sep 13 08:38:08 ubuntu2004 uwsgi[662796]: spawned uWSGI master process (pid: 662796) Sep 13 08:38:08 ubuntu2004 uwsgi[662796]: spawned uWSGI worker 1 (pid: 662808, cores: 1) Sep 13 08:38:08 ubuntu2004 uwsgi[662796]: spawned uWSGI worker 2 (pid: 662809, cores: 1) Sep 13 08:38:08 ubuntu2004 uwsgi[662796]: spawned uWSGI worker 3 (pid: 662810, cores: 1) Sep 13 08:38:08 ubuntu2004 uwsgi[662796]: spawned uWSGI worker 4 (pid: 662811, cores: 1) Sep 13 08:38:08 ubuntu2004 uwsgi[662796]: spawned uWSGI worker 5 (pid: 662812, cores: 1)
Configure Nginx as a Reverse Proxy
Next, you will need to configure Nginx as a reverse proxy to serve the Flask application. You can do it with the following command:
nano /etc/nginx/sites-available/flask.conf
Add the following lines:
server { listen 80; server_name flask.example.com; location / { include uwsgi_params; uwsgi_pass unix:/var/www/html/myapp/myapp.sock; } }
Save and close the file when you are finished. Next, check the Nginx for any syntax error with the following command:
nginx -t
You should see the following output:
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful
Next, activate the Nginx virtual host with the following command:
ln -s /etc/nginx/sites-available/flask.conf /etc/nginx/sites-enabled/
Finally, restart the Nginx service to apply the changes:
systemctl restart nginx
At this point, Nginx is configured to serve your Flask application.
Secure Flask Application with Let's Encrypt SSL
Next, it is also recommended to secure your application with Let's Encrypt free SSL. First, you will need to install Certbot client to install and manage the SSL certificate. You can install it with the following command:
apt-get install python3-certbot-nginx -y
Once installed, secure your website with Let's Encrypt SSL by running the following command:
certbot --nginx -d flask.example.com
You will be asked to provide a valid email address and accept the term of service as shown below:
Saving debug log to /var/log/letsencrypt/letsencrypt.log Plugins selected: Authenticator nginx, Installer nginx Enter email address (used for urgent renewal and security notices) (Enter 'c' to cancel): [email protected] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Please read the Terms of Service at https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf. You must agree in order to register with the ACME server at https://acme-v02.api.letsencrypt.org/directory - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - (A)gree/(C)ancel: A - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Would you be willing to share your email address with the Electronic Frontier Foundation, a founding partner of the Let's Encrypt project and the non-profit organization that develops Certbot? We'd like to send you email about our work encrypting the web, EFF news, campaigns, and ways to support digital freedom. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - (Y)es/(N)o: Y Obtaining a new certificate Performing the following challenges: http-01 challenge for flask.example.com Waiting for verification... Cleaning up challenges Deploying Certificate to VirtualHost /etc/nginx/sites-enabled/flask.conf
Next, choose whether or not to redirect HTTP traffic to HTTPS as shown bellow:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1: No redirect - Make no further changes to the webserver configuration. 2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for new sites, or if you're confident your site works on HTTPS. You can undo this change by editing your web server's configuration. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Select the appropriate number [1-2] then [enter] (press 'c' to cancel): 2
Type 2 and hit Enter to finish the installation. You should see the following output:
Redirecting all traffic on port 80 to ssl in /etc/nginx/sites-enabled/flask.conf - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Congratulations! You have successfully enabled https://flask.example.com You should test your configuration at: https://www.ssllabs.com/ssltest/analyze.html?d=flask.example.com - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - IMPORTANT NOTES: - Congratulations! Your certificate and chain have been saved at: /etc/letsencrypt/live/flask.example.com/fullchain.pem Your key file has been saved at: /etc/letsencrypt/live/flask.example.com/privkey.pem Your cert will expire on 2020-10-30. To obtain a new or tweaked version of this certificate in the future, simply run certbot again with the "certonly" option. To non-interactively renew *all* of your certificates, run "certbot renew" - Your account credentials have been saved in your Certbot configuration directory at /etc/letsencrypt. You should make a secure backup of this folder now. This configuration directory will also contain certificates and private keys obtained by Certbot so making regular backups of this folder is ideal. - If you like Certbot, please consider supporting our work by: Donating to ISRG / Let's Encrypt: https://letsencrypt.org/donate Donating to EFF: https://eff.org/donate-le - We were unable to subscribe you the EFF mailing list because your e-mail address appears to be invalid. You can try again later by visiting https://act.eff.org.
Now, your flask website is secured with Let's Encrypt SSL. You can access your Flask application using the URL https://flask.example.com.
Conclusion
Congratulations! you have successfully deployed Flask application with uWSGI and Nginx and secure it with Let's Encrypt SSL. You can now easily develop and deploy your Python app with Flask. Feel free to ask me if you have any questions.