一、前提准备 在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应用
mkdir swagger-project && cd swagger-project
npm init -y
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容器化部署 若需容器化部署,可按以下步骤操作:
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 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()中的路径一致。-v挂载路径是否正确。