温馨提示×

centos怎样配置swagger

小樊
37
2026-09-27 09:54:07
栏目: 智能运维

在 CentOS 上“配置 Swagger”通常分几种情况,先确认你是哪一种:

  1. Java 项目(Spring Boot) 使用 Swagger / Springdoc
  2. Node.js / Python / Go 等项目 接入 Swagger UI
  3. 单纯在 CentOS 上部署 Swagger UI(静态页面)
  4. 通过 Nginx 反向代理 Swagger

下面我按最常见场景给你说明。


一、Spring Boot 项目(最常用)

1️⃣ 添加依赖

Swagger 2(老版本)

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

Springdoc(推荐,Swagger 3)

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

2️⃣ 配置类(Swagger 2 示例)

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example"))
                .paths(PathSelectors.any())
                .build();
    }
}

Springdoc 不需要配置类。


3️⃣ 启动并访问

java -jar your-app.jar

访问地址:

  • Swagger 2:http://服务器IP:端口/swagger-ui.html
  • Springdoc:http://服务器IP:端口/swagger-ui/index.html

二、CentOS 上直接部署 Swagger UI(通用)

1️⃣ 安装依赖

yum install -y git nginx

2️⃣ 下载 Swagger UI

git clone https://github.com/swagger-api/swagger-ui.git
cp -r swagger-ui/dist /usr/share/nginx/html/swagger

3️⃣ 配置 Nginx

server {
    listen 80;
    server_name swagger.example.com;

    location / {
        root /usr/share/nginx/html/swagger;
        index index.html;
    }
}
nginx -t
systemctl restart nginx

访问:http://服务器IP/


三、Swagger 指向你的接口

修改:

/usr/share/nginx/html/swagger/swagger-initializer.js
url: "http://你的服务IP:端口/v3/api-docs"

四、防火墙 & 安全(重要)

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

⚠️ 生产环境建议:

  • 加 鉴权
  • 限制 IP
  • 不要对外暴露 Swagger

五、我可以更具体帮你

你可以告诉我:

  • ✅ 用的什么语言(Java / Node / Python)
  • ✅ CentOS 版本(7 / 8 / Stream)
  • ✅ 是否是 Spring Boot
  • ✅ 是否用 Docker

我可以直接给你 可复制的完整配置。

0 踩