KenoKivabe

Your Essential Queries

Author
Md Mojahedul Islam
31 Jan, 2023

Run Python Code On Nginx


To run Python code on Nginx, you will need to use a web server gateway interface (WSGI) server, such as Gunicorn or uWSGI, to handle the Python code and interface with Nginx. Here's a general outline of the steps to run Python code on Nginx:

1. Install Nginx and Gunicorn:

  1. sudo apt-get update  
  2. sudo apt-get install nginx gunicorn 

2. Create a Python script, for example "app.py", that will be run on the server:

  1. def application(environ, start_response):  
  2.     status = '200 OK'  
  3.     output = b'Hello World!'  
  4.   
  5.     response_headers = [('Content-type''text/plain'),  
  6.                         ('Content-Length', str(len(output)))]  
  7.     start_response(status, response_headers)  
  8.   
  9.     return [output] 

3. Start Gunicorn on terminal to run the Python script:

  1. gunicorn app:application 

4. Configure Nginx to act as a reverse proxy to Gunicorn by adding the following to the Nginx configuration file, typically located at '/etc/nginx/sites-available/default':

  1. server {  
  2.     listen 80;  
  3.     server_name example.com;  
  4.   
  5.     location / {  
  6.         proxy_pass http://127.0.0.1:8000;  
  7.         proxy_set_header Host $host;  
  8.         proxy_set_header X-Real-IP $remote_addr;  
  9.     }  

5. Restart Nginx to apply the changes:

  1. sudo service nginx restart

With these steps, Nginx will act as a reverse proxy to Gunicorn, which will run the Python script and serve the response to Nginx to be sent to the client.

Share: