温馨提示×

怎么在Linux配Swagger

小樊
37
2026-08-21 03:28:51
栏目: 智能运维

在 Linux 上配置 Swagger,通常取决于你用的是哪种技术栈。下面我按最常见的几种情况给你讲,你可以直接跳到对应部分。


一、通用概念先说明

Swagger 现在通常指 OpenAPI + Swagger UI

  • OpenAPI:接口描述规范(YAML / JSON)
  • Swagger UI:可交互的接口文档页面
  • Swagger Editor:编写 OpenAPI 文件的工具

二、方式一:直接部署 Swagger UI(最通用 ✅)

适合:
✅ 任何后端(Java / Python / Go / Node / PHP)
✅ 只想在 Linux 上看接口文档

1️⃣ 安装依赖

sudo apt update
sudo apt install -y git curl

2️⃣ 下载 Swagger UI

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

或直接下载:

wget https://github.com/swagger-api/swagger-ui/archive/refs/heads/master.zip
unzip master.zip

3️⃣ 用 Nginx 部署(推荐)

sudo apt install -y nginx
sudo cp -r swagger-ui/dist /var/www/swagger

编辑 Nginx 配置:

sudo vim /etc/nginx/sites-available/swagger

内容示例:

server {
    listen 8080;
    server_name localhost;

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

启用:

sudo ln -s /etc/nginx/sites-available/swagger /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx

访问:

http://服务器IP:8080

三、方式二:Spring Boot + Swagger(Java 最常见)

1️⃣ 添加依赖(Springfox)

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

2️⃣ 启用 Swagger

@Configuration
@EnableOpenApi
public class SwaggerConfig {
}

3️⃣ 访问地址

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

✅ Linux 上无需额外配置,只要服务能访问即可


四、方式三:Python(FastAPI / Flask)

✅ FastAPI(自带 Swagger)

pip install fastapi uvicorn
from fastapi import FastAPI

app = FastAPI()

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

启动:

uvicorn main:app --host 0.0.0.0 --port 8000

访问:

http://服务器IP:8000/docs

✅ Flask + Flasgger

pip install flasgger
from flask import Flask
from flasgger import Swagger

app = Flask(__name__)
Swagger(app)

@app.route("/hello")
def hello():
    return "hello"

app.run(host="0.0.0.0", port=5000)

访问:

http://服务器IP:5000/apidocs

五、方式四:用 Docker 部署 Swagger UI(最简单 ⭐)

docker run -p 8080:8080 swaggerapi/swagger-ui

访问:

http://服务器IP:8080

✅ 不需要 Nginx、不需要配置环境


六、常见问题

❓ 端口访问不了?

sudo ufw allow 8080

❓ 想加载自己的 API 文档?

修改:

/var/www/swagger/swagger-initializer.js
url: "http://你的IP:端口/v3/api-docs",

七、我可以继续帮你

你可以直接告诉我:

  1. ✅ 用的什么语言 / 框架?
  2. ✅ 是本地 Linux 还是服务器?
  3. ✅ 想看 Swagger 页面,还是生成接口文档?

我可以给你精确到命令级别的配置方案

0