温馨提示×

Linux下Swagger如何部署

小樊
42
2026-07-10 13:16:00
栏目: 智能运维

在 Linux 下部署 Swagger(通常指 Swagger UI / Swagger Editor / Swagger 相关服务),常见有三种场景。下面按从简单到完整给你说明,你可以根据实际需求选择。


一、最简单:直接部署 Swagger UI(静态页面)

适合:
✅ 已有 OpenAPI 接口文档(JSON / YAML)
✅ 只想让别人通过浏览器查看接口文档

1️⃣ 下载 Swagger UI

cd /usr/local
sudo git clone https://github.com/swagger-api/swagger-ui.git

2️⃣ 只保留静态资源

cp -r swagger-ui/dist /var/www/swagger

3️⃣ 修改默认 JSON 文件

编辑:

vim /var/www/swagger/swagger-initializer.js

修改:

url: "https://petstore.swagger.io/v2/swagger.json"

改成你自己的接口文档地址,例如:

url: "http://your-domain.com/api/openapi.json"

4️⃣ 使用 Nginx 部署

sudo yum install nginx -y   # CentOS
sudo apt install nginx -y  # Ubuntu

Nginx 配置:

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

    root /var/www/swagger;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }
}

重启:

nginx -t
systemctl restart nginx

✅ 浏览器访问:

http://swagger.xxx.com

二、Swagger Editor(在线编辑 OpenAPI)

适合:
✅ 编写 / 调试 OpenAPI 文档

方式一:Docker(推荐)

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

访问:

http://服务器IP:8080

方式二:直接部署

git clone https://github.com/swagger-api/swagger-editor.git
cd swagger-editor
http-server -p 8080

三、Swagger 与 Java / Spring Boot 项目集成(最常见)

适合:
✅ Java 后端
✅ 自动生成接口文档

1️⃣ Maven 依赖(Springfox)

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

2️⃣ 启动类

@SpringBootApplication
@EnableOpenApi
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

3️⃣ 访问地址

http://IP:端口/swagger-ui/index.html

四、Swagger UI + 后端 API(生产推荐)

架构:

Nginx
 ├── /api        → 后端服务
 └── /swagger    → Swagger UI

Nginx 示例

location /api/ {
    proxy_pass http://127.0.0.1:8080/;
}

location /swagger/ {
    root /var/www;
    index index.html;
}

五、常见问题

❓ Swagger 显示 Unable to fetch

  • JSON 地址不可访问
  • 跨域问题(后端加 CORS)

❓ Linux 防火墙

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

六、总结对比

方式 适合场景
静态 Swagger UI 已有接口文档
Swagger Editor 编写 API
Springfox / springdoc Java 项目
Docker 快速部署

如果你愿意,可以告诉我:

  • ✅ 使用什么语言(Java / Python / Node)
  • ✅ 是否已有 OpenAPI 文件
  • ✅ 是否用 Docker / Nginx

我可以给你一份完全贴合你项目的部署方案

0