Sunday, November 22, 2020

Nginx and Gunicorn

Nginx and Gunicorn

NGINX
  1. Serving Static Content
  2. Reverse Proxy (forward requests from clients to backend servers)
  3. load balancing / distributing traffic across multiple servers.
  4. API Gateway (single entry point for all API requests)
  5. Caching ( caching frequently requested content)

Unicorn (Web Server Gateway Interface - WSGI)
Unicorn is designed to handle multiple concurrent requests 

Ingress is a Kubernetes-specific solution (similar to Nginx) 

Sequence of Operation :


  1. Nginx sits in front of Gunicorn/ unicorn.
  2. Gunicorn (uWSGI can be used as well) serves your flask app
  3. For example, if the incoming request is an http request Nginx redirects it to gunicorn, if it is for a static file, it serves it itself.


Example 

Pre-Req: 

  1. Docker is installed
  2. Create Test Folder with below files:
    1. Dockerfile
    2. requirments.txt
    3. flask.py

---Dockerfile------
FROM python:3
WORKDIR /app
COPY . .
RUN pip install -r requirements.txt
CMD ["gunicorn", "--workers=1", "--bind=0.0.0.0:5000", "flask:app"]

------requirments.txt------
flask==1.1.1
gunicorn

------flask.py------
from flask import Flask, request
app = Flask(__name__)
@app.route('/')
def hello_world() -> str: return "Hello world"
if __name__ == '__main__':app.run(debug=True, host='0.0.0.0')

------------------------------------

Steps:
  1. $ cd to Test Folder
  2. $ docker run -it --rm -p 5000:5000 -v ${PWD}:/app python:3 bash # cd /app
  3. cd /apps
  4. pip install -r requirements.txt
  5. export FLASK_APP=flask.py
  6. gunicorn --bind=0.0.0.0:5000 --workers=1 flask:app

Ref
https://stackoverflow.com/questions/43044659/what-is-the-purpose-of-using-nginx-with-gunicorn
https://rahmonov.me/posts/run-a-django-app-with-gunicorn-in-ubuntu-16-04/

No comments:

Post a Comment