saber酱的抱枕

Fly me to the moon

09/24
16:31
软件

在 Debian 上运行 Nodejs 网站后台

我在本地建立了一个网站,前台使用 Vue.js,后台使用 Nodejs 的 Koa.js 框架。现在打算上架到服务器,服务器的操作系统是 Debian。记录一下操作步骤。

1. 把临时域名替换成正式域名

因为在本地开发时,前后台使用的都是本地 url,如:

// 前台
http://localhost:8080
// 后台
http://localhost:3000

上线时需要使用正式的域名,所以需要把项目中的本地 url 替换成真实的域名。

2. 建立前台网站

网站前台使用的网址是 https://note.pixiv.download

先 build 项目,把 dist 文件上传到服务器,设置权限。

之后在 nginx 里建立这个网站,并配置 https 证书。

之后,访问 https://note.pixiv.download/ 成功即可。

ps:因为采用了 Vue 路由的 history 模式,所以需要在 nginx 配置的 location 里加一句:

$uri $uri/ /index.html; # 防止刷新 404

3. 在服务器上安装 Nodejs

在 Debian 上安装 Nodejs LTS 版本,也就是 10.x 版本,依次执行这两条命令:

curl -sL https://deb.nodesource.com/setup_10.x | bash -
apt-get install -y nodejs

命令来源自 nodesource/distributions 项目的指南。

4. 安装守护进程 forever

我们平时会用类似下面的方式启动 Nodejs 项目:

npm run serve
// 或者
node app.js

但是如果我们退出了终端,这个 Nodejs 进程就会被关闭,所以需要守护进程。

全局安装守护进程 forever:

npm i -g forever

使用方法:

forever start app.js     #启动应用
forever stop app.js      #关闭应用
forever restart app.js   #重启应用
forever stopall          #关闭所有应用
forever restartall       #重启所有应用
forever list             #显示所有运行的应用

5. 建立网站后台,并反向代理

网站后台对外使用的网址是 https://notes.pixiv.download,但其实因为网站后台是用 Nodejs 来运行,所以实际运行的后台网址是服务器本地的 http://localhost:3000。所以我需要给后台网站建立反向代理,当服务器接收到对后台网址 notes.pixiv.download 的请求时,将其转发到 localhost:3000

部分配置文件如下:

server {
	listen 443 ssl;
	server_name notes.pixiv.download;
	# 因篇幅原因,在这里省略一些配置	

	location / {
		proxy_pass	http://127.0.0.1:3000; # 反向代理
	}
}

6.运行后台

进行一些配置之后,用 forever 启动后台网站。前后台测试无误,任务完成。

前台网址:
https://note.pixiv.download/

在 Debian 上运行 Nodejs 网站后台