🔍 Introduction

When deploying a Flask web application, it’s best practice to place it behind a reverse proxy to enhance security, enable SSL encryption, and optimize traffic handling. Nginx is a powerful web server that efficiently handles these tasks.

In this guide, we will:

  • Configure Nginx as a reverse proxy for a Flask application running on port 5000.
  • Secure the setup with a custom SSL certificate.
  • Automate the installation and configuration using Ansible on RHEL 8.

By the end, you’ll have a fully automated solution that ensures your Flask app is securely accessible over HTTPS.


🚀 Steps to Automate Installation Using Ansible

1️⃣ Install Nginx on RHEL 8

We need to install Nginx to act as a reverse proxy for our Flask app.

2️⃣ Copy SSL Certificates

The SSL certificate and private key must be placed in the correct directory.

3️⃣ Configure Nginx Reverse Proxy

We will create an Nginx configuration file to route traffic to our Flask application.

4️⃣ Enable and Start Nginx

Ensure that Nginx starts on boot and is running.


📝 Ansible Playbook

Create a new Ansible playbook named nginx_reverse_proxy.yml:

---
- name: Setup Nginx Reverse Proxy for Flask with SSL
  hosts: webserver
  become: true
  vars:
    domain_name: "example.com"
    ssl_cert_path: "/etc/nginx/ssl/example.com.crt"
    ssl_key_path: "/etc/nginx/ssl/example.com.key"
    flask_app_port: 5000

  tasks:
    - name: Install Nginx
      yum:
        name: nginx
        state: present

    - name: Create SSL directory
      file:
        path: /etc/nginx/ssl
        state: directory
        owner: root
        group: root
        mode: '0755'

    - name: Copy SSL certificate
      copy:
        src: files/example.com.crt
        dest: "{{ ssl_cert_path }}"
        owner: root
        group: root
        mode: '0644'

    - name: Copy SSL key
      copy:
        src: files/example.com.key
        dest: "{{ ssl_key_path }}"
        owner: root
        group: root
        mode: '0600'

    - name: Create Nginx reverse proxy config
      template:
        src: templates/flask_nginx.conf.j2
        dest: /etc/nginx/conf.d/flask_app.conf
        owner: root
        group: root
        mode: '0644'
      notify:
        - Restart Nginx

    - name: Ensure Nginx is running and enabled
      service:
        name: nginx
        state: started
        enabled: yes

  handlers:
    - name: Restart Nginx
      service:
        name: nginx
        state: restarted

🔧 Nginx Configuration Template

Create a Jinja2 template file named templates/flask_nginx.conf.j2:

server {
    listen 80;
    server_name {{ domain_name }};

    location / {
        return 301 https://$host$request_uri;
    }
}

server {
    listen 443 ssl;
    server_name {{ domain_name }};

    ssl_certificate {{ ssl_cert_path }};
    ssl_certificate_key {{ ssl_key_path }};

    location / {
        proxy_pass http://127.0.0.1:{{ flask_app_port }};
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

📂 Directory Structure

Ensure your Ansible project has the following structure:

ansible/
│── nginx_reverse_proxy.yml
│── files/
│   ├── example.com.crt
│   ├── example.com.key
│── templates/
│   ├── flask_nginx.conf.j2

🚀 Running the Playbook

To execute the playbook, follow these steps:

  1. Ensure your inventory file (hosts) contains your target server under the [webserver] group.

  2. Copy your SSL certificate and key into the files/ directory.

  3. Run the playbook:

    ansible-playbook -i hosts nginx_reverse_proxy.yml
    

🏆 Key Benefits of Using Ansible for Nginx Configuration

✅ Automated Deployment

Eliminates manual setup, ensuring consistent and repeatable deployments.

✅ Secure SSL Configuration

Custom SSL certificates ensure encrypted communication between the client and server.

✅ Optimized Flask Performance

Nginx efficiently handles incoming requests, reducing the load on the Flask app.

✅ Easy Scalability

The setup can be expanded to multiple servers with minimal changes to the Ansible playbook.


🔄 Comparing Manual vs Automated Nginx Setup

FeatureManual SetupAutomated Setup (Ansible)
Time RequiredHighLow
Error-ProneYesNo
ScalabilityLimitedHigh
SecurityManual SSL setupPre-configured secure setup
MaintenanceManual changes requiredEasily updated via playbook

Ansible simplifies and secures Nginx configuration, making it the preferred choice for managing reverse proxies.


🏁 Conclusion

With this Ansible playbook, we have successfully:

  • Installed and configured Nginx as a reverse proxy for a Flask application.
  • Set up SSL encryption using a custom SSL certificate.
  • Automated the entire deployment process on RHEL 8.

By using Ansible, we eliminate manual configuration, ensuring consistent and error-free deployments.

💬 Are you using Ansible for Nginx automation? Share your experience in the comments!
🚀 Stay ahead in automation with Nginx, Flask, and Ansible!

Subscribe to the YouTube channel, Medium, and Website, X (formerly Twitter) to not miss the next episode of the Ansible Pilot.

Academy

Learn more about Nginx automation with hands-on tutorials in my
Udemy 300+ Lessons Video Course.

BUY the Complete Udemy 300+ Lessons Video Course

My book Ansible By Examples: 200+ Automation Examples For Linux and Windows System Administrator and DevOps

BUY the Complete PDF BOOK to easily Copy and Paste the 250+ Ansible code

Want to support my work? Consider donating:

Patreon Buy me a Pizza