Sign In
Sign In

Deploying Flask Applications with Nginx and Gunicorn on Ubuntu

Deploying Flask Applications with Nginx and Gunicorn on Ubuntu
Hostman Team
Technical writer
Flask
29.05.2024
Reading time: 5 min

This article will describe how to deploy a simple Flask app on Ubuntu using Gunicorn and Nginx.

Prerequisites

To follow this guide, you will need:

  • A cloud server running Ubuntu 20.04 or higher, with Nginx installed.

  • A non-root user with sudo privileges.

  • A domain name with its A record pointing to your cloud server's IP address.

Install components

To begin with, we will install several packages necessary for our application, including pip for managing Python components.

sudo apt update
sudo apt install python3-pip python3-dev build-essential libssl-dev libffi-dev python3-setuptools

Configure Python virtual environment

Virtual environments allow you to separate the dependencies of applications hosted on the same server. 

Install python3-venv:

sudo apt install python3-venv

Create a directory for your Flask project files.

mkdir ~/myproject

Move to this directory:

cd ~/myproject

Now, create a virtual environment:

python3 -m venv myprojectenv

And activate it:

source myprojectenv/bin/activate

In the terminal, you will see that now you're working within the virtual environment:

(myprojectenv)user@host:~/myproject$

Configure the Flask application

Update pip:

pip install -U pip

Download Flask and Gunicorn:

pip install gunicorn flask

Creating an app

Now, let's create a simple Flask application called myproject.py:

nano ~/myproject/myproject.py

Add the code below to the file. 

from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
    return "<h1>Hello<h1>"
if __name__ == "__main__":
 app.run(host='0.0.0.0')

Save the changes and close the file. 

Before launching the app to check if the code works, make sure your firewall allows traffic on port 5000. On Ubuntu, it's probably ufw, so run:

sudo ufw allow 5000

Now we can run our Flask app: 

python myproject.py

Go to http://your_server_ip:5000. The browser should display "Hello!". Go back to the terminal and press CTRL+C to disconnect the Flask server.

Creating a WSGI entry point

Let's move on to creating an entry point to our app: 

nano ~/myproject/wsgi.py

Add the following code to the file:

from myproject import app
if __name__ == "__main__":
 app.run()

Save changes.

Configure Gunicorn

Before continuing, verify the Gunicorn server can serve our program correctly.

Go to the project directory:

cd ~/myproject

And run the command:

gunicorn --bind 0.0.0.0:5000 wsgi:app

You should see a similar output:

[2024-05-23 15:52:19 +0000] [9211] [INFO] Starting gunicorn 20.1.0
[2024-05-23 15:52:19 +0000] [9211] [INFO] Listening at: http://0.0.0.0:5000 (9211)
[2024-05-23 15:52:19 +0000] [9211] [INFO] Using worker: sync
[2024-05-23 15:52:19 +0000] [9213] [INFO] Booting worker with pid: 9213

Again, go to http://your_server_ip:5000 and verify that the "Hello!" message is displayed.

In the terminal, press Ctrl+C to stop the application and deactivate the virtual environment:

deactivate

To be able to launch Gunicorn automatically, let's create a systemd unit file:

sudo nano /etc/systemd/system/myproject.service

And add the following content to it:

[Unit]
Description=Gunicorn instance for myproject
After=network.target
[Service]
User=username
Group=www-data
WorkingDirectory=/home/username/myproject
Environment= "PATH=/home/username/myproject/myprojectenv/bin"
ExecStart=/home/username/myproject/myprojectenv/bin/gunicorn --workers 3 --bind unix:myproject.sock -m 007 wsgi:app
[Install]
WantedBy=multi-user.target

Save the changes and close the file. Now you can start the Gunicorn service and enable it so it runs at boot: 

sudo systemctl start myproject
sudo systemctl enable myproject

Check the status to verify that Gunicorn is running: 

sudo systemctl status myproject

Configure Nginx

Let's move on to working with the Nginx web server. First, create a configuration file in the sites-available directory:

sudo nano /etc/nginx/sites-available/myproject

Add the following directives to the file: 

server {
 listen 80;
 server_name your_domain www.your_domain;
 location/{
 include proxy_params;
 proxy_pass http://unix:/home/username/myproject/myproject.sock;
 }
}

And save the changes. Apply the new configuration:

sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled

Next, add the www-data user to the current user group:

sudo usermod -a -G ${USER} www-data

Check the Nginx configuration:

sudo nginx -t

If everything is fine, restart the web server:

sudo nginx -s reload

Complete the setup by adjusting the firewall settings. For example, we no longer need the rule about access through port 5000; we can safely delete it. Instead, add another rule to open a connection to the Nginx server:

sudo ufw delete allow 5000
sudo ufw allow 'Nginx Full'

Try accessing your server from a browser via http://your_domain. The program shouls display the "Hello!" message.

Install an SSL certificate

Finally, let's install an SSL certificate to secure traffic. 

We will issue a Let's Encrypt SSL using Certbot. The recommended way to install Certbot is through snap. More information can be found in the official Certbot documentation.

Run the command below to ensure you are using the latest version of snapd:

sudo snap install core; sudo snap refresh core

If you previously installed any Certbot packages using the apt package manager, remove them with the command:   

sudo apt-get remove certbot

Install Certbot via snap:

sudo snap install --classic certbot

Execute the following command to ensure that the certbot command can be run:

sudo ln -s /snap/bin/certbot /usr/bin/certbot

Obtain the certificate and automatically make the necessary changes to the Nginx configuration:

sudo certbot --nginx

Certbot will automatically update the certificate. You can test the update by running the command:

sudo certbot renew --dry-run

Try going to your domain via HTTPS (https://your_domain) to make sure the secure connection works. 

Conclusion

In this tutorial, we deployed a simple Flask app on an Ubuntu server using the Python virtual environment, configured Gunicorn and Nginx, and secured our application with an SSL certificate.

Flask
29.05.2024
Reading time: 5 min

Similar

Flask

How to Handle Incoming Request Data in Flask

Websites where you watch videos, read news or chat with friends operate on a client-server architecture. The client (e.g., a browser) sends a request to the server, and based on that request, the server responds—usually by sending an HTML document back. When we look under the hood of how websites work, request handling follows a general logic: Accept the request. Choose a request handler. Execute the handler. Send a response back to the client. A framework is a developer tool used to implement this logic. Flask is a microframework for building websites using Python. The term "micro" means that Flask provides a small, lightweight set of tools that are still sufficient for creating most websites. Flask is great for building APIs or websites hosted on cloud servers. In this article, we'll create a Flask application and explore how to process incoming requests. Getting Started We'll use PyCharm + pipenv on Windows 10. There are plenty of tutorials online for installing this setup on other operating systems, but here’s how to install it on Windows 10. Install Python. Visit the official website www.python.org/downloads, choose the Python version for your OS, and follow the installer instructions. Install pipenv. Pipenv is a package for managing virtual environments in Python. To install it, open the Windows command prompt and run this command: py -m pip install pipenv Install PyCharm. PyCharm is an IDE (Integrated Development Environment) for Python. Download and install it from the official site www.jetbrains.com/pycharm, choosing either the Community or Professional version. Creating a Project In PyCharm, click "File" → "New Project" and specify the following: Project directory Virtual environment settings Path to the Python interpreter Path to pipenv executable After setting everything up, click "Create." Installing Flask After creating the project, open the terminal at the bottom of PyCharm and run: pip install flask If everything is set up correctly, Flask will install. If you encounter an error like "Execution of scripts is disabled," open PowerShell as an administrator and run this command: Set-ExecutionPolicy RemoteSigned Then type [A] to allow the script to run. Working with URLs Once the necessary components are installed, let's start interacting with Flask. First, import Flask: from flask import Flask We’ll write a small Flask application to demonstrate working with URL requests: from flask import Flask app = Flask(__name__) @app.route("/hostman") def hostman(): return "This is the /hostman page" @app.route("/blog") def blog(): return "This is the /blog page" @app.route("/cloud") def cloud(): return "This is the /cloud page" if __name__ == "__main__": app.run() Explanation: First, we import Flask. We then create an instance of the Flask class, app. We use the .route decorator to assign functions to specific URLs. Finally, we run the application using app.run(). Running the Application In the terminal, you will see the local address of your site (127.0.0.1:5000). You might see nothing if you navigate to this address because we still need to define a handler for the root URL (/). However, if you visit: 127.0.0.1:5000/hostman 127.0.0.1:5000/blog 127.0.0.1:5000/cloud You’ll see responses for these routes. Flask automatically logs each request in the console. Handling GET Requests You can pass various parameters to the server via a GET request. For instance, consider this URL: hostman.com/blog?framework=flask&language=python&version=3.10 Here, the parameters are passed as key-value pairs after the question mark (?): framework=flask language=python version=3.10 Let’s write a function, get_example(), to extract these parameters in Flask: from flask import request @app.route("/get_example") def get_example(): framework = request.args.get('framework') language = request.args.get('language') version = request.args.get('version') return f"language = {language}; framework = {framework}; version = {version}" This code: Imports the request class and its methods. Uses the .args.get() method to extract query parameters. Returns the extracted values in the response. If you go to the URL: http://127.0.0.1:5000/get_example?language=python&framework=flask&version=3.10 The application will correctly process the GET request and display the extracted parameters. Handling POST Requests By default, .route() handles only GET requests. Flask can also handle POST requests. Let’s add a simple login form that accepts a username and password: @app.route('/authorization', methods=['GET', 'POST']) def authorization(): if request.method == 'POST': login = request.form.get('Login') password = request.form.get('Password') if login == "admin" and password == "admin": return "Correct" else: return "Incorrect" return ''' <form method="POST"> <div><label>Login: <input type="text" name="Login"></label></div> <div><label>Password: <input type="text" name="Password"></label></div> <input type="submit" value="Enter"> </form>''' Explanation: The decorator handles both GET and POST requests. On a GET request, a form for login and password is displayed. On a POST request (when the form is submitted), the credentials are checked. If correct, it returns "Correct"; otherwise, it is "Incorrect." Visit the URL: 127.0.0.1:5000/authorization If you enter "admin" as both login and password, you will see "Correct." Otherwise, you’ll see "Incorrect." Full Code Example from flask import Flask, request app = Flask(__name__) @app.route("/hostman") def hostman(): return "This is the /hostman page" @app.route("/blog") def blog(): return "This is the /blog page" @app.route("/cloud") def cloud(): return "This is the /cloud page" @app.route("/get_example") def get_example(): framework = request.args.get('framework') language = request.args.get('language') version = request.args.get('version') return f"language = {language}; framework = {framework}; version = {version}" @app.route('/authorization', methods=['GET', 'POST']) def authorization(): if request.method == 'POST': login = request.form.get('Login') password = request.form.get('Password') if login == "admin" and password == "admin": return "Correct" else: return "Incorrect" return ''' <form method="POST"> <div><label>Login: <input type="text" name="Login"></label></div> <div><label>Password: <input type="text" name="Password"></label></div> <input type="submit" value="Enter"> </form>''' if __name__ == "__main__": app.run() Conclusion This article explored how to handle GET and POST requests in Flask. However, it's important to remember that security is critical when handling client data. Always validate and sanitize input to prevent malicious attacks. Prevention is the best way to protect your server from unwanted consequences.
15 October 2024 · 6 min to read

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start.
Email us
Hostman's Support