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 node v8.1.3
nvm use node v8.1.3
nvm alias default v8.1.3 默認版本
安裝常用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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM