Dify添加ollama模型失败:NewConnectionError: Failed to establish a new connection
问题描述
Dify 配置 ollama 模型时返回以下报错,无法连接到 ollama 服务:
An error occurred during credentials validation: HTTPConnectionPool(host=‘xxx ip’, port=11434): Max retries exceeded with url: /api/chat (Caused by NewConnectionError(‘<urllib3.connection.HTTPConnection object at 0x7ff6c00d4440>: Failed to establish a new connection: [Errno 111] Connection refused’))
添加 ollama 模型时的报错截图:
问题排查
该问题主要是无法外部访问 ollama 服务引起。
以下排查命令主要基于 ubuntu 系统,Dify 和 ollama 都配置在 ubuntu 服务器上,Ollama 以 systemd 服务的形式运行。
第一步、检查ollama服务是否运行
首先在ollama部署的服务器上,用命令行验证 ollama 服务是否运行:
curl http://localhost:11434
结果显示:Ollama is running
证明ollama服务在运行状态。
如果 ollama 服务未运行,可以用以下命令启动服务:
sudo systemctl daemon-reload
sudo systemctl enable ollama
第二步、测试外部访问 ollama
假设ollama部署的服务器ip为:SERVER_IP,从外部通过 curl 命令访问该地址 curl http://SERVER_IP:11434/
,或者直接在浏览器访问该地址,查看能否访问ollama服务。
curl 返回结果显示,外部访问 ollama 服务失败:
curl: (7) Failed to connect to SERVER_IP port 11434 after 2050 ms: Could not connect to server
第三步、修改 ollama 服务配置
查看及编辑 ollama 服务文件:
sudo vim /etc/systemd/system/ollama.service
在 [Service] 中修改 OLLAMA_HOST
和 OLLAMA_ORIGINS
变量。
[Unit]
Description=Ollama Service
After=network-online.target[Service]
ExecStart=/usr/bin/ollama serve
User=ollama
Group=ollama
Restart=always
RestartSec=3
Environment="PATH=$PATH"
Environment="OLLAMA_HOST=0.0.0.0:11434" #允许外部设备访问
Environment="OLLAMA_ORIGINS=*" #允许跨域访问[Install]
WantedBy=multi-user.target
OLLAMA_HOST
环境变量通常用来指定 Ollama 服务监听的 IP 地址。默认情况只监听 127.0.0.1
(即本地回环接口),只有本机可以访问该服务。如果需要让外部其他设备也能访问到这个服务,将其设置为 0.0.0.0
,这样 Ollama 就会监听所有可用的网络接口。
OLLAMA_ORIGINS
环境变量设置为 *,这表示接受所有来源的请求,用于配置跨域访问。
完成上述配置后,重启 Ollama 服务以使新的环境变量生效。
sudo systemctl restart ollama
第四步、配置防火墙
在部署 ollama 的服务器上允许 11434 端口:
sudo ufw allow 11434/tcp
sudo ufw reload
第五步、重新验证
利用 curl 从外部访问 ollama 模型列表:
curl http://SERVER_IP:11434/api/tags
如果能返回 json 结果说明成功。
重新在 Dify 模型配置页面里添加 ollama 模型,模型名称参考 json 返回列表中的 model 参数。
添加成功以后,就可以在 Dify 中调用新模型了。