1. Windows Server 2022部署前后端项目概述
最近接手了一个企业级应用系统的部署任务,客户要求将SpringBoot+Vue前后端分离项目部署到Windows Server 2022环境。这种部署场景在企业内部系统中非常常见,特别是那些历史遗留系统较多、运维团队对Windows更熟悉的传统行业客户。与Linux部署相比,Windows环境有其独特的配置方式和注意事项。
在Windows Server上部署前后端分离项目,主要涉及以下几个核心组件:
- IIS作为Web服务器托管前端静态资源
- Java运行环境(JRE/JDK)运行后端服务
- 数据库服务(MySQL/SQL Server等)
- 可能的中间件如Redis、消息队列等
2. 环境准备与基础配置
2.1 Windows Server 2022初始配置
新安装的Windows Server 2022默认是最小化安装,我们需要先进行基础环境配置:
启用GUI管理工具(如果安装的是Server Core版本):
Install-WindowsFeature Server-Gui-Mgmt-Infra,Server-Gui-Shell -Restart安装.NET Framework 4.8:
Install-WindowsFeature NET-Framework-45-Core配置系统防火墙:
New-NetFirewallRule -DisplayName "Allow HTTP" -Direction Inbound -Protocol TCP -LocalPort 80 -Action Allow New-NetFirewallRule -DisplayName "Allow HTTPS" -Direction Inbound -Protocol TCP -LocalPort 443 -Action Allow
注意:生产环境建议只开放必要的端口,并根据实际需求调整防火墙规则。
2.2 IIS安装与配置
IIS是Windows平台最常用的Web服务器,安装步骤如下:
通过服务器管理器添加角色和功能:
Install-WindowsFeature Web-Server,Web-ASP,Web-Asp-Net45,Web-Mgmt-Console -IncludeManagementTools安装URL重写模块(用于前端路由): 从Microsoft官网下载并安装URL Rewrite模块
配置应用程序池:
- 为前端应用创建专用应用程序池
- 设置.NET CLR版本为"无托管代码"
- 将托管管道模式设为"集成"
3. 前端项目部署
3.1 Vue项目构建与发布
在开发环境构建生产版本:
npm run build将生成的dist文件夹内容复制到服务器上的发布目录(如C:\wwwroot\frontend)
IIS中配置网站:
- 物理路径指向发布目录
- 绑定域名和端口
- 设置默认文档为index.html
配置URL重写规则(解决前端路由404问题):
<rule name="Handle History Mode" stopProcessing="true"> <match url=".*" /> <conditions logicalGrouping="MatchAll"> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> </conditions> <action type="Rewrite" url="/" /> </rule>
3.2 静态资源优化配置
启用静态内容压缩:
Enable-WindowsOptionalFeature -Online -FeatureName IIS-HttpCompressionStatic配置客户端缓存: 在web.config中添加:
<staticContent> <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="30.00:00:00" /> </staticContent>
4. 后端服务部署
4.1 Java环境配置
安装JDK 11(推荐使用AdoptOpenJDK):
choco install adoptopenjdk11 -y配置环境变量:
[Environment]::SetEnvironmentVariable("JAVA_HOME", "C:\Program Files\AdoptOpenJDK\jdk-11.0.11.9-hotspot", "Machine")验证安装:
java -version
4.2 SpringBoot应用部署
打包应用:
mvn clean package -DskipTests将生成的jar文件复制到服务器(如C:\wwwroot\backend)
创建Windows服务(推荐使用NSSM):
nssm install MyBackendService "C:\Program Files\AdoptOpenJDK\jdk-11.0.11.9-hotspot\bin\java.exe" "-jar C:\wwwroot\backend\myapp.jar"配置服务自动重启:
nssm set MyBackendService AppRestartDelay 5000
4.3 数据库连接配置
在application.properties中配置生产环境数据库连接:
spring.datasource.url=jdbc:sqlserver://localhost:1433;databaseName=mydb spring.datasource.username=sa spring.datasource.password=yourStrongPassword加密敏感配置(推荐使用Jasypt):
spring.datasource.password=ENC(加密后的密码)
5. 前后端联调与优化
5.1 跨域问题解决
后端配置CORS(SpringBoot示例):
@Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**") .allowedOrigins("https://yourdomain.com") .allowedMethods("GET", "POST", "PUT", "DELETE") .allowCredentials(true); } }前端axios配置:
axios.defaults.withCredentials = true
5.2 性能优化建议
前端:
- 启用Gzip压缩
- 使用CDN分发静态资源
- 实现懒加载路由
后端:
- 配置JVM参数(Xms/Xmx)
- 启用响应压缩
server.compression.enabled=true数据库:
- 优化索引
- 配置连接池参数
spring.datasource.hikari.maximum-pool-size=20
6. 监控与维护
6.1 基础监控配置
配置Windows性能监控:
- 关键指标:CPU、内存、磁盘I/O、网络
- 使用Performance Monitor创建数据收集器集
应用健康检查:
- SpringBoot Actuator配置:
management.endpoints.web.exposure.include=health,info,metrics management.endpoint.health.show-details=always
6.2 日志管理方案
统一日志配置:
<RollingFile name="FileAppender" fileName="logs/app.log" filePattern="logs/app-%d{yyyy-MM-dd}-%i.log"> <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5level %logger{36} - %msg%n"/> <Policies> <TimeBasedTriggeringPolicy interval="1" modulate="true"/> <SizeBasedTriggeringPolicy size="100 MB"/> </Policies> </RollingFile>日志集中收集(可选ELK方案):
- 安装Filebeat收集日志
- 配置Logstash解析规则
- Kibana可视化展示
7. 安全加固措施
7.1 基础安全配置
SSL证书配置:
- 申请正规CA证书
- 在IIS中绑定HTTPS
- 配置HTTP强制跳转HTTPS
账户安全:
# 禁用默认Administrator账户 Rename-LocalUser -Name "Administrator" -NewName "CustomAdmin" # 配置密码策略 secedit /export /cfg secpolicy.inf # 修改文件后应用 secedit /configure /db secedit.sdb /cfg secpolicy.inf
7.2 应用层安全
SpringSecurity配置:
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .antMatchers("/api/public/**").permitAll() .anyRequest().authenticated() .and() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS); } }定期漏洞扫描:
- 使用Nessus等工具进行扫描
- 关注Windows Update推送的安全补丁
8. 自动化部署方案
8.1 基础脚本自动化
- 部署脚本示例(deploy.ps1):
param( [string]$frontendPath, [string]$backendPath ) # 停止现有服务 Stop-Service -Name "MyBackendService" -ErrorAction SilentlyContinue # 清理旧文件 Remove-Item -Path "C:\wwwroot\frontend\*" -Recurse -Force Remove-Item -Path "C:\wwwroot\backend\*" -Recurse -Force # 复制新文件 Copy-Item -Path "$frontendPath\*" -Destination "C:\wwwroot\frontend\" -Recurse Copy-Item -Path "$backendPath\*.jar" -Destination "C:\wwwroot\backend\" # 重启服务 Start-Service -Name "MyBackendService"
8.2 CI/CD集成(可选)
- Jenkins配置示例:
- 设置Windows节点
- 配置Pipeline脚本:
pipeline { agent any stages { stage('Build Frontend') { steps { bat 'npm install' bat 'npm run build' } } stage('Build Backend') { steps { bat 'mvn clean package -DskipTests' } } stage('Deploy') { steps { powershell 'C:\scripts\deploy.ps1 -frontendPath ./dist -backendPath ./target' } } } }
在实际部署过程中,我发现Windows Server环境对文件路径大小写不敏感,这可能导致从Linux开发环境迁移过来时出现资源加载问题。建议在开发阶段就统一使用小写文件名,避免部署时出现问题。另外,IIS的应用程序池回收设置需要根据实际负载调整,默认设置可能不适合高并发场景。