前后端分离项目的部署 - Levyy
Levyy是最近写的一个提交电子版作业的平台。这个项目花了约3天时间基本写完,因为是第一次部署前后端分离的项目,所以写篇文章把部署过程记录下来。
Levyy的前端部分使用Vue+Vuetify,后端HomeworkUpload使用Spring Boot框架编写。
之前测试的时候是部署到阿里云Ubuntu 18.04,因为一些关于备案的原因,所以最终上线时选择了Vultr的CentOS 7 VPS。
安装环境
操作系统为CentOS 7。
首先更新系统
yum update
之后安装JRE(Java 运行时环境),设置Java环境变量。
yum install java-11-openjdk-devel
cat > /etc/profile.d/java11.sh <<EOF
export JAVA_HOME=$(dirname $(dirname $(readlink $(readlink $(which javac)))))
export PATH=\$PATH:\$JAVA_HOME/bin
export CLASSPATH=.:\$JAVA_HOME/jre/lib:\$JAVA_HOME/lib:\$JAVA_HOME/lib/tools.jar
EOF
source /etc/profile.d/java11.sh
确认安装:
java -version
之后安装Tomcat9,考虑到之前踩过的坑,建议不要通过yum安装。
apt-get install nginx
apt-get install tomcat9
wget https://www-us.apache.org/dist/tomcat/tomcat-9/v9.0.20/bin/apache-tomcat-9.0.20.tar.gz
tar xvf apache-tomcat-9.0.20.tar.gz -C /opt/tomcat --strip-components=1
firewall-cmd --zone=public --permanent --add-port=80/tcp
firewall-cmd --reload
systemctl start nginx
systemctl enable nginx
/usr/share/nginx/html/
之后打开浏览器(80/8080),确认安装成功!
当然,还有编译前端要用到的nodejs、npm等等
配置nginx
我们需要将nginx和Tomcat配合起来使用,因此需要使用nginx的反向代理将调用后端的请求转发到Tomcat(127.0.0.1:8080)上面。
在Levyy中,后端的请求都放在/api/路径下面,所以可以通过正则表达式匹配把这些请求转发到Tomcat上。
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_min_length 256;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
location ^~ /homeworkupload/api/ {
proxy_pass http://127.0.0.1:8080;
proxy_redirect off;
proxy_set_header HOST $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size 20m;
client_body_buffer_size 128k;
proxy_connect_timeout 90;
proxy_send_timeout 90;
proxy_read_timeout 90;
proxy_buffer_size 4k;
proxy_buffers 4 32k;
proxy_busy_buffers_size 64k;
proxy_temp_file_write_size 64k;
}
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ @router;
index index.html;
}
location @router {
rewrite ^.*$ /index.html last;
}
配置后端
在最初测试时,Levyy后端使用的是Spring Boot内置的Tomcat容器,打包成jar直接启动。但这种方式容易导致崩溃等问题,因此需要修改打包成war放入Tomcat当中。
首先需要修改HomeworkUploadApplication
里面的内容,使其能够支持打包后使用war启动。
@SpringBootApplication
public class HomeworkUploadApplication extends SpringBootServletInitializer {
// run with war
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(HomeworkUploadApplication.class);
}
// run with jar
public static void main(String[] args) {
SpringApplication.run(HomeworkUploadApplication.class, args);
}
}
接下来还要配置build.gradle(Levyy使用Gradle构建):
// ...
apply plugin: 'war'
// ...
dependencies {
// ...
providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
// ...
}
之后执行build,成功生成war文件。
本作品采用 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议 进行许可。