使用git自动部署静态博客到vps

sumcai 2022.05.08

写在前面

折腾博客也很长时间了,几乎市面上的静态博客框架都用过了,折腾来折腾去发现用哪个框架不重要,选择最适合自己的就行,还是要把重心放到博客内容上,牢记自己写博客的初衷。说回本文,每次写完博客后,如果使用git page, 那么只要推送到gh-pages分支即可,那如果博客部署在自己购买的服务器或者vps上,又该如何操作呢?

步骤

  1. 登录vps安装git

    1
    
    yum -y install git
    
  2. vps创建git用户

    1
    2
    3
    4
    5
    6
    7
    8
    
    adduser git
    passwd git
    vi /etc/ssh/sshd_config
    PermitRootLogin no
    PasswordAuthentication yes
    AllowUsers ubuntu
    AllowUsers git
    service sshd restart
    
  3. git用户免密码登录

    在个人电脑上执行(xx.xx.xx.xx是vps地址):

    1
    
    ssh-copy-id -i ~/.ssh/id_rsa.pub   git@xx.xx.xx.xx
    
  4. 初始化git仓库

    1
    2
    3
    
    mkdir /home/git/blog
    cd /home/git/blog
    git init --bare blog.git
    
  5. 配置git hook

    1
    2
    
    cd blog.git/hooks
    vi post-receive
    

    添加如下内容:

    1
    2
    
    #!/bin/sh
    git --work-tree=/home/git/html --git-dir=/home/git/blog/blog.git checkout -f
    

    添加执行权限

    1
    
    chmod +x post-receive
    
  6. 本地配置

    package.json添加内容:

    1
    2
    3
    
    "scripts": {
      "deploy": "bash deploy.sh"
    }
    

    添加deploy.sh,内容如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    
    # 确保脚本抛出遇到的错误
    set -e
       
    git add -A
    git commit -m "deploy blog"
       
    githubOriUrl=git@github.com:sumcai/blog.git
    githubUrlVps=git@xx.xx.xx.xx:/home/git/blog/blog.git
       
    git push $githubOriUrl master # 推送到主分支
       
    # 生成静态文件
    npm run build
       
    # 进入生成的文件夹
    cd public
    git init
    git add -A
    git commit -m "deploy"
    git push -f $githubUrlVps master # 推送到github gh-pages分支
    
  7. 部署提交

    1
    
    npm run deploy
    

参考:使用Git Hook自动部署Hexo到个人VPS