最近写了一个前后端分离的项目,前端用的是vue,因此记录一下将该项目部署到服务器的整个过程。

1.首先,在控制台输入npm run build命令(或者npm run build:prod)。该命令用于将前端vue打包。打包后的文件是dist文件夹。(开发阶段的一些配置在打包后会失效,比如开发阶段配置的后端域名和端口,下文会给出解决方法)

 

 2.打包完成之后,就可以用nginx来部署前端项目了。nginx在这里的作用是反向代理,说得具体一点就是将我们服务器上的文件比如C://dist/index.html映射为127.0.0.1:9000,nginx的安装很简单我就不赘述了,主要说一下nginx.conf的配置。

    server {
        listen       9000;
        server_name  localhost;

        location /user/ {
            proxy_pass   http://127.0.0.1:8080/user/;
        }

		location /workOrder/ {
            proxy_pass   http://127.0.0.1:8080/workOrder/;
        }
		
		location / {
            root   C://dist;
            index  index.html index.htm;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

    }

上面nginx.conf的配置分为两个部分,第一个部分是实现前端vue的映射,即将C://dist/index.html映射为127.0.0.1:9000。

location / {
            root   C://dist;
            index  index.html index.htm;
        }

第二部分是将后端请求指向后端项目。在前端项目中我会发送请求给后端程序请求数据,如:127.0.0.1:8080/user/login,在开发阶段我们可以在vue.config.js中配置后端ip和端口,但是打包后这些配置会失效,因此,我们需要通过nginx将后端请求指向后端项目。在我的后端有两种前缀user和workOrder,因此,配置如下。

location /user/ {
            proxy_pass   http://127.0.0.1:8080/user/;
        }

		location /workOrder/ {
            proxy_pass   http://127.0.0.1:8080/workOrder/;
        }

至此,前端项目就已经部署完成了。

3.后端程序部署,后端程序打包命令为:mvn clean package,打包后的程序在项目目录下的target文件夹中。

 4.最后一步就是启动后端程序,我用的java,启动命令是java -jar xxx.jar

更多推荐

vue项目打包部署在windows或linux服务器上