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

WSL-Ubuntu中OpenResty脚本无法解析localhost服务报502问题求助

问题分析

错误日志显示localhost could not be resolved (110: Operation timed out),核心问题有两个:

  • 配置的resolver 8.8.4.4是公共DNS,不会解析localhost这类本地回环域名,导致解析超时。
  • WSL-Ubuntu的网络栈与Windows独立,WSL内的localhost指向自身虚拟机,无法直接访问Windows主机上的本地服务。
解决方案

1. 替换resolver为可解析本地域名的DNS

删除resolver 8.8.4.4;,或替换为WSL系统默认DNS(查看/etc/resolv.conf中的nameserver值),示例:

resolver 172.17.0.1; # 替换为你的WSL resolv.conf里的nameserver

2. 正确指向Windows主机服务

方式一:使用Windows局域网IP

  1. 在Windows CMD执行ipconfig,获取以太网/WLAN的IPv4地址(如192.168.3.10)。
  2. 修改nginx配置:
server {
    listen 8082;

    location / {
        set $target '192.168.3.10/foo/hostname'; # 替换为你的Windows IP
        proxy_pass http://$target;
    }
}

方式二:使用WSL2特殊映射地址

WSL2支持通过host.docker.internal直接访问Windows本地服务,配置如下:

server {
    listen 8082;

    location / {
        resolver 127.0.0.11 valid=30s; # WSL2内置DNS解析器
        set $target 'host.docker.internal/foo/hostname';
        proxy_pass http://$target;
    }
}

3. 优化proxy_pass写法(可选)

拆分主机与路径,避免拼接异常:

server {
    listen 8082;

    location / {
        resolver 127.0.0.11 valid=30s;
        set $target_host 'host.docker.internal';
        set $target_uri '/foo/hostname';
        proxy_pass http://$target_host$target_uri;
    }
}
验证

修改配置后重启OpenResty:

sudo openresty -s reload

执行curl localhost:8082验证结果。

内容的提问来源于stack exchange,提问作者mt-user20620859

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 17:31:00