温馨提示×

centos怎么配置swagger

小樊
39
2026-10-26 17:52:06
栏目: 智能运维

在 CentOS 上“配置 Swagger”通常不是系统级配置,而是在应用中集成 Swagger。不同语言/框架方式不同,下面按常见情况说明。


一、常见场景说明

  • Java(Spring Boot):最常见 ✅
  • Node.js(Express)
  • Python(FastAPI / Flask)
  • 纯静态 Swagger UI(不写代码)

二、Spring Boot 项目(最常用)

1. 环境准备(CentOS)

java -version
mvn -version

2. 引入依赖(Maven)

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

老项目可用 springfox-swagger2(已停止维护)

3. 启动项目

mvn spring-boot:run

4. 访问 Swagger

http://服务器IP:端口/swagger-ui.html
或
http://服务器IP:端口/swagger-ui/index.html

5. 防火墙放行

firewall-cmd --permanent --add-port=8080/tcp
firewall-cmd --reload

三、Node.js + Express

1. 安装

npm install swagger-ui-express yamljs

2. 示例代码

const express = require('express');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');

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

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

app.listen(3000);

3. 访问

http://IP:3000/api-docs

四、Python(FastAPI)

pip install fastapi uvicorn
from fastapi import FastAPI

app = FastAPI()

@app.get("/items")
def read_items():
    return {"msg": "hello"}

访问:

http://IP:8000/docs

五、纯静态 Swagger UI(不写代码)

yum install -y nginx
git clone https://github.com/swagger-api/swagger-ui.git
cp -r swagger-ui/dist/* /usr/share/nginx/html/
systemctl start nginx

访问:

http://服务器IP/

六、常见问题

✅ 无法访问

  • 检查防火墙
  • 检查云服务器安全组
  • 检查应用是否监听 0.0.0.0

✅ 生产环境建议

  • 加账号密码(Nginx Basic Auth)
  • 或内网访问

如果你能告诉我:

  • 用的什么语言/框架
  • CentOS 版本
  • 是否是 Spring Boot

我可以直接给你精确配置步骤。

0 踩