ubuntu

ubuntu swagger怎样配置环境

小樊
53
2025-09-04 10:56:04
栏目: 智能运维

以下是在Ubuntu上配置Swagger环境的步骤:

  1. 安装Node.js和npm
    sudo apt update
    sudo apt install nodejs npm
    
  2. 安装Swagger相关包
    • 安装Swagger UI Express:
    sudo npm install -g swagger-ui-express
    
    • 或者使用npm在项目中安装:
    npm install swagger-ui-express
    
  3. 创建Swagger文档:在项目目录创建swagger.yaml文件,定义API元数据,如:
    swagger: '2.0'
    info:
      title: Sample API
      description: Sample API description
      version: 1.0.0
    paths:
      /users:
        get:
          summary: List all users
          responses:
            '200':
              description: An array of users
    
  4. 集成到Express应用
    • 创建index.js文件,添加以下代码:
    const express = require('express');
    const swaggerUi = require('swagger-ui-express');
    const YAML = require('yamljs');
    const swaggerDocument = YAML.load('./swagger.yaml');
    const app = express();
    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}`);
    });
    
  5. 运行应用
    node index.js
    
    然后访问http://localhost:3000/api-docs查看Swagger UI界面。

如果使用Docker部署:

  1. 安装Docker
    sudo apt update
    sudo apt install docker.io
    
  2. 创建Dockerfile
    FROM node:14
    WORKDIR /usr/src/app
    COPY package*.json ./
    RUN npm install
    COPY . .
    EXPOSE 3000
    CMD [ "node", "index.js" ]
    
  3. 构建并运行容器
    docker build -t swagger-ui-express .
    docker run -p 3000:3000 swagger-ui-express
    

0
看了该问题的人还看了