SpringBoot、Vue项目部署到Ubuntu服务器
前置情景
本文章基于Ubuntu 20.04平台部署。Vue项目通过nginx反向代理转发到SpringBoot端口。本文中,前端请求到后端的url地址会加上前缀 /api,举例:
前端向后端请求:
axios.post('/api/operationsummary/sysuser/getIdListByName')
后端实际的请求格式:
/operationsummary/sysuser/getIdListByName
后续会利用前端增加的 /api/ 在nginx做代理,使得前端可以跟后端通信。
部署
在Ubuntu中安装JDK1.8
输入命令:
sudo apt-get install openjdk-8-jre
等待安装完成,完成后输入java -version可验证是否安装成功。
部署SpringBoot项目
-
在项目根目录输入mvn clean package,项目目录下会生成 /target 文件夹,把里面的***.jar上传到服务器。
-
输入 nohup java -jar ***.jar >log.txt &,让程序后台运行,并把日志输出到log.txt文件。
注意:记得检查spring boot项目配置文件中访问数据库的IP地址是否正确
部署Vue项目
安装nginx
-
输入命令:
sudo apt install nginx
-
输入以下命令检查nginx是否安装成功,或者在地址栏输入ip地址。
sudo systemctl status nginx
若输入命令后有对应显示,或在地址栏上输入ip地址后能访问,则说明安装成功。
配置nginx
-
进入 /etc/nginx/conf.d 目录,若没有 default.conf 文件,则创建一个(touch default.conf),我们对nginx的配置就使用该目录下的 default.conf 文件。
-
在开发环境中,到vue项目根目录下,输入 npm run build ,项目根目录下会生成 /dist 文件夹。
Ubuntu服务器中/usr/share/nginx/html/目录长这样:
现在要把/dist文件夹下的文件替换到/usr/share/nginx/html/中,替换后长这样:
-
修改/etc/nginx/conf.d下的 default.conf ,把以下内容复制进去,注意把 location /api/ 下的 proxy_pass ip地址修改为后端springboot所在的地址和springboot服务的端口:
server { listen 80; listen [::]:80; server_name localhost; #access_log /var/log/nginx/host.access.log main; location / { root /usr/share/nginx/html; index index.html index.htm; } #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } location /api/ { proxy_pass http://换成你自己服务器的ip:换成你自己服务器后端的端口/; } # proxy the PHP scripts to Apache listening on 127.0.0.1:80 # #location ~ \.php$ { # proxy_pass http://127.0.0.1; #} # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # #location ~ \.php$ { # root html; # fastcgi_pass 127.0.0.1:9000; # fastcgi_index index.php; # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; # include fastcgi_params; #} # deny access to .htaccess files, if Apache's document root # concurs with nginx's one # #location ~ /\.ht { # deny all; #} }
-
重启nginx服务:
nginx -s reload
注意:如果打开/etc/nginx/nginx.conf文件后看到类似
include /etc/nginx/conf.d/.conf;
include /etc/nginx/sites-enabled/;的两行代码块,删去一个不需要的即可,例如我把第二行注释掉,只保留/etc/nginx/conf.d/default.conf:
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
然后输入nginx -s reload重启nginx服务即可
-
打开浏览器,地址栏输入服务器IP地址,看到项目页面则说明部署成功。