CentOS系统部署Swagger指南
Swagger是一套用于设计、构建、记录和使用RESTful API的工具集,其中Swagger UI是常用的交互式文档展示工具。以下是在CentOS系统上部署Swagger UI的具体步骤:
sudo yum update -y
sudo yum install -y wget curl gcc-c++ make
Swagger UI依赖Node.js环境,需先安装对应版本(推荐Node.js 12.x及以上):
# 添加NodeSource源(以12.x为例)
curl -sL https://rpm.nodesource.com/setup_12.x | sudo bash -
# 安装Node.js及npm
sudo yum install -y nodejs
# 验证安装
node -v # 应输出v12.x.x及以上版本
npm -v # 应输出6.x.x及以上版本
mkdir -p /opt/swagger && cd /opt/swagger
wget https://github.com/swagger-api/swagger-ui/archive/refs/tags/v3.34.0.tar.gz
tar -xzf v3.34.0.tar.gz --strip-components=1
http-server快速启动Swagger UInpm install -g http-server
http-server -p 8080 ./dist
http://<服务器IP>:8080,即可看到Swagger UI界面。若需自定义接口文档路径或添加认证等功能,可通过Express框架部署:
mkdir -p /opt/swagger/{public,server}
cd /opt/swagger/server
npm init -y
npm install express --save
index.js文件,内容如下:const express = require('express');
const app = express();
const path = require('path');
// 指向Swagger UI的静态文件目录
app.use('/static', express.static(path.join(__dirname, '../public')));
// 可选:自定义API文档路径(需将接口文档放入public目录)
// app.get('/api-docs', (req, res) => {
// res.sendFile(path.join(__dirname, '../public/your-api-docs.json'));
// });
// 启动服务
app.listen(3000, () => {
console.log('Swagger UI运行于 http://localhost:3000/static/index.html');
});
node index.js
http://<服务器IP>:3000/static/index.html。api-docs.json(或api-docs.yaml)。public目录(如/opt/swagger/public)。/opt/swagger/public/index.html,找到以下代码:const ui = SwaggerUIBundle({
url: "https://petstore.swagger.io/v2/swagger.json", // 替换为你的文档路径
// ...
});
将url值改为本地文档路径,例如:url: "/static/api-docs.json"
node index.js使配置生效。sudo firewall-cmd --permanent --add-port=80/tcp
sudo firewall-cmd --permanent --add-port=443/tcp
sudo firewall-cmd --reload
swagger)并赋予权限。通过以上步骤,即可在CentOS系统上完成Swagger UI的部署,并通过浏览器访问交互式API文档。如需进一步定制(如添加认证、修改主题),可参考Swagger UI官方文档进行调整。