# 前后端多端口启动与访问
# 一、Spring Boot 多端口运行
# ✅ 目的
同一个后端项目同时启动多个实例(如测试不同数据、环境、功能),通过不同端口访问。
# ✅ 方法
# 方式一:IDEA 多运行配置(推荐)
打开 Run → Edit Configurations
复制已有的启动配置
在 Program arguments 添加:
--server.port=8081分别启动两个配置:
http://localhost:8080 http://localhost:8081
# 方式二:命令行启动
java -jar target/app.jar --server.port=8080
java -jar target/app.jar --server.port=8081
# 方式三:多环境配置(profiles)
在 application.yml:
spring:
profiles:
active: dev
---
spring:
config:
activate:
on-profile: dev
server:
port: 8080
---
spring:
config:
activate:
on-profile: test
server:
port: 8081
启动参数:
--spring.profiles.active=dev
--spring.profiles.active=test
# 二、Vue3 多端口运行(基于 Vite)
# ✅ 目的
同时运行多个前端实例,分别访问不同后端端口(或不同环境)。
# ✅ 方法
# 方式一:命令行直接指定端口
npm run dev -- --port 5174
# 方式二:package.json 定义多个命令
"scripts": {
"dev": "vite",
"dev2": "vite --port 5174"
}
# 方式三:使用多环境文件(推荐)
.env.dev1
VITE_PORT=5173
VITE_API_BASE=http://localhost:8080
.env.dev2
VITE_PORT=5174
VITE_API_BASE=http://localhost:8081
vite.config.js
export default defineConfig(({ mode }) => ({
server: { port: Number(process.env.VITE_PORT) || 5173 }
}))
运行:
npm run dev --mode dev1
npm run dev --mode dev2
访问:
http://localhost:5173 → 对应后端 8080
http://localhost:5174 → 对应后端 8081
# 三、前后端多端口联调示例
| 环境 | 前端端口 | 后端端口 | 说明 |
|---|---|---|---|
| dev1 | 5173 | 8080 | 开发环境 |
| dev2 | 5174 | 8081 | 测试环境 |
浏览器访问:
http://localhost:5173 -> API: http://localhost:8080
http://localhost:5174 -> API: http://localhost:8081
# 四、注意事项
- 每个实例端口必须唯一(否则会冲突)
- 确保后端已配置 CORS(允许不同端口访问)
- 建议不同环境使用
.env+ profile 管理 - 浏览器端口不同 → localStorage/sessionStorage 不会冲突
✅ 一句话总结:
Spring Boot 用
--server.port,Vue3 用--port, 分别开不同端口运行,就能轻松实现前后端多实例联调。
← 参数校验 打包的jar启动报错问题 →