在 Ubuntu 上使用 Swagger 进行 API 文档共享
一 方案总览
二 本地安装与快速启动
sudo apt update && sudo apt install -y nodejs npmnode -v、npm -vwget https://github.com/swagger-api/swagger-editor/archive/refs/tags/v3.50.0.tar.gz && tar -xvf v3.50.0.tar.gz && cd swagger-editor-3.50.0npm install -g http-serverhttp-server -p 8080,访问:http://localhost:8080wget https://github.com/swagger-api/swagger-ui/archive/refs/tags/v3.50.0.tar.gz && tar -xvf v3.50.0.tar.gz && cd swagger-ui-3.50.0http-server -p 8081,访问:http://localhost:8081三 Docker 部署与远程访问
docker pull swaggerapi/swagger-editor && docker run -p 8088:8080 -d swaggerapi/swagger-editordocker run -p 8080:8080 -e SWAGGER_JSON=/app/swagger.json -v $(pwd):/app swaggerapi/swagger-ui-express四 集成到现有服务与团队协作
npm install express swagger-ui-express yamljsconst express = require('express');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');
const app = express();
const swaggerDocument = YAML.load('./swagger.yaml'); // 或 swagger.json
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on ${PORT}`));
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
五 安全与运维建议
server {
listen 80;
server_name api-docs.example.com;
location / {
proxy_pass http://127.0.0.1:8080; # 指向 Swagger UI 或 Editor
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/.htpasswd;
}
}