使用Docker容器化部署是解决Linux下Swagger兼容性问题的高效方式,可避免环境依赖冲突。具体步骤如下:
sudo apt install docker.io,CentOS使用sudo yum install docker),安装后启动Docker服务并设置开机自启(sudo systemctl start docker && sudo systemctl enable docker)。docker pull swaggerapi/swagger-ui:v4.15.5(Swagger UI)、docker pull swaggerapi/swagger-editor:v4.6.0(Swagger Editor)。docker run命令映射端口到主机(如Swagger UI映射8081端口:docker run -d -p 38081:8080 swaggerapi/swagger-ui:v4.15.5),确保端口未被占用。http://localhost:38081(Swagger Editor)或http://localhost:38080(Swagger UI)即可使用。若需直接在Linux服务器上部署Swagger UI,可通过以下步骤操作:
sudo apt install nodejs npm),验证安装(node -v、npm -v)。git clone https://github.com/swagger-api/swagger-ui.git),进入目录后安装依赖(npm install),修改index.html文件中的url参数,指向本地或远程API文档(如http://your-server-ip:8080/v2/api-docs)。target/swagger-ui-dist/目录)复制到Web服务器目录(如Apache的/var/www/html或Nginx的/usr/share/nginx/html)。/etc/apache2/sites-available/swagger.conf),添加DocumentRoot /var/www/html和<Directory>权限设置,启用站点并重启Apache(sudo a2ensite swagger.conf && sudo systemctl reload apache2)。/etc/nginx/sites-available/swagger),添加root /usr/share/nginx/html和try_files $uri $uri/ /index.html指令,启用配置并重启Nginx(sudo ln -s /etc/nginx/sites-available/swagger /etc/nginx/sites-enabled/ && sudo nginx -t && sudo systemctl reload nginx)。若在Spring Boot项目中使用Swagger,需确保依赖兼容性与配置正确:
pom.xml中添加Swagger 2依赖(如springfox-swagger2 2.9.2、springfox-swagger-ui 2.9.2),避免与Spring Boot版本冲突(如Spring Boot 2.7.x及以上版本建议使用springdoc-openapi-starter-webmvc-ui替代)。@Configuration、@EnableSwagger2),设置API扫描范围(如RequestHandlerSelectors.any())和路径映射(如PathSelectors.any()),若使用路径前缀(如/api),需在Docket中添加pathMapping("/api"),并在application.properties中配置springfox.documentation.swagger-ui.base-path=/api。application.yml中添加spring.resources.static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/。static-locations配置)、Nginx代理是否转发正确路径(如proxy_set_header X-Forwarded-Prefix /api-docs)、应用端口是否开放(如sudo ufw allow 8080)。springfox-swagger2与spring-boot-starter-web的版本兼容性)。location块正确代理了Swagger的URL路径,例如location /api-docs { proxy_pass http://localhost:8080; },并添加proxy_set_header Host $host;以保留原始请求头。