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

Colab+ngrok部署Ollama服务器后访问出现403错误求助

问题描述

通过Google Colab和ngrok搭建Ollama服务器,代码如下:

!pip install aiohttp pyngrok

import os
import asyncio
from aiohttp import ClientSession

os.environ.update({'LD_LIBRARY_PATH': '/usr/lib64-nvidia'})

async def run(cmd):

    '''
    run is a helper function to run subcommands asynchronously.
    '''
    print('>>> starting', *cmd)
    p = await asyncio.subprocess.create_subprocess_exec(
      *cmd,
      stdout=asyncio.subprocess.PIPE,
      stderr=asyncio.subprocess.PIPE,
      )

async def pipe(lines):
    async for line in lines:
    print(line.strip().decode('utf-8'))

    await asyncio.gather(
        pipe(p.stdout),
        pipe(p.stderr),
        )

await asyncio.gather(
    run(['ollama', 'serve']),
    run(['ngrok', 'http', '--log', 'stderr', '11434', '--authtoken', '2h8g2xEIRTbSaXraFIRdsdpbACT_6HnpzGYxvEUFcbYyWPhYo', '--host-header="localhost:11434"']),
)

使用Windows客户端连接服务器时,连接正常但始终返回403错误,错误日志:

t=2024-05-29T23:40:22+0000 lvl=info msg="join connections" obj=join id=d124d435c3b1 l=127.0.0.1:11434 r=ip@ [GIN] 2024/05/29 - 23:40:22 | 403 |     295.834µs |   ip@ | HEAD     "/"

尝试过设置OLLAMA_ORIGIN=""但无效,询问Ollama serve是否需要认证或其他解决办法。

问题分析
  1. 代码语法错误:pipe函数中async for循环内的print语句无缩进,且run函数未调用管道处理逻辑,可能导致Ollama服务未正常启动或无法输出日志排查问题。
  2. OLLAMA_ORIGIN配置错误:设置为空字符串无法允许外部访问,需明确指定允许的来源(如*表示允许所有),且必须在启动ollama serve前设置该环境变量。
  3. ngrok参数问题:--host-header参数的引号多余,可能导致头部传递异常,引发Ollama的访问限制。
  4. Ollama默认不需要认证,403错误主要来自跨域访问限制或请求头部不符合要求。
修正方案

1. 修正代码中的语法与环境变量配置

使用以下修正后的代码:

!pip install aiohttp pyngrok

import os
import asyncio

# 设置允许所有外部来源访问Ollama
os.environ['OLLAMA_ORIGIN'] = '*'
os.environ.update({'LD_LIBRARY_PATH': '/usr/lib64-nvidia'})

async def run(cmd):
    print('>>> starting', *cmd)
    p = await asyncio.subprocess.create_subprocess_exec(
        *cmd,
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE,
    )
    
    async def pipe(lines):
        async for line in lines:
            print(line.strip().decode('utf-8'))
    
    # 同时处理子进程的 stdout 和 stderr
    await asyncio.gather(
        pipe(p.stdout),
        pipe(p.stderr),
    )

await asyncio.gather(
    run(['ollama', 'serve']),
    run(['ngrok', 'http', '--log', 'stderr', '11434', '--authtoken', '2h8g2xEIRTbSaXraFIRdsdpbACT_6HnpzGYxvEUFcbYyWPhYo', '--host-header=localhost:11434']),
)

2. 客户端连接注意事项

  • 确保Windows客户端使用ngrok生成的HTTPS域名(如https://xxxx-xx-xx-xx-xx.ngrok-free.app),而非直接访问11434端口。
  • 在Ollama客户端设置中,将服务器地址改为上述ngrok域名,无需添加额外端口(ngrok默认映射443/80到内部11434)。

3. 额外排查步骤

  • 查看Colab的输出日志,确认Ollama服务正常启动(会显示Listening on 127.0.0.1:11434)。
  • 检查ngrok日志,确认隧道连接正常,无报错信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 01:50:13