Ubuntu 22服务器部署Node.js后端遇Certbot认证失败求助
一、先解决DNS与Certbot认证失败问题
清理无效DNS记录
删除DNS解析中www1.example.com的所有记录,仅保留example.com和www.example.com的A/AAAA记录,确保它们指向你的VPS公网IP。用dig example.com和dig www.example.com验证解析是否生效,等待10-30分钟让DNS缓存更新。配置防火墙规则
执行以下命令放行必要端口,避免防火墙拦截Certbot验证请求:ufw allow 80/tcp ufw allow 443/tcp ufw allow 3000/tcp ufw reload验证规则:
ufw status,确认80、443、3000端口已被允许。
二、配置Nginx反向代理(解决IP:3000无样式、SSL错误)
修改Nginx站点配置
找到CloudPanel生成的Nginx配置文件(通常在/etc/nginx/sites-available/你的域名.conf,或直接在CloudPanel面板的站点设置中编辑),替换为以下基础配置:server { listen 80; server_name example.com www.example.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; } }验证并重启Nginx
nginx -t # 检查配置语法是否正确 systemctl restart nginx # 重启Nginx服务此时访问
http://example.com应能正常加载包含CSS/JS的页面,不再出现SSL错误(当前走80端口的HTTP请求,后续由Certbot配置SSL)。
三、重新申请Let's Encrypt证书
执行Certbot命令,通过Nginx自动配置SSL:
certbot --nginx -d example.com -d www.example.com
按照提示选择自动跳转HTTPS即可。若仍报错,确认DNS解析已完全生效,且Nginx配置无问题。
四、检查Node.js index.js配置
确保你的Node服务满足以下两点:
监听0.0.0.0而非localhost
这样Nginx才能从本地网络访问到Node服务,示例代码:const express = require('express'); const app = express(); // 托管静态文件(根据你的前端文件路径调整) app.use(express.static('public')); // API接口示例 app.get('/api/portfolio', (req, res) => { res.json({ projects: [] }); }); // 监听0.0.0.0:3000 app.listen(3000, '0.0.0.0', () => { console.log('Server running on http://0.0.0.0:3000'); });静态文件路径正确
如果前端的CSS/JS放在项目的public目录,app.use(express.static('public'))必须配置正确,否则静态资源会返回404,导致页面无样式。
内容的提问来源于stack exchange,提问作者Dstock

