Windows WSL2完美配置:Ubuntu子系统运行Ollama连接本地MySQL

云信安装大师
90
AI 质量分
11 5 月, 2025
4 分钟阅读
0 阅读

Windows WSL2完美配置:Ubuntu子系统运行Ollama连接本地MySQL

引言

在Windows环境下使用WSL2(Windows Subsystem for Linux)运行Ubuntu子系统,可以让我们在不安装虚拟机的情况下享受完整的Linux开发体验。本教程将详细介绍如何配置WSL2下的Ubuntu系统,安装Ollama(一个轻量级的Web框架),并连接Windows本地的MySQL数据库。

准备工作

在开始之前,请确保你的系统满足以下要求:

  • Windows 10版本2004及更高版本或Windows 11
  • 已启用WSL功能
  • 至少4GB可用内存
  • 管理员权限

第一步:安装和配置WSL2

1.1 启用WSL功能

以管理员身份打开PowerShell并运行:

代码片段
# 启用WSL功能
dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart

# 启用虚拟机平台功能
dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart

原理说明:第一个命令启用Windows的Linux子系统支持,第二个命令启用虚拟机平台为WSL2做准备。

1.2 设置WSL2为默认版本

代码片段
wsl --set-default-version 2

1.3 安装Ubuntu发行版

从Microsoft Store安装Ubuntu(建议选择22.04 LTS版本),或者使用命令行:

代码片段
wsl --install -d Ubuntu-22.04

安装完成后,启动Ubuntu并设置用户名和密码。

第二步:优化WSL2配置

2.1 内存限制配置

在Windows用户目录下创建或修改.wslconfig文件(例如:C:\Users\你的用户名\.wslconfig):

代码片段
[wsl2]
memory=4GB   # 限制最大使用内存为4GB
swap=2GB     # swap空间大小
localhostForwarding=true # 允许本地主机转发

注意事项:根据你的机器配置调整内存大小,建议不超过物理内存的50%。

2.2 WSL网络优化

默认情况下,WSL2使用NAT网络。为了能够从Windows访问WSL中的服务,我们需要确保:

代码片段
# PowerShell中查看WSL IP地址
wsl hostname -I

第三步:在Ubuntu中安装Ollama

3.1 更新系统并安装依赖

在Ubuntu终端中执行:

代码片段
sudo apt update && sudo apt upgrade -y
sudo apt install -y python3 python3-pip python3-venv git curl build-essential libssl-dev libffi-dev python3-dev mysql-client libmysqlclient-dev

3.2 创建Python虚拟环境并安装Ollama

代码片段
mkdir ~/ollama_project && cd ~/ollama_project
python3 -m venv venv
source venv/bin/activate

pip install ollama mysql-connector-python cryptography pymysql sqlalchemy flask flask-sqlalchemy flask-migrate flask-login flask-wtf email_validator gunicorn eventlet gevent gevent-websocket psutil requests beautifulsoup4 lxml html5lib python-dotenv markdown bleach pillow werkzeug itsdangerous click jinja2 wtforms blinker zope.interface greenlet pyopenssl cffi pycparser idna charset-normalizer urllib3 certifi soupsieve webencodings pyparsing packaging typing-extensions alembic mako markupsafe sqlparse pytz six deprecated wrapt astroid lazy-object-proxy isort mccabe pylint pylint-flask pylint-flask-sqlalchemy pylint-plugin-utils tomlkit wrapt cached-property deprecated importlib-metadata zipp typing-extensions colorama shellingham click-completion rich prompt-toolkit wcwidth pygments jedi parso ptyprocess pexpect pickleshare traitlets ipython-genutils decorator ipython prompt-toolkit backcall pickleshare simplegeneric wcwidth pygments jedi parso ptyprocess pexpect pickleshare traitlets ipython-genutils decorator ipython prompt-toolkit backcall pickleshare simplegeneric wcwidth pygments jedi parso ptyprocess pexpect pickleshare traitlets ipython-genutils decorator ipython prompt-toolkit backcall pickleshare simplegeneric wcwidth pygments jedi parso ptyprocess pexpect pickleshare traitlets ipython-genutils decorator ipython prompt-toolkit backcall pickleshare simplegeneric wcwidth pygments jedi parso ptyprocess pexpect pickleshare traitlets ipython-genutils decorator ipython prompt-toolkit backcall pickleshare simplegeneric wcwidth pygments jedi parso ptyprocess pexpect pickleshare traitlets ipython-genutils decorator ipython prompt-toolkit backcall pickleshare simplegeneric wcwidth pygments jedi parso ptyprocess pexpect pickleshare traitlets ipython-genutils decorator ipython prompt-toolkit backcall pickleshare simplegeneric wcwidth pygments jedi parso ptyprocess pexpect pickleshare traitlets ipython-genutils decorator ipython prompt-toolkit backcall pickleshare simplegeneric wcwidth pygments jedi parso ptyprocess pexpect pickleshare traitlets ipython-genutils decorator ipython prompt-toolkit backcall pickleshare simplegeneric wcwidth pygments jedi parso ptyprocess pexpect pickleshare traitlets ipython-genutils decorator ipython prompt-toolkit backcall pickleshare simplegeneric wcwidth pygments jedi parso ptyprocess pexpect pickleshare traitlets ipython-genutils decorator ipython prompt-toolkit backcall pickleshare simplegeneric wcwidth pygments jedi parso ptyprocess pexpect pickleshare traitlets ipython-genutils decorator ipython prompt-toolkit backcall pickleshare simplegeneric wcwidth pygments jedi parso ptyprocess pexpect pickleshare traitlets ipython-genutils decorator ipython prompt-toolkit backcall pickleshare simplegeneric wcwidth pygments jedi parso ptyprocess pexpect 

实践经验:这里我们安装了完整的开发环境依赖包,包括数据库连接、Web开发和调试工具。

第四步:配置Windows本地MySQL服务

4.1 Windows端MySQL安装与配置

  1. 下载MySQL Community Server
  2. 安装时选择”Development Computer”类型
  3. 重要:记下root密码或设置一个强密码

4.2 MySQL远程访问配置

编辑MySQL配置文件my.ini(通常在C:\ProgramData\MySQL\MySQL Server X.X):

代码片段
[mysqld]
bind-address = *    # Windows防火墙会处理安全性问题,这里设置为*允许所有IP连接
skip-name-resolve   # WINS解析可能导致问题,跳过名称解析可提高性能

重启MySQL服务:

代码片段
net stop mysqlXX && net start mysqlXX   # XX是你的MySQL版本号如80,57等)

4.3 Windows防火墙设置

允许3306端口入站:

代码片段
New-NetFirewallRule -DisplayName "MySQL Port" -Direction Inbound -LocalPort @('3306') -Protocol TCP -Action Allow -Profile Any -EdgeTraversalPolicy Allow 

第五步:从Ubuntu连接Windows MySQL服务

5.1 Ubuntu端测试连接

首先获取Windows主机的IP地址(不是127.0.0.1):

代码片段
cat /etc/resolv.conf | grep nameserver | awk '{print $2}'

假设得到的IP是172.x.x.x(每次启动可能不同),测试连接:

代码片段
mysql -h <windows_ip> -u root -p 

输入密码后应该能成功连接。

5.2 Ollama项目数据库配置示例代码

创建一个简单的Flask应用来测试数据库连接:

代码片段
# app.py示例代码:
from flask import Flask, jsonify, request, render_template_string, redirect, url_for, flash, session, logging, make_response, send_file, abort, Response, stream_with_context, g, current_app as app_ctx 
from flask_sqlalchemy import SQLAlchemy 
from flask_migrate import Migrate 
import os 
from dotenv import load_dotenv 

load_dotenv() 

app = Flask(__name__) 

# Windows主机的IP可以通过/etc/resolv.conf获取nameserver地址 
windows_ip = os.popen("cat /etc/resolv.conf | grep nameserver | awk '{print $2}'").read().strip() 

app.config['SQLALCHEMY_DATABASE_URI'] = f'mysql+pymysql://root:你的密码@{windows_ip}:3306/ollamadb' 
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False 

db = SQLAlchemy(app) 
migrate = Migrate(app, db) 

class User(db.Model): 
    id = db.Column(db.Integer, primary_key=True) 
    username = db.Column(db.String(80), unique=True, nullable=False) 
    email = db.Column(db.String(120), unique=True, nullable=False) 

@app.route('/init_db') 
def init_db(): 
    try: 
        db.create_all() 
        return 'Database initialized successfully!' 
    except Exception as e: 
        return f'Error initializing database: {str(e)}' 

@app.route('/') 
def index(): 
    return 'Ollama running on WSL connected to Windows MySQL!' 

if __name__ == '__main__': 
    app.run(host='0.0.0.0', port=5000)  

注意事项
1. windows_ip变量自动获取当前Windows主机的IP地址(因为每次启动可能变化)
2. MySQL密码建议通过环境变量传入而非硬编码在代码中

FAQ常见问题解决

Q1: WSL无法启动或报错?

尝试重置WSL:

代码片段
wsl --shutdown && wsl --terminate Ubuntu-22.04 && wsl --unregister Ubuntu-22.04 && wsl --install -d Ubuntu-22.04  

Q2: MySQL连接被拒绝?

检查:
1.Windows防火墙是否放行3306端口
2.MySQL用户是否有远程访问权限(执行 GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION; FLUSH PRIVILEGES;)

Q3: Ollama运行时报编码错误?

在Ubuntu中添加以下环境变量到~/.bashrc:

代码片段
export LANG=C.UTF-8  
export LC_ALL=C.UTF-8  
source ~/.bashrc  

总结

通过本教程我们完成了以下关键步骤:

1.WSL2的安装与优化配置
2.Ubuntu子系统的环境搭建
3.Windows本地MySQL服务的远程访问配置
4.Ollama框架的安装与数据库连接

这种架构的优势在于可以充分利用Windows的GUI环境和Linux的开发环境,同时共享本地数据库资源。对于开发者来说既保持了开发效率又降低了环境复杂度。

原创 高质量