温馨提示×

如何在Debian上配置Python服务器

小樊
52
2025-08-26 05:36:42
栏目: 云计算

以下是在Debian上配置Python服务器的几种常见方法:

简易HTTP服务器(基于Python内置模块)

  1. 安装Python(若未安装):sudo apt updatesudo apt install python3
  2. 创建Python文件,如simple_server.py,内容为:
import http.server
import socketserver

PORT = 8000
Handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(("", PORT), Handler) as httpd:
    print(f"Serving at port {PORT}")
    httpd.serve_forever()
  1. 运行服务器:python3 simple_server.py,可通过http://localhost:8000访问。

使用Gunicorn和Nginx的Web服务器

  1. 安装必要软件:sudo apt updatesudo apt install python3-pip python3-venv nginx
  2. 创建虚拟环境并激活:python3 -m venv venvsource venv/bin/activate
  3. 安装项目依赖(若有requirements.txt):pip install -r requirements.txt
  4. 安装Gunicorn:pip install gunicorn
  5. 用Gunicorn运行应用,如gunicorn -w 4 -b 127.0.0.1:8000 app:appapp为Flask等框架的应用对象)。
  6. 配置Nginx反向代理,编辑/etc/nginx/sites-available/your_site
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. 启用Nginx配置并重启:sudo ln -s /etc/nginx/sites-available/your_site /etc/nginx/sites-enabledsudo nginx -tsudo systemctl restart nginx
  2. (可选)将Gunicorn设为系统服务以便后台运行。

0