杰瑞科技汇

如何在Windows上用Python部署Nginx?

Of course! Setting up a web environment with Nginx and Python on Windows is a common and powerful combination. Nginx acts as a high-performance reverse proxy, handling incoming requests and serving static files, while a Python application (like a Flask or Django app) handles the dynamic, back-end logic.

如何在Windows上用Python部署Nginx?-图1
(图片来源网络,侵删)

This guide will walk you through the entire process step-by-step.

Why Use Nginx with Python on Windows?

  • Performance: Nginx is incredibly fast at serving static files (CSS, JavaScript, images) and handling high traffic. It offloads this work from your Python application, allowing it to focus on what it does best.
  • Security: Nginx can act as a shield for your Python application. It handles incoming connections first, filters malicious requests, and can handle SSL/TLS encryption (HTTPS) so your Python app doesn't have to.
  • Scalability: It's much easier to scale a setup with Nginx. You can run multiple instances of your Python app (using Gunicorn, uWSGI, etc.) and have Nginx distribute the load between them.
  • Reliability: If a Python app crashes, Nginx can still serve static files and can be configured to return a user-friendly error page instead of just crashing.

Core Concepts: The Architecture

Here's how the components will work together:

  1. A user makes a request to your domain (e.g., http://myapp.com).
  2. The request hits Nginx, which is listening on port 80 (HTTP) or 443 (HTTPS).
  3. Nginx checks the request URL. If it's for a static file (e.g., /static/style.css), Nginx serves it directly from the file system.
  4. If the request is for a dynamic URL (e.g., /api/data), Nginx forwards the request to the Python application server (like Gunicorn), which is listening on a local port (e.g., 0.0.1:8000).
  5. The Python application processes the request and sends the response back to Nginx.
  6. Nginx then sends the final response back to the user's browser.

Step-by-Step Installation and Configuration

Step 1: Install Python

If you don't have Python installed, get it from the official website: python.org.

Crucial: During installation, make sure to check the box that says "Add Python to PATH". This will allow you to run python and pip from the command line.

如何在Windows上用Python部署Nginx?-图2
(图片来源网络,侵删)

Step 2: Install Nginx for Windows

  1. Download the latest mainline version of Nginx for Windows: nginx.org/en/download.html
  2. You will get a .zip file (e.g., nginx-1.25.3.zip).
  3. Extract the contents to a simple, path-free location like C:\nginx. Avoid spaces and special characters in the path.
  4. To verify the installation, open a Command Prompt, navigate to the C:\nginx directory, and run:
    start nginx

    This will start Nginx as a background process. You can check if it's working by opening your web browser and navigating to http://localhost. You should see the "Welcome to nginx!" page.

Step 3: Create a Simple Python Web Application

We'll use Flask for this example because it's very simple and great for demonstration.

  1. Install Flask: Open a Command Prompt and run:

    pip install Flask
  2. Create the App: Create a new folder for your project, for example, C:\projects\my-python-app. Inside this folder, create a file named app.py and paste the following code into it:

    如何在Windows上用Python部署Nginx?-图3
    (图片来源网络,侵删)
    # C:\projects\my-python-app\app.py
    from flask import Flask, jsonify
    app = Flask(__name__)
    @app.route('/')
    def home():
        return "<h1>Hello from Python (Flask)!</h1><p>This is a dynamic page.</p>"
    @app.route('/api/status')
    def status():
        return jsonify({"status": "OK", "message": "The Python app is running!"})
    if __name__ == '__main__':
        # Note: We will run this with Gunicorn, not the built-in server.
        # The built-in server is for development only.
        app.run()

Step 4: Set Up a Production WSGI Server (Gunicorn)

You should never use Flask's built-in development server in production. It's slow and not designed for multiple users. We'll use Gunicorn, a robust WSGI server for Python.

  1. Install Gunicorn: In your Command Prompt, run:

    pip install gunicorn
  2. Test Gunicorn: Navigate to your project directory in the Command Prompt:

    cd C:\projects\my-python-app

    Now, start Gunicorn, telling it to run your app object from the app.py file, and to listen on 0.0.1:8000:

    gunicorn --workers 1 --bind 127.0.0.1:8000 app:app
    • --workers 1: We start with a single worker process. For production, you'd use more (e.g., --workers 3).
    • --bind 127.0.0.1:8000: Binds the server to your local machine on port 8000.
    • app:app: The first app is the name of the Python file (app.py), and the second app is the name of the Flask application instance inside that file.

    You should see output like this, indicating Gunicorn is running:

    [2025-10-27 10:30:00 +0000] [12345] [INFO] Starting gunicorn 21.2.0
    [2025-10-27 10:30:00 +0000] [12345] [INFO] Listening at: http://127.0.0.1:8000 (12345)
    [2025-10-27 10:30:00 +0000] [12345] [INFO] Using worker: sync
    [2025-10-27 10:30:00 +0000] [12349] [INFO] Booting worker with pid: 12349

    Keep this Gunicorn window open. To test it, open a new browser tab and go to http://127.0.0.1:8000. You should see your "Hello from Python!" page. This confirms your Python app is working correctly behind a proper server.

Step 5: Configure Nginx as a Reverse Proxy

Now for the most important part: telling Nginx how to talk to Gunicorn.

  1. Open the Nginx Configuration File: Navigate to C:\nginx\conf and open nginx.conf in a text editor (like VS Code or Notepad++).

  2. Edit the http Block: Find the http block. Inside it, you'll see a server block that listens on port 80. We will modify this block.

  3. Replace the Default server Block: Replace the existing server block (starting with server { and ending with ) with the following configuration. Read the comments to understand what each part does.

    # C:\nginx\conf\nginx.conf
    # ... (other http settings) ...
    server {
        listen       80;
        server_name  localhost; # Or your domain name if you have one
        # This is the root directory for your project's static files
        # Create a 'static' folder in your project and put CSS/JS/images there
        location /static/ {
            alias C:/projects/my-python-app/static/;
        }
        # This forwards all other requests to the Gunicorn server
        location / {
            # The address of the Gunicorn server
            proxy_pass http://127.0.0.1:8000;
            # These headers are important for passing information to the Python app
            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;
        }
        # It's good practice to have a custom 404 page
        error_page   404              /404.html;
        # Redirect server error pages to the static page /50x.html
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
    # ... (other http settings) ...
  4. Create a Static File (Optional but Recommended): To test the static file serving, create a folder named static inside C:\projects\my-python-app. Inside that, create a file named style.css and add some CSS:

    /* C:\projects\my-python-app\static\style.css */
    body {
        background-color: #f0f8ff;
        font-family: sans-serif;
    }

    Then, in your app.html (if you had one) or by modifying the Flask home() route to return HTML, you could link to this CSS file.

Step 6: Test the Full Setup

  1. Restart Nginx: Your Gunicorn server is still running from Step 4. Now, you need to apply the Nginx configuration changes.

    • Open a new Command Prompt.
    • Navigate to C:\nginx.
    • Execute the following commands to gracefully restart Nginx (it will finish existing requests before reloading the config):
      nginx -s reload
  2. Visit Your Application: Open your web browser and navigate to http://localhost.

    You should now see the "Hello from Python!" page, but this time it's being served by Nginx, which forwarded the request to Gunicorn, which then ran your Flask app. You have successfully set up a reverse proxy!


Managing Services on Windows (Recommended)

Running your servers from command prompt windows is not ideal for a production environment. You want them to run as background services that start automatically when the computer boots.

The best tool for this on Windows is NSSM (Non-Sucking Service Manager).

  1. Download NSSM: Get it from nssm.cc.
  2. Extract NSSM: Unzip the file and copy nssm.exe to a location in your system's PATH (like C:\Windows\System32) or remember its location.
  3. Create a Service for Gunicorn:
    • Open Command Prompt as an Administrator.
    • Run nssm install Gunicorn (or any name you like).
    • A GUI window will appear:
      • Path: Browse to your Python executable (e.g., C:\Users\YourUser\AppData\Local\Programs\Python\Python311\python.exe).
      • Arguments: Enter the command to run Gunicorn: "C:\projects\my-python-app\app.py" app:app --workers 3 --bind 127.0.0.1:8000
      • Startup directory: Set it to your project folder: C:\projects\my-python-app
    • Click Install service.

Now Gunicorn will run as a Windows Service. You can manage it through the services.msc utility (press Win + R, type services.msc, and hit Enter). You can start, stop, and restart your Python app without opening any command prompts. You would do the same for Nginx if you wanted, but it often works fine as-is.

分享:
扫描分享到社交APP
上一篇
下一篇