Required tools: Nginx, NodeJS, PM2 (NPM Package), KOA (NPM Package), Github Webhook.

Process:

  1. Pm2 maintains a NodeJS Web service
  2. After the user commits commit, a Webhook is triggered to send a request to the NodeJS Web service.
  3. The Web service receives the request and executes the automatic execution script

1. Write the automatic deployment script and Web service

Create the automatic build script directory

> mkdir git-webhooks && cd git-webhooks
Copy the code

Create hook: blog-hook.js

My blog here for/home/shancw/Project/blogs

  • git pull origin master
  • NPM run build # Generate hexo static file
const util = require("util");
const exec = util.promisify(require("child_process").exec);
async function main() {
  await exec("cd /home/shancw/Project/blogs && git pull origin master");
  await exec("cd /home/shancw/Project/blogs && npm run build");
}

module.exports = {
  main,
};
Copy the code

Create web service (open port 4001): index.js

const Koa = require("koa");

const app = new Koa();
const exec = require("./blog-hook.js").main;
app.use(async (ctx) => {
  console.log("blog webhook trigger! start deploy");
  exec();
});

app.listen(4001);
Copy the code

Directory structure:

  • git-webhooks
    • index.js
    • blog-hook.js

2. Configure nginx forwarding

Linux nginx location: /etc/nginx custom configuration location /etc/nginx/conf.d

Add the github Webhook web service address in conf.d

www.limiaomiao.site/auto-deploy… -> http://localhost:4001/

# blog-deploy.confserver { server_name www.limiaomiao.site limiaomiao.site; location /auto-deploy/ { proxy_pass http://localhost:4001/; }}Copy the code

Add the hexo static file agent under conf.d

# blog static.conf
server {
    listen 80;
    server_name blog.limiaomiao.site;
    root /home/shancw/Project/blogs/public;   # This is our resource file directory
    index index.html index.htm index.nginx-debian.html;
}
Copy the code

Adjust the URL of the _config.yml file of the Hexo blog

# URL
## If your site is put in a subdirectory, set url as 'http://yoursite.com/child' and root as '/child/'
url: http://blog.limiaomiao.site/
root: /
Copy the code

Enable Github Hook under the Github Blog project

Payload URL Is the URL forwarded by nginx in Step 2