在 Linux 上配置 Swagger,通常取决于你用的是哪种技术栈。下面我按最常见的几种情况给你讲,你可以直接跳到对应部分。
Swagger 现在通常指 OpenAPI + Swagger UI:
适合:
✅ 任何后端(Java / Python / Go / Node / PHP)
✅ 只想在 Linux 上看接口文档
sudo apt update
sudo apt install -y git curl
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
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
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
@Configuration
@EnableOpenApi
public class SwaggerConfig {
}
http://localhost:8080/swagger-ui/index.html
✅ Linux 上无需额外配置,只要服务能访问即可
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
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 run -p 8080:8080 swaggerapi/swagger-ui
访问:
http://服务器IP:8080
✅ 不需要 Nginx、不需要配置环境
sudo ufw allow 8080
修改:
/var/www/swagger/swagger-initializer.js
url: "http://你的IP:端口/v3/api-docs",
你可以直接告诉我:
我可以给你精确到命令级别的配置方案。