Technology Sharing

Deploy Python Web Services in Linux Environment

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

insert image description here

"Girl, it depends on luck if we meet again. Don't pretend you don't know each other, and don't be afraid to say "long time no see"..."

To deploy a backend API written in Python to a Linux environment, you can follow the detailed steps below. This article will cover environment preparation, API writing, using Gunicorn as a WSGI server, configuring Nginx as a reverse proxy, and using Systemd to manage services.

1. Prepare the environment

Install Python

If Python is not installed on your Linux system, you can install it using the following command:

sudo yum update
sudo yum install python3 python3-pip
  • 1
  • 2

Install Necessary Libraries

Assuming you are using Flask or Django framework, install the required libraries first:

pip3 install flask  # 如果你使用的是 Flask
pip3 install django  # 如果你使用的是 Django
  • 1
  • 2

2. Write API code

Flask Example

Create a simple Flask API example:

from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/api', methods=['GET'])
def api():
    return jsonify({'message': 'Hello, World!'})

if __name__ == '__main__':
    app.run(host='0.0.0.0')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

Django example

Create a new Django project and add the API:

django-admin startproject myproject
cd myproject
django-admin startapp myapp
  • 1
  • 2
  • 3

exist myapp/views.py Add the API view:

from django.http import JsonResponse
def api(request):
    return JsonResponse({'message': 'Hello, World!'})
  • 1
  • 2
  • 3

exist myproject/urls.py Configure URL routing in:

from django.contrib import admin
from django.urls import path
from myapp.views import api

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', api),
]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

3. Method 1 - Direct Start

To quickly start an application in a development or test environment, you can run:

python main.py 或者 nohup python main.py
  • 1
Django example:

Django has its own development server, which you can start with the following command:

python manage.py runserver 0.0.0.0:8000
  • 1

Gunicorn is recommended for production environments. To ensure the performance and stability of your application in a production environment, it is recommended that you use Gunicorn.Gunicorn As an application server, it handles the execution of Python code and multi-process management.

4. Method 2 - Configure Gunicorn (WSGI server for production environment)

Install Gunicorn

Install Gunicorn:

pip3 install gunicorn
  • 1

Running the Flask Application

Run the Flask application using Gunicorn:

gunicorn --bind 0.0.0.0:8000 app:app
  • 1

Running the Django application

Run the Django application using Gunicorn:

gunicorn --bind 0.0.0.0:8000 myproject.wsgi:application
  • 1

5. Use Nginx as a reverse proxy

Install Nginx

Install Nginx:

sudo yum install nginx
  • 1

Configure Nginx

Editing the Configuration File /etc/nginx/sites-available/default

server {
    listen 80;
    server_name your_domain_or_IP;

    location / {
        proxy_pass http://127.0.0.1:8000;
        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;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

Reload the Nginx configuration:

sudo systemctl restart nginx
  • 1

6. Managing Gunicorn with Systemd

Create Systemd service file

Create a new Systemd service file:

sudo vim /etc/systemd/system/myproject.service
  • 1

Add service configuration

Flask Application
[Unit]
Description=Gunicorn instance to serve myproject
After=network.target

[Service]
User=your_user
Group=www-data
WorkingDirectory=/path/to/your/project
ExecStart=/usr/bin/gunicorn --workers 3 --bind unix:myproject.sock -m 007 app:app

[Install]
WantedBy=multi-user.target
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
Django Application

Will ExecStart Change the line to:

ExecStart=/usr/bin/gunicorn --workers 3 --bind unix:myproject.sock -m 007 myproject.wsgi:application
  • 1

Start and enable the service

Start and enable the service:

sudo systemctl start myproject
sudo systemctl enable myproject
  • 1
  • 2

7. Check service status

Make sure the service is running:

sudo systemctl status myproject
  • 1

In this way, your Python API is successfully deployed to the Linux environment. You can adjust the configuration as needed to suit your specific project requirements. I hope this detailed guide is helpful to you!