Linux 环境一键打包发布脚本

以下脚本作为工作笔记沉淀,记录一下。

deploy.sh

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#!/bin/sh

# 本脚本用于开发环境,直接打包需要发布的文件,然后通过 SSH 复制到服务器并直接通过 pm2 启动执行。
# 主要功能:
# - 打包本地文件
# - 剪切备份 $BUILDDIR 目录(实际程序执行的目录)
# - 复制到远程服务器 $BUILDDIR 目录
# - 解压
# - 使用备份的配置文件覆盖
# - 启动程序

WORKROOT=/path/to/your/dir/on/remote/server
BUILDDIR=$WORKROOT/build

SKEY=" -i ~/.ssh/your-ssh-key-file"
SCHANNEL="your-ssh-user@your-ssh-host"
SROOT=$SCHANNEL:$WORKROOT
SBUILD=$SCHANNEL:$BUILDDIR
DATE=`date '+%Y-%m-%d%H%M%S'`

. ./bash/pack.sh $DATE

echo "copying files..."
scp $SKEY -r ./build/build-$DATE.zip $SROOT
ssh $SKEY $SCHANNEL mv $BUILDDIR $BUILDDIR-$DATE

echo "unzipping files..."
ssh $SKEY $SCHANNEL unzip -q $WORKROOT/build-$DATE.zip -d $BUILDDIR
#ssh $SKEY $SCHANNEL cp $WORKROOT/bak/etc/config.json $BUILDDIR/etc/config.json

echo "starting..."
CMD="cd $BUILDDIR ; pm2 restart ./etc/pm2.config.json"
ssh $SKEY $SCHANNEL $CMD

pack.sh

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#!/bin/sh

# 需要在项目根目录执行,如:./bash/pack.sh

DATE=$1

if [ -z "$DATE" ] ; then
DATE=`date '+%Y-%m-%d%H%M%S'`
fi

# 备份本地配置,使用生产环境配置
mv ./etc/config.json ./etc/config.dev.json.bak
mv ./etc/config.prod.json ./etc/config.json

echo "packing files..."
zip -r -q ./build/build-$DATE.zip ./bin
zip -r -q ./build/build-$DATE.zip ./dal
zip -r -q ./build/build-$DATE.zip ./etc -i ./etc/*.json
zip -r -q ./build/build-$DATE.zip ./controller
zip -r -q ./build/build-$DATE.zip ./middlewares
zip -r -q ./build/build-$DATE.zip ./models
zip -r -q ./build/build-$DATE.zip ./node_modules
zip -r -q ./build/build-$DATE.zip ./public
zip -r -q ./build/build-$DATE.zip ./routes
zip -r -q ./build/build-$DATE.zip ./utils
zip -r -q ./build/build-$DATE.zip ./views
zip -r -q ./build/build-$DATE.zip ./app.js

# 还原配置
mv ./etc/config.json ./etc/config.prod.json
mv ./etc/config.dev.json.bak ./etc/config.json