单VPS部署多Java Spring Boot应用方案咨询
单VPS部署多Spring Boot应用并绑定不同域名的实现方案
完全可以实现,以下是几种成熟的实现方案,按推荐程度排序:
方案一:Nginx反向代理(生产环境首选)
这是最常用的方案,通过Nginx作为反向代理,将不同域名的请求转发到对应Spring Boot应用的端口,用户访问时无需手动输入端口。
具体步骤:
- 配置Spring Boot应用端口:给每个应用设置唯一端口,比如在
application.properties中:- 应用1:
server.port=8081 - 应用2:
server.port=8082
- 应用1:
- 安装Nginx:根据VPS的系统执行安装命令:
- Ubuntu/Debian:
sudo apt update && sudo apt install nginx - CentOS/RHEL:
sudo yum install nginx
- Ubuntu/Debian:
- 配置Nginx虚拟主机:在
/etc/nginx/sites-available/目录下创建两个配置文件:- 对应
example1.domain的配置(example1.conf):server { listen 80; server_name example1.domain; location / { proxy_pass http://localhost:8081; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } - 对应
example2.domain的配置(example2.conf):server { listen 80; server_name example2.domain; location / { proxy_pass http://localhost:8082; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } }
- 对应
- 启用配置并重启Nginx:
- 创建软链接到启用目录:
sudo ln -s /etc/nginx/sites-available/example1.conf /etc/nginx/sites-enabled/,同理执行example2.conf的链接命令。 - 重启Nginx生效:
sudo systemctl restart nginx
- 创建软链接到启用目录:
- 域名解析:将
example1.domain和example2.domain的A记录都指向你的VPS公网IP。
完成后,用户访问example1.domain会自动转发到8081端口的应用,example2.domain转发到8082端口。
方案二:Spring Cloud Gateway(Spring生态专属)
如果你的应用都是Spring技术栈,可使用Spring Cloud Gateway作为统一入口网关,它本身是一个Spring Boot应用,通过路由规则根据域名转发请求。
具体步骤:
- 创建Spring Cloud Gateway应用:初始化一个Spring Boot项目,引入
Spring Cloud Gateway依赖,设置端口为80(或8080)。 - 配置路由规则:在
application.yml中添加域名路由配置:spring: cloud: gateway: routes: - id: app1_route uri: http://localhost:8081 predicates: - Host=example1.domain - id: app2_route uri: http://localhost:8082 predicates: - Host=example2.domain - 启动所有应用:先启动网关应用,再分别启动端口为8081、8082的Spring Boot应用。
- 域名解析:将两个域名指向VPS公网IP。
该方案适合微服务架构,后续扩展新应用只需添加路由规则即可。
方案三:直接端口访问(简易但体验差)
这是你最初的想法,配置最简单但用户体验不佳:
- 给每个Spring Boot应用设置不同端口(如8081、8082)。
- 在VPS防火墙开放这些端口:
sudo ufw allow 8081/tcp、sudo ufw allow 8082/tcp(以Ubuntu为例)。 - 域名解析后,用户需通过
example1.domain:8081、example2.domain:8082访问对应应用。
此方案需用户记住端口号,不推荐用于生产环境。
内容的提问来源于stack exchange,提问作者Danilo Congradac
相关产品推荐
相关产品推荐

