温馨提示×

如何在Ubuntu中配置Swagger UI

小樊
67
2025-07-01 05:46:34
栏目: 智能运维

在Ubuntu中配置Swagger UI可以通过多种方法实现,以下是几种常见的方法:

方法一:使用Docker

  1. 安装Docker
sudo apt update
sudo apt install docker.io
  1. 拉取Swagger UI Docker镜像
docker pull swaggerapi/swagger-ui-express
  1. 运行Swagger UI容器
docker run -p 8080:8080 swaggerapi/swagger-ui-express
  1. 访问Swagger UI: 在浏览器中访问 http://localhost:8080,你应该能看到Swagger UI界面。

方法二:使用Node.js和Express手动安装

  1. 安装Node.js和npm
sudo apt update
sudo apt install nodejs npm
  1. 创建一个新的Node.js项目
mkdir swagger-ui-project
cd swagger-ui-project
npm init -y
  1. 安装Swagger UI Express
npm install swagger-ui-express
  1. 创建一个简单的Express应用: 创建一个名为 app.js 的文件,并添加以下代码:
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');

// Load Swagger document
const swaggerDocument = YAML.load('./swagger.yaml');
const app = express();

// Serve Swagger docs
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
  1. 创建Swagger文档: 创建一个名为 swagger.yaml 的文件,并添加你的API文档。例如:
swagger: '2.0'
info:
  title: Sample API
  description: A sample API to demonstrate Swagger UI integration
  version: '1.0.0'
paths:
  /users:
    get:
      summary: List all users
      responses:
        '200':
          description: A list of users
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/definitions/User'
definitions:
  User:
    type: object
    properties:
      id:
        type: integer
      name:
        type: string
    required:
      - id
      - name
  1. 运行应用
node app.js
  1. 访问Swagger UI: 在浏览器中访问 http://localhost:3000/api-docs,你应该能看到Swagger UI界面。

方法三:使用Nginx作为反向代理

  1. 安装Nginx
sudo apt install nginx
  1. 下载Swagger Editor和Swagger UI
wget https://github.com/swagger-api/swagger-ui/releases/download/v3.47.1/swagger-ui.zip
unzip swagger-ui.zip
  1. 配置Nginx: 编辑 /etc/nginx/sites-available/default 文件,添加以下内容:
server {
    listen 80;
    server_name localhost;

    location /swagger-editor {
        proxy_pass http://localhost:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    location /swagger-ui {
        proxy_pass http://localhost:3000;
        proxy_set_header Host $host;
    }
}
  1. 重启Nginx
sudo systemctl restart nginx
  1. 访问Swagger Editor和Swagger UI
  • Swagger Editor: http://localhost/swagger-editor
  • Swagger UI: http://localhost/swagger-ui

以上方法可以帮助你在Ubuntu上成功安装和配置Swagger UI,并进行API文档的查看和测试。选择适合你的方法并按照步骤操作即可。如果在安装过程中遇到问题,可以参考相关的官方文档或社区论坛寻求帮助。

0