一、前提准备 在Ubuntu上配置Swagger前,需确保系统已更新并安装必要工具:
sudo apt update && sudo apt upgrade -y
二、安装Swagger核心工具
Swagger的配置与部署通常依赖swagger-jsdoc(生成文档)和swagger-ui-express(可视化界面),通过npm安装:
sudo apt install nodejs npm -y # 安装Node.js和npm
sudo npm install -g swagger-jsdoc swagger-ui-express # 全局安装Swagger工具
三、编写Swagger配置文件
创建swagger.yaml(或swagger.json)文件,定义API元数据(如路径、操作、模型)。示例如下:
swagger: '2.0'
info:
title: Sample API
description: A demo API for Swagger configuration on Ubuntu
version: 1.0.0
host: localhost:3000
basePath: /api
schemes:
- http
paths:
/users:
get:
summary: Retrieve all users
responses:
'200':
description: A list of user objects
schema:
type: array
items:
$ref: '#/definitions/User'
definitions:
User:
type: object
properties:
id:
type: integer
format: int64
name:
type: string
将文件保存至项目根目录(如/home/user/swagger-project/swagger.yaml)。
四、集成Swagger到Express应用
- 初始化Node.js项目:
mkdir swagger-project && cd swagger-project npm init -y - 安装Express及依赖:
npm install express swagger-ui-express yamljs --save - 创建
app.js文件,集成Swagger UI:const express = require('express'); const swaggerUi = require('swagger-ui-express'); const YAML = require('yamljs'); // 加载Swagger文档 const swaggerDocument = YAML.load('./swagger.yaml'); const app = express(); // 将Swagger UI挂载至/api-docs路径 app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument)); // 示例路由(需与swagger.yaml中的路径一致) app.get('/api/users', (req, res) => { res.json([{ id: 1, name: 'John Doe' }]); }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server running at http://localhost:${PORT}`); console.log(`Swagger UI available at http://localhost:${PORT}/api-docs`); });
五、启动应用并访问Swagger UI 运行Node.js应用:
node app.js
打开浏览器访问http://localhost:3000/api-docs,即可看到Swagger UI界面,展示API文档并支持交互式测试。
六、可选:使用Docker容器化部署 若需容器化部署,可按以下步骤操作:
- 安装Docker:
sudo apt install docker.io -y sudo systemctl start docker && sudo systemctl enable docker - 创建
Dockerfile:FROM node:18 WORKDIR /app COPY package*.json ./ RUN npm install COPY . . EXPOSE 3000 CMD ["node", "app.js"] - 构建并运行Docker容器:
docker build -t swagger-ubuntu . docker run -p 3000:3000 -v $(pwd)/swagger.yaml:/app/swagger.yaml swagger-ubuntu - 访问
http://localhost:3000/api-docs即可查看容器内的Swagger UI。
七、常见问题排查
- 端口冲突:若端口被占用,修改
app.js中的PORT变量(如const PORT = 8080;)。 - 文件路径错误:确保
swagger.yaml路径与YAML.load()中的路径一致。 - Docker权限问题:若无法访问容器内的文件,检查
-v挂载路径是否正确。
以上就是关于“Swagger在Ubuntu上如何配置与部署”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm