如何无需反向代理在Ubuntu部署Golang Fiber API并无端口域名访问?
部署Golang Fiber API到Ubuntu VPS并实现无端口域名访问
一、无需反向代理实现无端口访问的方法
默认HTTP请求使用80端口、HTTPS使用443端口,只要让你的Fiber API直接监听这两个端口之一,就能实现无端口访问。但需要注意低端口(1024以下)的权限限制:
方法1:以root用户运行API
在Fiber代码中设置监听80或443端口:app := fiber.New() // HTTP监听80端口 log.Fatal(app.Listen(":80")) // 若启用HTTPS,需配置证书文件路径 // log.Fatal(app.ListenTLS(":443", "cert.pem", "key.pem"))直接用root用户启动二进制文件即可,但不推荐长期以root身份运行服务,存在安全风险。
方法2:给二进制文件授权低端口监听权限
使用cap_net_bind_service能力,让普通用户的二进制文件也能监听1024以下端口:setcap 'cap_net_bind_service=+ep' /path/to/your-api-binary之后用普通用户运行API,代码中同样监听
:80或:443即可。
二、解决Nginx反向代理失效的步骤
如果选择用Nginx做反向代理,按以下步骤排查和配置:
1. 确认基础依赖状态
- 检查域名解析:在本地执行
nslookup api.otherdomain.com,确认返回的IP是你的VPS公网IP。 - 检查防火墙规则:确保VPS开放80/443端口(对外提供HTTP/HTTPS服务):
ufw allow 80/tcp ufw allow 443/tcp ufw reload - 检查Fiber API状态:
- 确认API监听的是
0.0.0.0:端口(而非仅127.0.0.1,否则Nginx无法访问),代码中设置为app.Listen(":3000")(示例端口3000)。 - 用命令验证API是否正常监听:
能看到对应进程信息说明监听正常。ss -tulpn | grep :3000
- 确认API监听的是
2. 配置Nginx反向代理
- 创建站点配置文件:
写入以下配置(替换nano /etc/nginx/sites-available/api.otherdomain.com3000为你的API实际监听端口):server { listen 80; server_name api.otherdomain.com; location / { proxy_pass http://localhost:3000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } - 启用配置文件:
ln -s /etc/nginx/sites-available/api.otherdomain.com /etc/nginx/sites-enabled/ - 检查配置合法性:
输出nginx -ttest is successful说明配置无错误。 - 重启Nginx生效:
systemctl restart nginx
3. 排查异常情况
如果配置后仍无响应,通过日志定位问题:
- 查看Nginx错误日志:
若出现tail -f /var/log/nginx/error.logconnection refused,说明Nginx无法连接到API,检查API是否运行、监听端口是否正确。 - 查看Nginx访问日志:
若没有请求记录,说明域名解析或防火墙存在问题;若有记录但返回5xx状态码,检查API服务运行状态。tail -f /var/log/nginx/access.log
4. 可选:配置HTTPS和服务自启
- 用Certbot自动配置HTTPS:
按照提示完成配置,会自动将HTTP请求跳转至HTTPS。apt install certbot python3-certbot-nginx certbot --nginx -d api.otherdomain.com - 用systemd管理API服务(实现开机自启、异常自动重启):
创建服务文件:
写入内容(替换用户、路径、二进制文件名):nano /etc/systemd/system/api.service
启用并启动服务:[Unit] Description=Fiber API Service After=network.target [Service] User=your-username WorkingDirectory=/path/to/api-folder ExecStart=/path/to/api-folder/your-api-binary Restart=always RestartSec=3 [Install] WantedBy=multi-user.targetsystemctl daemon-reload systemctl enable api.service systemctl start api.service
内容的提问来源于stack exchange,提问作者dickey
相关产品推荐
相关产品推荐

