Traefik无法访问本地Golang应用,返回HTTP 404求助
Traefik v3.2.3 反向代理Go应用返回404排查
我在本地Ubuntu 22.10机器上运行Traefik v3.2.3(二进制版本),未使用Docker、K8s等容器编排工具。Traefik仪表盘可正常访问,但访问我的简单Golang应用时始终返回HTTP 404,请求排查问题。
环境栈
- Ubuntu 22.10
- Traefik v3.2.3(二进制版本)
- 简单Golang Web应用
应用源码
package main import ( "log" "net/http" ) func responseURLHandler(w http.ResponseWriter, r *http.Request) { log.Printf("Host: %s | Method: %s | Path: %s\n", r.Host, r.Method, r.URL) } func main() { http.HandleFunc("/", responseURLHandler) log.Println("starting....") http.ListenAndServe(":8000", nil) log.Println("stopping....") }
Traefik配置文件(traefik_lab.yaml)
############################# # # Configuration for Traefik. # ############################# ############################# # Global configuration ############################# global: checkNewVersion: true sendAnonymousUsage: true ############################# # Traefik UI ############################# serversTransport: insecureSkipVerify: true ############################# # Traefik logs configuration ############################# log: level: INFO # format: json ############################# # Access logs configuration ############################# accessLog: {} # Sets the file path for the access log. If not specified, stdout will be used. # Intermediate directories are created if necessary. # # Optional # Default: os.Stdout # # filePath: /path/to/log/log.txt # Format is either "json" or "common". # # Optional # Default: "common" # # format: json ############################# # API and dashboard configuration ############################# # Enable API and dashboard # # Optional # api: # Enable the API in insecure mode # # Optional # Default: false # insecure: true # Enabled Dashboard # # Optional # Default: true # # dashboard: false ############################# # EntryPoints configuration ############################# entryPoints: web: address: ":8888" asDefault: true http: routers: app-router: service: app-service entryPoints: - "web" services: app-service: loadBalancer: servers: - url: http://localhost:8000/
测试步骤
- 启动Go应用:
go run main.go - 启动Traefik:
traefik --configfile=traefik_lab.yaml - 发送测试请求:
curl http://localhost:8888/api/xxx/111
测试结果
Traefik访问日志返回404:
::1 - - [26/Dec/2024:12:09:32 +0000] "GET /api/xxx/111 HTTP/1.1" 404 19 "-" "-" 1 "-" "-" 0ms
问题原因及解决方法
问题根源
Traefik路由配置中缺少请求匹配规则,Traefik无法识别哪些请求需要转发到app-service服务,默认不会自动将所有请求路由到定义的服务。
修复后的配置
修改http.routers.app-router节点,添加rule字段指定匹配规则,示例为匹配所有路径:
http: routers: app-router: service: app-service entryPoints: - "web" rule: "PathPrefix(`/`)" # 添加该行,匹配所有路径前缀 services: app-service: loadBalancer: servers: - url: http://localhost:8000/
可选匹配规则
根据需求可调整rule实现精细路由:
- 仅转发
/api开头的请求:rule: "PathPrefix(/api)" - 匹配特定域名:
rule: "Host(myapp.local)"(需配置本地Hosts映射)
验证步骤
- 重启Traefik加载新配置
- 再次发送测试请求,此时请求会转发到Go应用,Go应用日志会打印请求信息,Traefik返回200状态码。
内容的提问来源于stack exchange,提问作者AlTheOne
相关产品推荐
相关产品推荐

