Home > Backend Development > Python Tutorial > How to Deploy Flask Applications on Vultr

How to Deploy Flask Applications on Vultr

Christopher Nolan
Release: 2025-02-08 08:31:09
Original
805 people have browsed it

How to Deploy Flask Applications on Vultr

Deploy secure Flask applications with Gunicorn, Nginx and Let's Encrypt

Flask is a Python framework for building web applications. With Flask, developers can easily define routing, process HTTP requests and responses, and render dynamic content using Jinja2 templates. It also supports extensions that allow developers to integrate features such as database access, form processing, and user authentication.

This article will explain how to use Gunicorn to deploy Flask applications and implement CSRF protection and content security policies (CSP). We will also set up a reverse proxy using Nginx and apply for a free SSL certificate through Let's Encrypt to implement HTTPS.

Deploy on Vultr-optimized cloud instance

  1. Register and log in to the Vultr customer portal.
  2. Navigate to the Products page.
  3. Select "Calculate" from the side menu.
  4. Click the "Deploy Server" button in the center.
  5. Select "Optimized Cloud Computing" as the server type.
  6. Select the server location.
  7. Select Ubuntu 24.04 as the operating system.
  8. Select the right package.
  9. Select any additional features if necessary.
  10. Click "Depend now".

Add demo application code file

Set up Python virtual environment

  1. Installing python3-venv package: sudo apt install python3-venv
  2. Create a virtual environment: python3 -m venv myenv
  3. Activate the virtual environment: source myenv/bin/activate

Add demo application code file

  1. Clone Github repository: git clone https://github.com/mayankdebnath/flask-todo-demo.git
  2. Navigate to project directory: cd flask-todo-demo/sample/
  3. Installing Flask and Gunicorn packages: pip install flask gunicorn
  4. Allow incoming connections to port 5000: ufw allow 5000

Apply CSRF protection and content security policies

Cross-site Request Forgery (CSRF) is a vulnerability that allows an attacker to make unauthorized requests to different websites trusted by the user using a logged-in session on a trusted website. WTForms is a Flask extension that integrates CSRF protection by default to prevent CSRF attacks.

Content Security Policy (CSP) is an additional layer of security for web applications that protect them from malicious attacks. CSP indicates which resources the browser allows to load on a specific web page. Typically, the website administrator configures the CSP by adding special headers to the web page's server response, and the browser then receives the CSP header and understands which resources are allowed to load. Talisman is a Flask extension that simplifies the process of adding CSP to Flask applications.

  1. Installing flask-wtf and talisman packages: pip install flask-wtf talisman
  2. Open app.py file: nano app.py
  3. Edit app.py file to include content security policy:
from talisman import Talisman

talisman = Talisman(
    app,
    content_security_policy={
        'default-src': ['\'self\''],
        'script-src': ['\'self\'', '\'unsafe-inline\'', 'https://code.jquery.com'],
        'style-src': ['\'self\'', '\'unsafe-inline\'', 'https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css', 'https://todoapp5.ddns.net/static/styles.css', 'https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css'],
    },
    force_https=True,
    session_cookie_secure=True,
    frame_options='DENY',
)
Copy after login
  1. In the app.py file, import and configure CSRF protection:
from flask_wtf.csrf import CSRFProtect

app.config['SECRET_KEY'] = 'your_secret_key_here'
csrf = CSRFProtect(app)
csrf._csrf_request_token_key = 'X-CSRFToken'
Copy after login

Save and close the file.

  1. Navigate to templates directory: cd templates
  2. Open index.html file: nano index.html
  3. Edit HTML page to include CSRF configuration:
var csrfToken = $('input[name="csrf_token"]').val();

$.ajaxSetup({
    beforeSend: function(xhr, settings) {
    if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
    xhr.setRequestHeader("X-CSRFToken", csrfToken);
        }
    }
});
Copy after login

Save and close the file. 8. Exit the templates directory: cd ..

Configure Nginx as reverse proxy

Nginx acts as a reverse proxy between the web server and the client. It boots incoming requests based on your request configuration settings. In this section, we will configure the application for reverse proxying for efficient request processing and load balancing. We will also apply for a free SSL certificate from Let's Encrypt to implement HTTPS, thereby protecting the communication between users and web servers.

  1. Login to the Vultr customer portal.
  2. Navigate to the Products page.
  3. Expand the Network drop-down menu from the side menu and select DNS.
  4. Click the "Add Domain Name" button in the center.
  5. Follow the settings steps to add your domain name and select the IP address of the server.
  6. Use your domain registrar to set the following hostnames as the primary and secondary name servers for the domain name: ns1.vultr.com and ns2.vultr.com.
  7. Installing Nginx: sudo apt install nginx
  8. Create a new Nginx configuration file: sudo nano /etc/nginx/sites-available/app.conf
  9. Paste the following configuration into the file:
server {
    listen 80;
    listen [::]:80;

    server_name <your_domain>;

    location / {
        proxy_pass http://127.0.0.1:5000/;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}
Copy after login
  1. Activate virtual host configuration: sudo ln -s /etc/nginx/sites-available/app.conf /etc/nginx/sites-enabled/
  2. Test the Nginx configuration: sudo nginx -t
  3. Reload Nginx: sudo systemctl reload nginx
  4. Allow incoming connections to ports 80 and 443: sudo ufw allow 80/tcp && sudo ufw allow 443/tcp
  5. Installing the certbot package: sudo snap install --classic certbot
  6. Apply for an SSL certificate: sudo certbot --nginx -d example.com -d www.example.com (Replace example.com with your domain name)
  7. Start the Gunicorn server: gunicorn -b 0.0.0.0:5000 app:app
  8. You can now access your Flask app via https://<your_domain></your_domain>.

Do more with Python app on Vultr

  • Containerize Python web applications
  • Install Python and Pip on Ubuntu 24.04
  • Using Vultr cloud inference in Python
  • In-depth discussion of important AI/ML Python packages
  • AI-driven search using Python and Milvus vector databases
  • Execute natural language processing tasks using Python

Conclusion

This article explores how to deploy Flask applications using Nginx reverse proxy and Gunicorn, and implement CSRF protection and CSP. We also protect the security of our applications by adding SSL certificates and enabling HTTPS access.

This article is sponsored by Vultr. Vultr is the world's largest private cloud computing platform. Vultr is loved by developers and has provided flexible and scalable global cloud computing, cloud GPU, bare metal and cloud storage solutions to more than 1.5 million customers in 185 countries. Learn more about Vultr

The above is the detailed content of How to Deploy Flask Applications on Vultr. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template