Swagger在CentOS上的调试流程与技巧
在CentOS上调试Swagger前,需确保系统具备必要的运行环境。常见依赖包括Java(用于Java项目)、Node.js/npm(用于Swagger工具链)、Docker(可选,简化部署):
sudo yum install java-11-openjdk-devel安装OpenJDK 11,验证java -version显示版本信息。curl -sL https://rpm.nodesource.com/setup_14.x | sudo bash -添加NodeSource源,再执行sudo yum install nodejs安装,验证node -v和npm -v。sudo yum install docker安装Docker,启动服务sudo systemctl start docker并设置开机自启sudo systemctl enable docker。根据需求选择Docker(推荐,快速部署)或手动安装(灵活定制):
docker pull swaggerapi/swagger-ui:v4.15.5
docker run -d -p 38081:8080 -e SWAGGER_FILE=/app/swagger.yaml swaggerapi/swagger-ui:v4.15.5
此方式无需手动配置,直接通过http://<CentOS_IP>:38081访问。git clone https://github.com/swagger-api/swagger-editor.git,进入目录后执行npm install -g http-server,启动静态服务器http-server -p 8080。git clone https://github.com/swagger-api/swagger-ui.git,进入目录后执行npm install express --save,创建public目录并将dist文件夹内容复制到public,编写index.js启动Express服务器(监听8005端口)。调试核心是将Swagger UI与你的API文档关联。需修改Swagger UI的配置文件,指定API文档的URL:
public/index.html文件,找到url参数(通常在SwaggerUIBundle配置中),将其值改为你的API文档地址(如http://<CentOS_IP>:8080/v2/api-docs,Spring Boot默认路径):window.onload = function() {
const ui = SwaggerUIBundle({
url: "http://localhost:8080/v2/api-docs", // 替换为你的API文档URL
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
]
});
};
重启Express服务器使配置生效。http://<CentOS_IP>:38081(Docker方式)或http://<CentOS_IP>:8005/static/index.html(手动方式),查看API文档列表。Authorization),点击按钮发送请求,查看响应结果(状态码、返回数据)。systemctl status <服务名>(如systemctl status nginx、systemctl status your-spring-boot-app)确认相关服务是否启动;若未启动,执行systemctl restart <服务名>重启。/var/log/spring-boot.log)、Swagger UI日志(手动部署时终端输出)、系统日志(journalctl -xe),定位具体错误信息(如404 Not Found、500 Internal Server Error)。url参数是否指向正确的API文档地址;确认API文档本身是否有效(可通过在线Swagger Editor验证swagger.yaml/swagger.json语法)。netstat -tulnp | grep <端口>确认Swagger UI端口(如38081、8005)是否监听;若防火墙开启,放行端口:sudo firewall-cmd --permanent --add-port=38081/tcp
sudo firewall-cmd --reload
/var/www/html)及文件具有正确的读取权限(chmod -R 755 /var/www/html)。若需深入调试Swagger UI或后端代码,可使用IDE(如IntelliJ IDEA、VS Code)进行远程调试:
--debug参数启动(如java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005 -jar your-app.jar);若调试Swagger UI容器,进入容器执行npm run debug。