node服務器部署系列———PM2自動化
在進行node部署完成後,日常開發運維中免不了需要經常需要更新維護服務器代碼,但是一次又一次的登錄服務器,手動更新代碼實在是非常麻煩,因此我們需要一套自動化部署方案,大家經常用的方案有很多,在此只講講PM2的自動化
準備
本地: pm2
git
node(npm)
ssh(生成密匙)
服務器:pm2
git
node(npm)
nginx
ssh(生成密匙)
本地可以clone
/ push
(拉取/提交)代碼到git
服務器可以clone
遠程git的代碼
設置部署配置文件 ecosystem.json
在項目根目錄生成ecosystem.json
文件,用作配置
{
"apps" : [{
"name": "server API", //項目名稱
"script": "app.js", //啓動入口文件
"env": {
"COMMON_VARIABLE": "true"
},
"env_production" : {
"NODE_ENV": "production"
}
}],
"deploy" : {
"production" : {
"user" : "root", //登錄服務器用戶名
"host" : ["xxx.xxx.xxx.xxx"], //服務器地址ip
"port": "22", //登錄的ssh端口
"ref" : "origin/master", //服務器應該拉取的分支
"repo" : "[email protected]:chuang_zao_zhi/server-api.git", //服務器應該拉取的git地址
"path" : "/www/server", //拉取後放置的目錄位置
"post-deploy" : "npm install", //拉取完後要執行的指令,多個指令用 “ ; ”分割
"ssh_options": "StrictHostKeyChecking=no",
"env" : {
"NODE_ENV": "production"
}
}
}
}
上面是經典的PM2部署配置文件,創建完成後就可以進行下一步安裝部署:
先確保git代碼爲最新
pm2 deploy ecosystem.json production setup
本地運行完上面指令後,PM2會在目標目錄生成項目部署文件,中間會需要多次輸入服務器密碼,按要求輸入即可
部署完後再來進行發佈:
運行pm2 deploy ecosystem.json production
上面命令會發布最新的git代碼到服務器部署就此完成
有幾個需要注意的點
-
首次部署完後服務器使用命令
pm2 list
查看項目狀態是否爲online
,如果不是,手動pm2 restart
啓動下,以後更新代碼僅僅需要運行pm2 deploy ecosystem.json production
即可 -
進行部署時會多次要求輸入服務器密碼,非常麻煩,如果不想要輸入可以使用ssh免蜜方式登錄,就像git的ssh一樣,通常使用
ssh-copy-id
來進行密匙複製
使用
ssh-copy-id -i .ssh/id_rsa.pub [email protected]
將公鑰複製到遠程機器中(ssh-copy-id 將key寫到遠程機器的 ~/.ssh/authorized_key.文件中)
ssh-copy-id
在linux裏自動帶有,在mac上可以通過brew
安裝,但唯獨沒有在windows上有支持,所以我們需要自己創建一個.sh
腳本文件來運行命令:
創建ssh-copy-id.sh
腳本文件,寫入一下內容,一般放在ssh目錄附近,便於使用
#!/bin/sh
# Shell script to install your public key on a remote machine
# Takes the remote machine name as an argument.
# Obviously, the remote machine must accept password authentication,
# or one of the other keys in your ssh-agent, for this to work.
ID_FILE="${HOME}/.ssh/id_rsa.pub"
if [ "-i" = "$1" ]; then
shift
# check if we have 2 parameters left, if so the first is the new ID file
if [ -n "$2" ]; then
if expr "$1" : ".*\.pub" > /dev/null ; then
ID_FILE="$1"
else
ID_FILE="$1.pub"
fi
shift # and this should leave $1 as the target name
fi
else
if [ x$SSH_AUTH_SOCK != x ] ; then
GET_ID="$GET_ID ssh-add -L"
fi
fi
if [ -z "`eval $GET_ID`" ] && [ -r "${ID_FILE}" ] ; then
GET_ID="cat ${ID_FILE}"
fi
if [ -z "`eval $GET_ID`" ]; then
echo "$0: ERROR: No identities found" >&2
exit 1
fi
if [ "$#" -lt 1 ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
echo "Usage: $0 [-i [identity_file]] [user@]machine" >&2
exit 1
fi
{ eval "$GET_ID" ; } | ssh $1 "umask 077; test -d ~/.ssh || mkdir ~/.ssh ; cat >> ~/.ssh/authorized_keys && (test -x /sbin/restorecon && /sbin/restorecon ~/.ssh ~/.ssh/authorized_keys >/dev/null 2>&1 || true)" || exit 1
cat <<EOF
Now try logging into the machine, with "ssh '$1'", and check in:
.ssh/authorized_keys
to make sure we haven't added extra keys that you weren't expecting.
EOF
這樣就能愉快的使用 ssh-copy-id
了,運行後會發現本地登錄服務器將不再需要鍵入密碼,可以直接登錄
本次講述使用root
用戶,如果使用自定義的用戶,記得給新的用戶相關目錄權限,或直接給予管理員最高權限,防止權限不足