Nginx and Gunicorn
NGINX- Serving Static Content
- Reverse Proxy (forward requests from clients to backend servers)
- load balancing / distributing traffic across multiple servers.
- API Gateway (single entry point for all API requests)
- Caching ( caching frequently requested content)
Unicorn is designed to handle multiple concurrent requests
Sequence of Operation :
- Nginx sits in front of Gunicorn/ unicorn.
- Gunicorn (uWSGI can be used as well) serves your flask app
- 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:
- Docker is installed
- Create Test Folder with below files:
- Dockerfile
- requirments.txt
- 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:
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/
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:
- $ cd to Test Folder
- $ docker run -it --rm -p 5000:5000 -v ${PWD}:/app python:3 bash # cd /app
- cd /apps
- pip install -r requirements.txt
- export FLASK_APP=flask.py
- 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