前言
接着文章——全栈项目搭建+部署流程 | 花猪のBlog,本文依然以Button Demo为例,主要介绍如何将本地服务器的项目部署至公网。
(本文依然会介绍Demo的全套代码编写过程,为了撰写文章方便,博主在本文就按照项目目录从上至下依次介绍(实际编写过程肯定不是这样的),这里依然摆出Demo的源码主要是因为有些配置信息需要特别关注。)
前提——需要一个24h不断电的主机。(我这里用的是一台老旧一体机做演示)
机器配置如下:
Demo编写
项目环境(版本)
- 后端:SpringBoot 3.0.2(JDK:jdk-17.0.12)
- 前端:Vue3 + ElementUI
- 数据库:MySQL 8.0
后端
数据库设计如下:
创建一个名为“button”的表,在其中创建一个名为“number”的字段。(这里“number”字段选择的是“varchar”类型。)

打开IDEA,创建一个名为Button的项目。
pom.xml配置文件如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
| <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.0.2</version> <relativePath/> </parent> <groupId>com.example</groupId> <artifactId>Button</artifactId> <version>0.0.1-SNAPSHOT</version> <name>Button</name> <description>Button</description> <url/> <licenses> <license/> </licenses> <developers> <developer/> </developers> <scm> <connection/> <developerConnection/> <tag/> <url/> </scm> <properties> <java.version>17</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.5.5</version> </dependency> <dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.20</version> </dependency> </dependencies>
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <executions> <execution> <id>default-compile</id> <phase>compile</phase> <goals> <goal>compile</goal> </goals> <configuration> <annotationProcessorPaths> <path> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </path> </annotationProcessorPaths> </configuration> </execution> <execution> <id>default-testCompile</id> <phase>test-compile</phase> <goals> <goal>testCompile</goal> </goals> <configuration> <annotationProcessorPaths> <path> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </path> </annotationProcessorPaths> </configuration> </execution> </executions> </plugin> </plugins> </build>
</project>
|
后端项目目录如下:

按照项目结构,从上至下依次介绍各模块代码:
ButtonController:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| package com.example.button.controller;
import com.example.button.service.ButtonService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap; import java.util.Map;
@CrossOrigin(origins = "*") @RestController public class ButtonController {
@Autowired private ButtonService buttonService;
@GetMapping("/query") public String query() { return buttonService.query(); }
@PostMapping("/add") public Map<String, Object> add(){ buttonService.addOne(); Map<String,Object> result = new HashMap<>(); result.put("msg","success"); return result; } }
|
ButtonDaoImpl
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| package com.example.button.dao.impl;
import com.example.button.dao.ButtonDao; import com.example.button.mapper.ButtonMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository;
@Repository public class ButtonDaoImpl implements ButtonDao {
@Autowired private ButtonMapper buttonMapper;
@Override public String query() { String number = buttonMapper.query(); return number; }
@Override public void addOne() { buttonMapper.addOne(); } }
|
ButtonDao
1 2 3 4 5 6 7
| package com.example.button.dao;
public interface ButtonDao { public String query();
public void addOne(); }
|
Button
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| package com.example.button.entity;
import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor;
import java.util.Objects;
@Data @NoArgsConstructor @AllArgsConstructor public class Button { private String number;
public String getNumber() { return number; }
public void setNumber(String number) { this.number = number; }
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Button button = (Button) o; return Objects.equals(number, button.number); }
@Override public int hashCode() { return Objects.hash(number); }
@Override public String toString() { return "Button{" + "number='" + number + '\'' + '}'; } }
|
ButtonMapper
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| package com.example.button.mapper;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update;
@Mapper public interface ButtonMapper { @Select("select number from button") String query();
@Update("update button set number = number + 1") void addOne();
}
|
ButtonServiceImpl
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| package com.example.button.service.impl;
import com.example.button.mapper.ButtonMapper; import com.example.button.service.ButtonService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;
@Service public class ButtonServiceImpl implements ButtonService {
@Autowired private ButtonMapper buttonMapper;
@Override public String query() { return buttonMapper.query(); }
@Override public void addOne() { buttonMapper.addOne(); } }
|
ButtonService
1 2 3 4 5 6 7
| package com.example.button.service;
public interface ButtonService { String query();
void addOne(); }
|
ButtonApplication
1 2 3 4 5 6 7 8 9 10 11 12 13
| package com.example.button;
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication public class ButtonApplication {
public static void main(String[] args) { SpringApplication.run(ButtonApplication.class, args); }
}
|
application.properties
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| server.port=44444 server.address=0.0.0.0
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/button_project?useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.username= # 需填写 spring.datasource.password= # 需填写
druid.initial-size=3 druid.max-active=5 druid.min-idle=2 druid.max-wait=3000 druid.remove-abandoned=true druid.remove-abandoned-timeout=5 druid.log-abandoned=true
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
|
注:数据库的用户名和密码字段需按照真实情况填写。
此时正常启动后端服务,使用postman(或其他调试工具)可以看到查询结果:

或者使用浏览器也可以访问:http://localhost:44444/query

前端
前端项目目录如下:

Button.vue
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| <template> <div class="container"> <el-button class="big-button" size="large" @click="addCount"> <span class="gradient-text">素念有成</span> </el-button> <h1>当前已祈愿:{{ count }}次</h1> </div> </template>
<script> import axios from 'axios';
export default { name: "Button", props: ["number"], data() { return { count: 0, }; }, created() { this.getCount(); }, methods: { async getCount() { try { const res = await axios.get('/api/query',{ responseType:'text' }); this.count = res.data; } catch (err) { console.error('请求失败:', err); } }, async addCount() { try { await axios.post('/api/add'); await this.getCount(); } catch (err) { console.error('更新失败:', err); } } } } </script>
<style> html { width: 100%; height: 100%; background: linear-gradient(to top right,#757F9A, #D7DDE8); }
.el-button { width: 15%; border-radius: 30px !important; background: linear-gradient(to top right,#757F9A, #D7DDE8); }
.gradient-text { background: linear-gradient(to top right,#fffef8, #baccd9); font-size: 150%; background-clip: text; color: transparent; }
.big-button:hover { filter: brightness(1.1); transition: filter 0.3s ease; } </style>
|
App.vue
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| <template> <div id="app"> <Button number="花猪"></Button> </div> </template>
<script> import Button from './components/Button.vue' import axios from 'axios';
export default { name: 'App', created() { axios.get("/api/query").then(function (response) { }) }, components: { Button } } </script>
<style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>
|
main.js
1 2 3 4 5 6 7 8 9 10 11
| import { createApp } from 'vue' import App from './App.vue' import ElementPlus from 'element-plus' import 'element-plus/dist/index.css' import 'font-awesome/css/font-awesome.min.css' import axios from 'axios'
const app = createApp(App)
app.use(ElementPlus) app.mount('#app')
|
vue.config.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| module.exports = { devServer: { host: '0.0.0.0', allowedHosts: 'all', client: { webSocketURL: 'auto://0.0.0.0:0/ws' }, proxy: { '/api': { target: 'https://button.cnhuazhu.cc.cd', changeOrigin: true, pathRewrite: { '^/api': '' } } } } }
|
注:这里target就按照如上代码写:https://button.cnhuazhu.cc.cd(不用修改,后文会按照这个申请域名)
在终端执行npm run serve启动前端项目。

申请免费域名
浏览器访问:https://dnshe.com

注册并登陆账号

点击【免费域名】
点击【+注册新域名】

在选择根域名一栏优先选择以下四种(否则不好接入cloudflare)

接着输入域名前缀,点击【确认注册】(这里我已经注册过了)

这样就有了一个免费域名。

接入Cloudflare
打开Cloudflare官网(https://www.cloudflare.com),注册并登录账号(这一步可能有点费劲)
可以在右侧账户菜单里切换语言。

按顺序依次点击 域名 -> 概览 -> 添加域名。

点击【连接域名】。

在域名栏里输入刚刚创建的域名,点击【继续】。
选择【免费计划】。
点击“继续前往激活”,这时Cloudflare会给出两个名称服务器地址。

说明:上图为网图。
本篇案例里真实给到我的两个名称服务器为:
接着回到域名管理网站,点击 域名管理 -> DNS服务器 -> 修改DNS服务器。

把原来的两个地址替换成Cloudflare提供的两个地址,点击【保存设置】。

回到Cloudflare,点击“我已更新域名服务器”
等待一段时间,显示“您的域现在受 Cloudflare 保护”
至此,Cloudflare接入已完成。
连接本地项目
首先启动后端项目。
现在要创建一条Cloudflare Tunnel隧道,把本地地址连接到刚才的域名。
在Cloudflare控制台点击 联网 -> Tunnels。

起一个隧道名称,然后点击【创建隧道】。

根据实际需求选择配置,点击 Download 链接下载cloudflare连接器。
安装完成cloudflare连接器之后,以管理员身份打开PowerShell,复制页面上提供的安装命令,粘贴并执行。


接着点击创建的隧道名称,进入管理页面。

点击【添加路由】(这里我已经添加过两个了)。

选择【已经发布的应用程序】。

填写以下三个内容,点击【添加路由】。

这时,浏览器访问【主机名+方法名】,就可以访问到后端编写对应方法的回显。

主机名就是路由添加成功后给到的主机名👇

打开前端项目,在终端键入npm run serve命令启动前端项目。

打开PowerShell,键入命令:cloudflared tunnel --url http://localhost:8080。

浏览器访问给出的地址就可以正常显示前端页面了,可以正常交互。

注:中途不能关闭PowerShell窗口,如果关闭之后想重新启动,需要在窗口中重新键入命令:cloudflared tunnel --url http://localhost:8080
后记(补充)
为什么访问公网https://baptist-parking-harvard-dts.trycloudflare.com ,就可以正常访问前端项目?
把整条链路拆开讲清楚:
- Cloudflared 隧道是“主动向外连接”,在本机终端执行
cloudflared tunnel --url http://localhost:8080,会主动连上 Cloudflare 的边缘节点,建立一条长通道。 Cloudflare 会分配这个临时域名:titans-solomon-wiley-carbon.trycloudflare.com,外网访客访问这个域名,流量会进到 Cloudflare 边缘。
- 流量会顺着隧道转发到电脑终端,Cloudflare 收到请求后,通过刚才建立好的隧道,把请求转发给本机的
http://localhost:8080,也就是 npm run serve 启动的 Vue CLI 开发服务。
- 接着Vue devServer 会返回页面 + 处理代理
npm run serve 监听 8080端口:
- 浏览器请求页面资源(html、js、css),devServer 直接返回 Vue 页面;
- 如果页面发起
/api/query、/api/add,会触发 vue.config.js 里写的 proxy 规则,把这个请求转发到后端公网地址;
- 后端返回响应内容,原路送回浏览器。
- HTTPS 是 Cloudflare 负责的。访客打开的是
https://xxx.trycloudflare.com,证书、HTTPS 加密由 Cloudflare 搞定;本机服务本身只跑普通 HTTP(8080),不需要自己配置证书。
所以整体完整流向为:
浏览器(公网)访问→ https://baptist-parking-harvard-dts.trycloudflare.com → Cloudflare 边缘节点 → Cloudflared 隧道 → 本机 localhost:8080(vue-cli serve)
- 页面资源:直接返回。
- /api 开头的请求:devServer 代理转发到 SpringBoot 后端 → 后端响应,原路返回给浏览器。
参考资料:免费域名 + Cloudflare Tunnel:把本地项目免费发布到公网_哔哩哔哩_bilibili