Deploy Flask App with Nginx, Gunicorn, and Systemd: A Comprehensive Guide
Tags: flask, python, development, webdev
Published: 2023-10-07 13:38:57

**Introduction:**

Before we delve into the deployment process, let’s take a moment to understand the key components and benefits of this setup. Flask is a micro web framework for Python known for its simplicity and flexibility. When deploying a Flask app for production, it’s essential to use a reliable and performant application server and a robust web server. This is where Nginx, Gunicorn, and Systemd come into play.

**Why Nginx, Gunicorn, and Systemd?**

**Nginx:** Nginx is a powerful web server that can also act as a reverse proxy. It excels at handling incoming HTTP requests, load balancing, and serving static files. By using Nginx in front of Gunicorn, we can improve security, performance, and scalability.

**Gunicorn:** Gunicorn is an application server designed to run Python web applications. It serves as the interface between the web server (Nginx) and your Flask app. Gunicorn provides multiple worker processes, ensuring your app can handle multiple simultaneous requests efficiently.

**Systemd:** Systemd is a system and service manager for Linux. It allows us to manage our Gunicorn application as a system service. This means our app can automatically start on boot, restart if it crashes, and be easily monitored.

**Prerequisites**

Before we dive into deployment, let’s ensure you have the necessary prerequisites in place:

1. A Linux server (e.g., Ubuntu, CentOS) with root or sudo access.
2. A Flask application ready for deployment.
3. Python and pip installed on the server.
4. Basic knowledge of Linux terminal commands.

**Step 1: Setting Up the Server**

First, access your server and ensure that it’s up-to-date by running:

`sudo apt update`
`sudo apt upgrade`


**Step 2: Configure Nginx**

Nginx acts as a reverse proxy server, forwarding requests to Gunicorn. Create an Nginx server block configuration file for your Flask app:

`sudo nano /etc/nginx/sites-available/myapp`

Replace `myapp` with a relevant name. Inside the file, configure Nginx like this:

```
server {
    listen 80;
    server_name your_domain.com www.your_domain.com;

    location / {
        proxy_pass http://127.0.0.1:8000;
        include /etc/nginx/proxy_params;
    }
}
```

Save and exit the file, then create a symbolic link:

`sudo ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled`

Test the Nginx configuration:

`sudo nginx -t`

If the test is successful, restart Nginx:

`sudo systemctl restart nginx`

**Step 3: Configure Gunicorn**

Gunicorn serves as the application server for your Flask app. Create a systemd service unit file for Gunicorn:

```
[Unit]
Description=Gunicorn instance to serve myapp
After=network.target

[Service]
User=your_username
Group=your_group
WorkingDirectory=/path/to/your/app
ExecStart=/usr/bin/gunicorn --workers 3 --bind unix:myapp.sock -m 007 wsgi:app

[Install]
WantedBy=multi-user.target
```

Be sure to replace `your_username`, `your_group`, `/path/to/your/app`, and `wsgi:app` with your specific information.


Reload systemd to recognize the new service:

`sudo systemctl daemon-reload`

Start Gunicorn and enable it to start on boot:
```
sudo systemctl start myapp
sudo systemctl enable myapp
```

**Step 4: Deploy Your Flask App**

With Nginx and Gunicorn configured, it’s time to deploy your Flask app. Copy your app files to the server, ensuring they reside in the directory specified in the Gunicorn service unit file.

Navigate to your app’s directory and install any required Python packages:

`pip install -r requirements.txt`

**Step 5: Secure Your Deployment**

To secure your deployment, consider:

- Configuring your firewall to allow only necessary ports (e.g., 80, 443).
- Enabling HTTPS with SSL/TLS certificates.
- Disabling directory indexing in Nginx.

**Conclusion:**

Deploying a Flask app with Nginx, Gunicorn, and Systemd is a robust and scalable approach to take your application from development to production. With careful configuration and security measures, your Flask app will be ready to handle real-world traffic and provide a reliable user experience.

Remember to regularly update your server, Flask app, and dependencies to stay current and secure. With this deployment setup, you’re well-equipped to manage and scale your Flask application effectively. Happy deploying!

Checkout [this article](https://codesolutionshub.com/2023/09/11/gracefully-reloading-flask-app-systemd-service/) to graceful reload flask app to avoid downtime of your application.