杰瑞科技汇

ubuntu python ugnix

Of course! It looks like you're asking about setting up a Python web application on Ubuntu using ubuntu, python, and ugnix (which is a common typo for Nginx).

ubuntu python ugnix-图1
(图片来源网络,侵删)

This is a very powerful and popular stack. Nginx acts as a high-performance reverse proxy and web server, while Python (usually with a framework like Flask or Django) handles the application logic.

Here is a complete, step-by-step guide to get you started.


Overview: The Role of Each Component

  1. Ubuntu: The operating system. It's the foundation that everything else runs on.

  2. Python: The programming language. You'll write your web application's code in Python.

    ubuntu python ugnix-图2
    (图片来源网络,侵删)
  3. Nginx (pronounced "Engine-X"): The web server and reverse proxy.

    • Web Server: It serves static files (like CSS, JavaScript, images) directly and very quickly.
    • Reverse Proxy: It receives requests from the internet and forwards them to your Python application. It then takes the response from your app and sends it back to the user. This is crucial because Python web servers (like Gunicorn or uWSGI) are not designed to handle direct traffic from the internet.
  4. WSGI Server (e.g., Gunicorn): A bridge between Nginx and your Python application. Nginx can't "speak" Python, so it needs a WSGI server to translate web requests into a format your Python app can understand and vice-versa. Gunicorn is a popular and easy-to-use choice.

The Architecture Looks Like This:

Internet -> Nginx (Port 80/443) -> Gunicorn (WSGI Server) -> Your Python App (e.g., Flask)

Step-by-Step Guide

Let's build a simple "Hello World" application using the Flask framework.

Step 1: Update Your Server

First, it's always good practice to update your package lists and upgrade existing packages.

ubuntu python ugnix-图3
(图片来源网络,侵删)
sudo apt update
sudo apt upgrade -y

Step 2: Install Python and Pip

We need Python and its package installer, pip.

sudo apt install python3 python3-pip -y

Step 3: Install Nginx

Now, let's install Nginx.

sudo apt install nginx -y

After installation, you can check if it's running by visiting your server's IP address in a web browser. You should see the "Welcome to Nginx!" page. You can also find your server's IP with:

hostname -I

Step 4: Install a Python Virtual Environment

It's a best practice to keep your project's dependencies isolated from the system's Python. We'll use venv for this.

# Install the venv module
sudo apt install python3-venv -y
# Create a directory for your project (e.g., in /var/www)
sudo mkdir -p /var/www/my-python-app
cd /var/www/my-python-app
# Create and activate the virtual environment
python3 -m venv venv
source venv/bin/activate
# Your terminal prompt should now change to show (venv)

Step 5: Create a Simple Python Application

Let's create a simple Flask app. Create a file named app.py.

nano app.py

Paste the following code into the file:

from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
    return "<h1>Hello from my Python App on Nginx!</h1><p>This is served by Nginx, but generated by Python/Flask.</p>"
if __name__ == "__main__":
    # This is only for development. We will use Gunicorn in production.
    app.run(host='0.0.0.0', port=5000)

Save the file (Ctrl+X, then Y, then Enter).

Step 6: Install Flask and Gunicorn

Now, inside your active virtual environment (venv), install the necessary Python packages.

# Install the Flask web framework
pip install Flask
# Install Gunicorn, our WSGI server
pip install gunicorn

Step 7: Test the App with Gunicorn

Before connecting Nginx, let's make sure Gunicorn can run our app.

# Tell Gunicorn to run the 'app' variable from our 'app.py' file
# The -b flag binds it to all network interfaces on port 8000
gunicorn --bind 0.0.0.0:8000 app:app

You should see output indicating Gunicorn is running. If you visit http://YOUR_SERVER_IP:8000 in your browser, you should see your "Hello World" message.

Press Ctrl+C to stop Gunicorn. We don't want it running in the foreground.

Step 8: Configure Nginx as a Reverse Proxy

Now for the most important part. We need to tell Nginx how to forward traffic to our Gunicorn process.

  1. Create a new Nginx configuration file for your app.

    sudo nano /etc/nginx/sites-available/my-python-app
  2. Paste the following configuration into the file:

    server {
        listen 80;
        server_name YOUR_SERVER_IP; # Or your domain name if you have one
        location / {
            # This is where we proxy the request to Gunicorn
            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;
        }
    }

    Important: Replace YOUR_SERVER_IP with your server's actual IP address.

  3. Enable the new site. We create a symbolic link from sites-available to sites-enabled.

    sudo ln -s /etc/nginx/sites-available/my-python-app /etc/nginx/sites-enabled/
  4. Test the Nginx configuration for syntax errors.

    sudo nginx -t

    If it says syntax is ok and test is successful, you're good to go.

  5. Restart Nginx to apply the changes.

    sudo systemctl restart nginx

Step 9: Run Gunicorn in the Background

We need Gunicorn to be running continuously, even after we close our terminal. We can use systemd for this.

  1. Create a systemd service file.

    sudo nano /etc/systemd/system/my-python-app.service
  2. Paste the following configuration. This tells the system how to manage our app.

    [Unit]
    Description=Gunicorn instance to serve my python app
    After=network.target
    [Service]
    User=www-data
    Group=www-data
    WorkingDirectory=/var/www/my-python-app
    Environment="PATH=/var/www/my-python-app/venv/bin"
    ExecStart=/var/www/my-python-app/venv/bin/gunicorn --workers 3 --bind unix:my-python-app.sock app:app
    [Install]
    WantedBy=multi-user.target
    • User/Group: We run Gunicorn as the www-data user, which is what Nginx runs as. This is a security best practice.
    • WorkingDirectory: The directory where your code is.
    • Environment: The path to your virtual environment's bin directory.
    • ExecStart: The command to start Gunicorn. We're using a Unix socket here (my-python-app.sock) which is slightly more efficient than a network port (0.0.1:8000). If you use this, you must also update the Nginx config in the next step.
  3. Update the Nginx config to use the socket. Let's modify the Nginx config file we created earlier.

    sudo nano /etc/nginx/sites-available/my-python-app

    Change the proxy_pass line to:

    proxy_pass http://unix:/var/www/my-python-app/my-python-app.sock;
  4. Start and enable your new service.

    # Reload the systemd daemon to recognize the new service
    sudo systemctl daemon-reload
    # Start the service
    sudo systemctl start my-python-app
    # Enable the service to start automatically on boot
    sudo systemctl enable my-python-app
  5. Check the status of your service.

    sudo systemctl status my-python-app

    It should show active (running).

  6. Restart Nginx one last time.

    sudo systemctl restart nginx

Final Step: Visit Your App!

Now, open your web browser and navigate to http://YOUR_SERVER_IP. You should see your "Hello from my Python App on Nginx!" message, served by the complete stack!


Troubleshooting

  • 502 Bad Gateway: This is the most common error. It means Nginx is trying to talk to Gunicorn, but Gunicorn isn't running or isn't listening where Nginx expects it to be.

    • Check Gunicorn Status: sudo systemctl status my-python-app
    • Check Nginx Error Logs: sudo tail -f /var/log/nginx/error.log
    • Check App Logs: sudo journalctl -u my-python-app -f
  • Permission Denied: If you see permission errors, it's often because the www-data user can't access your project files. Ensure your project files are owned by www-data or that they are readable by everyone (chmod 644 for files, chmod 755 for directories).

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