使用Docker容器化部署Swagger,可彻底规避Linux环境下的依赖冲突、路径配置等问题。具体步骤如下:
apt-get install docker.io
)。docker pull swaggerapi/swagger-ui:latest
docker pull swaggerapi/swagger-editor:latest
docker run -d -p 8080:8080 swaggerapi/swagger-ui:latest
docker run -d -p 8081:8080 swaggerapi/swagger-editor:latest
http://localhost:8080
(Swagger UI)和http://localhost:8081
(Swagger Editor)即可使用。pom.xml
中移除SpringFox依赖,添加SpringDoc依赖:<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.1.0</version> <!-- 使用最新稳定版 -->
</dependency>
mvn dependency:tree
或Gradle的dependencies
命令检查依赖树,通过exclusion
排除冲突的库(如Guava、Jackson等)。例如:<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</exclusion>
</exclusions>
</dependency>
PathPatternMatcher
,而Swagger 3可能需要AntPathMatcher
。需在配置类中显式设置:@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
configurer.setPathMatcher(new AntPathMatcher());
}
}
X-Forwarded-Prefix
头,确保Swagger能正确加载JSON文件。例如:location /api-docs/ {
proxy_pass http://localhost:8080/;
proxy_set_header X-Forwarded-Prefix /api-docs;
}
index.html
及JSON文件的路径正确,且Linux用户对目录有读取权限(如chmod -R 755 /var/www/html/swagger
)。ufw allow 8080
),以及JSON文件路径是否正确。http://localhost:8080/swagger-ui/index.html
),查看应用日志(如Spring Boot的logs/application.log
)获取详细错误信息。npm install -g swagger-cli
swagger-cli validate api-specification.json
allow/deny
指令限制IP访问。例如,Spring Security配置:@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/swagger-ui/**").authenticated()
.and().formLogin();
}
sudo certbot --nginx -d yourdomain.com