本地部署 Dify 无法连接本地 Ollama 问题
·
本地部署 Dify 无法连接本地 Ollama 问题
问题描述
在 Dify 本地部署环境中,尝试接入本地运行的 Ollama 模型服务时,系统报错如下:
vbnet复制编辑An error occurred during credentials validation:
HTTPConnectionPool(host='0.0.0.0', port=11434):
Max retries exceeded with url: /api/chat
(Caused by NewConnectionError: Failed to establish a new connection: [Errno 111] Connection refused)
同时,在 Dify API 容器内运行以下命令时也无法获取模型:
bash复制编辑curl http://127.0.0.1:11434/api/ps # Connection refused
curl http://0.0.0.0:11434/api/ps # 无法访问
原因分析
- Ollama 默认监听地址是
127.0.0.1:- 宿主机可以访问,但 Docker 容器内无法访问宿主机的
127.0.0.1。
- 宿主机可以访问,但 Docker 容器内无法访问宿主机的
- 配置错误使用了
0.0.0.0作为请求地址:0.0.0.0是监听地址,不能用来发起连接。- 导致 Dify 报错无法建立 API 请求连接。
解决方案
步骤一:修改 Ollama 启动方式
让 Ollama 监听所有 IP 地址:
powershell复制编辑# 在 PowerShell 启动 Ollama 服务前设置监听地址
$Env:OLLAMA_HOST = "0.0.0.0:11434"
ollama serve
步骤二:修改 Dify 配置
方式 A:修改 .env 文件
env
复制编辑
OLLAMA_API_URL=http://host.docker.internal:11434
方式 B:修改 docker-compose.yaml
yaml复制编辑services:
api:
environment:
- OLLAMA_API_URL=http://host.docker.internal:11434
步骤三:重启 Dify 容器使配置生效
powershell复制编辑cd C:\Users\24872\dify\docker
docker-compose down
docker-compose up -d
步骤四:激活 Ollama 模型
运行一次调用以激活模型:
powershell复制编辑curl -X POST http://127.0.0.1:11434/api/generate `
-H "Content-Type: application/json" `
-d '{"model": "llama2:7b", "prompt": "你好"}'
激活后,通过以下命令确认容器内能识别模型:
bash
复制编辑
docker exec -it docker-api-1 curl http://host.docker.internal:11434/api/ps
返回内容中应包含已激活模型。
最终结果
- Dify 成功连接并调用本地 Ollama 服务。
- 模型已被识别并可用于任务执行。
更多推荐



所有评论(0)