You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Apache与Gunicorn运行多版本Python?配置后Apache仍用Python2.7

解决Apache仍使用Python 2.7而非虚拟环境Python 3.4的问题

这种情况大概率是Apache的WSGI模块绑定了系统默认的Python 2.7,或者你的虚拟主机配置没有正确关联到Python 3.4的环境/Gunicorn服务。下面分两种常见场景给出解决方案:

场景1:你通过mod_wsgi直接让Apache运行Python应用

如果你的配置是让Apache通过mod_wsgi加载Python代码,那问题出在mod_wsgi的版本上——系统默认安装的mod_wsgi通常是针对Python 2编译的。

解决步骤:

  • 先卸载系统自带的Python 2版本mod_wsgi:
    # Debian/Ubuntu系统
    sudo apt remove libapache2-mod-wsgi
    # CentOS/RHEL系统
    sudo yum remove mod_wsgi
    
  • 激活你的Python 3.4虚拟环境,然后安装适配Python 3的mod_wsgi:
    source /path/to/your/python3.4/venv/bin/activate
    pip install mod_wsgi
    
  • 生成mod_wsgi的Apache配置片段:
    mod_wsgi-express module-config
    
    执行后会输出类似下面的内容,把这些行添加到你的Apache主配置文件(比如/etc/apache2/apache2.conf)或者虚拟主机配置中:

    LoadModule wsgi_module "/path/to/venv/lib/python3.4/site-packages/mod_wsgi/server/mod_wsgi-py34.cpython-34m.so"
    WSGIPythonHome "/path/to/venv"

  • 确保你的WSGI应用文件(比如wsgi.py)开头激活虚拟环境:
    activate_this = '/path/to/your/venv/bin/activate_this.py'
    with open(activate_this) as file_:
        exec(file_.read(), dict(__file__=activate_this))
    
  • 重启Apache服务:
    # Debian/Ubuntu
    sudo systemctl restart apache2
    # CentOS/RHEL
    sudo systemctl restart httpd
    

场景2:你用Apache反向代理Gunicorn(Gunicorn跑在8100端口)

如果你的架构是Gunicorn运行Python 3.4应用,Apache作为反向代理转发请求到8100端口,那问题可能出在虚拟主机的反向代理配置没正确设置,导致Apache没把请求转发给Gunicorn。

解决步骤:

  • 确保你的Apache启用了反向代理模块:
    # Debian/Ubuntu
    sudo a2enmod proxy proxy_http
    # CentOS/RHEL
    sudo yum install mod_proxy mod_proxy_http
    
  • 修改你的虚拟主机配置,添加反向代理规则:
    <VirtualHost *:80>
        ServerName your-domain.com
    
        ProxyPass / http://localhost:8100/
        ProxyPassReverse / http://localhost:8100/
    
        # 可选:添加日志配置
        ErrorLog ${APACHE_LOG_DIR}/your-domain-error.log
        CustomLog ${APACHE_LOG_DIR}/your-domain-access.log combined
    </VirtualHost>
    
  • 重启Apache和Gunicorn服务,确保Gunicorn是在Python 3.4虚拟环境中启动的:
    # 重启Apache
    sudo systemctl restart apache2
    # 重启Gunicorn(确保在虚拟环境中执行)
    source /path/to/venv/bin/activate
    pkill gunicorn
    gunicorn --workers=3 --bind=0.0.0.0:8100 your_app.wsgi:application &
    

验证方法

  • 查看Apache错误日志,检查是否有Python版本相关的报错:
    # Debian/Ubuntu
    tail -f /var/log/apache2/error.log
    # CentOS/RHEL
    tail -f /var/log/httpd/error_log
    
  • 在你的Python应用中添加一个输出Python版本的接口,访问后确认返回的是3.4.x:
    from flask import Flask
    import sys
    
    app = Flask(__name__)
    
    @app.route('/python-version')
    def show_version():
        return f"Python Version: {sys.version}"
    
    if __name__ == '__main__':
        app.run()
    

内容的提问来源于stack exchange,提问作者shaswa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:54:41