温馨提示×

ubuntu swagger怎么配置

小樊
38
2026-10-09 20:54:39
栏目: 智能运维

在 Ubuntu 上配置 Swagger,通常取决于你用的后端语言/框架。下面我按常见场景给你说明,你可以对号入座。


一、Ubuntu + Java(Spring Boot)配置 Swagger

1. 安装 Java & Maven

sudo apt update
sudo apt install openjdk-17-jdk maven -y

2. Spring Boot 项目引入 Swagger

以 SpringDoc OpenAPI(推荐) 为例:

pom.xml

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.3.0</version>
</dependency>

3. 启动项目

mvn spring-boot:run

4. 访问 Swagger UI

http://localhost:8080/swagger-ui.html

二、Ubuntu + Node.js(Express)配置 Swagger

1. 安装 Node.js

sudo apt install nodejs npm -y

2. 安装 Swagger 相关包

npm init -y
npm install express swagger-ui-express yamljs

3. 示例代码

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));

app.listen(3000, () => {
  console.log('Swagger: http://localhost:3000/api-docs');
});

4. 访问

http://localhost:3000/api-docs

三、Ubuntu + Python(FastAPI / Flask)

FastAPI(最简单)

pip install fastapi uvicorn

FastAPI 自带 Swagger:

http://localhost:8000/docs

Flask + Flask-RESTX

pip install flask flask-restx

四、Ubuntu 上独立部署 Swagger Editor(可选)

docker run -d -p 8080:8080 swaggerapi/swagger-editor

访问:

http://localhost:8080

五、常见问题

  • 端口被占用:lsof -i:8080
  • 无法访问:检查 Ubuntu 防火墙
sudo ufw allow 8080
  • 生产环境:建议加 Nginx 反向代理

如果你能告诉我:

  • 用的语言(Java / Node / Python / Go)
  • 框架(Spring / Express / FastAPI)
  • 是否 Docker

我可以给你更精确的配置示例。

0 踩