Ubuntu 上部署 Swagger 的实用流程
一 前置准备
二 部署方式一 Docker 快速部署 Swagger UI
docker run -d -p 8080:8080 \
-e SWAGGER_JSON=/app/swagger.yaml \
-v $(pwd):/app \
swaggerapi/swagger-ui-express
三 部署方式二 Node.js + Express 集成 Swagger UI
mkdir swagger-node-app && cd $_
npm init -y
npm install express swagger-ui-express yamljs
openapi: 3.0.0
info:
title: Sample API
version: 1.0.0
servers:
- url: http://localhost:3000/api
paths:
/users:
get:
summary: List users
responses:
'200':
description: A list of users
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/User'
components:
schemas:
User:
type: object
properties:
id:
type: integer
format: int64
name:
type: string
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));
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
console.log(`Swagger UI at http://localhost:${PORT}/api-docs`);
});
四 部署方式三 在现有 Java Spring Boot 项目中集成
<dependencies>
<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>
</dependencies>
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.controller"))
.paths(PathSelectors.any())
.build();
}
}
五 常用扩展与运维要点
反向代理与域名访问(Nginx 示例,将 /api-docs 代理到本地服务):
sudo apt install -y nginx
# 编辑 /etc/nginx/sites-available/default
server {
listen 80;
server_name your-domain.com;
location /api-docs {
proxy_pass http://127.0.0.1:3000/api-docs;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
sudo systemctl restart nginx
仅编辑文档时可部署 Swagger Editor(Docker):
docker run -d -p 8081:8080 swaggerapi/swagger-editor
访问 http://localhost:8081 在线编辑并导出 swagger.yaml/json。
防火墙放行(如使用 ufw):
sudo ufw allow 80,3000,8080,8081/tcp
sudo ufw enable
常见问题排查: