NodeJS项目迁移兼Ubuntu下NodeJS环境部署

时间:2021-03-25 09:25:45

前言

之前做的几个项目都托管在阿里云服务器,但是最近要到期了。想着到底要不要续期,毕竟100/月。后面看着阿里云有个活动,800/三年。果断买下。环境部署折腾了一天,其中也遇到几个坑。

目录


一、安装环境
1.1 安装NodeJS环境
1.2 安装版本控制软件Git
1.3 安装MongoDB数据库
1.4 安装Nginx 二、导入数据 三、安装项目 四、部署项目
4.1 Nginx配置
4.2 启用HTTPS
4.3 使用PM2部署项目
4.4 开启阿里云外网访问 五、踩坑记录
5.1 数据库导入失败
5.2 PM2部署失败

一、安装环境

为了保证项目运行不出问题,在新服务器安装和原服务器一致的环境。项目迁移历时一天,两台服务器的系统都是Ubuntu 16.04 64位。

1.1 安装NodeJS环境

自带的NodeJS版本是4.2.6,版本有点低,使用npm的n模块更新到最新版。

安装NPM


sudo apt-get install npm

使用淘宝源

阿里云访问npm的速度非常慢,这里通过设置,让NPM从淘宝镜像更新模块


npm set registry https://registry.npm.taobao.org // 设置从淘宝镜像更新
npm set disturl https://npm.taobao.org/dist
npm cache clean // 清除缓存

更新NodeJS


npm install n // 更新NodeJS的模块
n stable // 更新到最新稳定版
node -v // v8.2.1

1.2 安装版本控制软件Git


sudo apt-get install git

1.3 安装MongoDB数据库


sudo apt-get install mongodb // 安装MongoDB
service mongodb start // 启动服务
mongod // 进入交互式控制台,能加入说明启动成功,ctrl+c退出

1.4 安装Nginx


sudo apt-get install nginx // 安装Nginx

二、导入数据

把以前的数据库完整的迁移过来

从源服务器导出数据库


mongodump -h localhost --port 27017 -d test -o database_dump

导入MongoDB数据库


mongorestore -d test database_dump/test

三、安装项目

项目是在Github开源,直接拉取就行。


git clone https://github.com/bergwhite/nchat.git // 克隆项目
cd nchat // 进入目录
npm install 安装模块
npm run build

四、部署项目

4.1 Nginx配置


vim /etc/nginx/nginx.conf // 编辑Nginx的配置 http { server { listen 80;
server_name hostName;
rewrite ^(.*) https://$server_name$1 permanent;
} server { listen 443 ssl;
server_name hostName;
ssl on;
# SSL证书会插入到这里 # 完整根目录
location / { root /*/*/*;
index index.html; } # 反向代理V2EX API到本地,解决跨域问题
location /api/ { proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass https://www.v2ex.com/api/; } }
...

4.2 启用HTTPS


sudo apt-get update // 更新软件源
sudo apt-get install software-properties-common // 安装
sudo add-apt-repository ppa:certbot/certbot // 添加仓库
sudo apt-get update // 更新软件源
sudo apt-get install python-certbot-nginx // 安装 sudo certbot --nginx // 生成证书(自动添加到Nginx)
sudo certbot --nginx certonly // 生成证书(手动添加到Nginx)

4.3 使用PM2部署项目


sudo apt-get install pm2 // 安装pm2

4.4 开启阿里云外网访问

在安全组里添加需要放行的NodeJS项目端口即可。

五、踩坑记录

5.1 数据库导入失败

导入数据库的时候,有一个Collection没有导入成功


Assertion failure amt == (size_t)( size - 4 ) src/mongo/tools/tool.cpp 330

解决方案


把报错的Collection单独导出,然后重新导入到新服务器的数据库

5.2 PM2部署失败

运行下面的代码会失败


pm2 start -i 0 --name test ./bin/www

解决方案

使用fork模式启动


pm2 start --name nchat3 ./bin/www

参考连接