nodejs服务器部署教程一

第一篇教程紧紧让你输出一个hello world

环境介绍

服务器环境:ubuntu(16.04)64位
本地环境:windows10 64位
连接工具:mobaxterm

ubuntu安装和基本配置

我的ecs是在阿里云买的,购买的时候镜像选择ubuntu16.04,现在在搞活动比较便宜,我买的香港地区的不用备案,购买后本地打开mobaxterm,点击session,输入ip确定,输入root,然后输入密码,会看到下面的界面:

连接远程服务器,接下来我参考了阮一峰老师的这篇文章
addgroup wmui添加用户组
useradd -d /home/wmui -s /bin/bash -m wmui创建wmui用户
passwd wmui设置密码,如果忘记密码,也可用此命令重置密码
usermod -a -G wmui wmui 添加用户到组
visudo 设置sudo权限
然后会跳转到下面页面

root ALL=(ALL:ALL) ALL下面添加wmui ALL=(ALL) NOPASSWD: ALL
ctrl+x保存退出
接下来打开一个新的窗口,测试是否登陆成功

ssh无密码登陆配置

首先你需要在本地安装git并生成id_rsa.pub,打开命令行
在本地生成公钥和私钥:
ssh-keygen -t rsa -b 4096 -C "1719442545@qq.com"
在服务器生成公钥和私钥:
ssh-keygen -t rsa -b 4096 -C "1719442545@qq.com"
在服务器窗口输入:
echo "[your public key]" > ~/.ssh/authorized_keys将本机的公钥拷贝到服务器的authorized_keys文件

完成以上操作,测试是否生效,重启服务:sudo service ssh restart新打开一个窗口,输入用户名回车,登陆成功

安全项配置:

我在搭建时候没有设置这一项,所以没有测试这项
编辑SSH配置文件/etc/ssh/sshd_config:修改port为1025到65536之间的任意一个整数
在末尾添加: AllowUsers [username]
此时登陆时需要端口号: -p [25000] [username]
fail2ban系统监控软件安装:
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install fail2ban
sudo service fail2ban status 查看fail2ban运行状态
sudo service fail2ban stop 关闭fail2ban
sudo service fail2ban start 开启fail2ban

nodejs环境搭建

安装常用软件
sudo apt-get install vim openssl build-essential libssl-dev wget curl git
nvm安装
wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.33.2/install.sh | bash
打开新的窗口
nvm install v8.9.1
nvm use 8.9.1
nvm alias default 8.9.1 默认版本
安装常用node包
npm i pm2 webpack vue-cli -g

nginx服务器代理设置

sudo apt-get install nginx 通过nginx -v查看版本号
打开/etc/nginx/conf.d/文件夹,创建配置文件test-8081.conf,内容如下:

upstream hello {
    server 127.0.0.1:8081;
}

server {
    listen 80;
    server_name hello.86886.wang;

    location / {
        proxy_set_header Host  $http_host;
        proxy_set_header X-Real-IP  $remote_addr;  
        proxy_set_header X-Forwarded-For  $proxy_add_x_forwarded_for;
        proxy_set_header X-Nginx-proxy true;
        proxy_pass http://hello;
        proxy_redirect off;
    }
}

解析你的域名到你的服务器ip,例如解析hello.86886.wang
sudo nginx -t 查看是否配置成功

sudo nginx -s reload 重启服务器
注意:我在第一次配置的时候遇到了黄色警告,但是不影响使用,如果你也遇到了,向下面一样解决
打来etc/hosts,在127.0.0.1 localhost下面添加127.0.1.1 iZj6cas9txr6crspqecn4zZ其中 iZj6cas9txr6crspqecn4zZ是你的ecs实例名称

ok完成以上操作,接下来开始写hello world

创建和部署hello world

以root用户身份在根目录下创建www目录,www目录下创建hello文件夹,里面就一个文件,hello.js,内容如下:

const http = require('http')
http.createServer(function(req,res) {
res.writeHead(200,{'Content-Type':'text/plain'})
res.end('hello world')
}).listen(8081)

console.log('server test')

进入到www下hello文件夹下
hello world测试:
pm2 start hello.js
pm2 list 查看启动的应用
pm2 show hello 查看详细信息
pm2 logs 查看当前信息
pm2 stop hello 停止hello
pm2 delete hello 删除hello

如图所示表示启动成功,输入hello.86886.wang就可以看到hello world了
接下来计划:
nodejs服务器部署教程二:部署一个基于vue的项目到线上
nodejs服务器部署教程三:部署基于nodejs+vue+mongodb的项目
nodejs服务器部署教程四:实现https

本文摘自:https://segmentfault.com/a/1190000010098126

原文地址:https://www.cnblogs.com/momoyan/p/9128037.html