本篇文章为 hexo 服务器端搭建, 完成自动化部署.
安装 Git, 请参考 Windows7 安装 Git 客户端
连接 GitHub, 请参考 Window7 下配置 SSH 连接 GitHub
本机安装 hexo, 请参考 CentOS 搭建 hexo 博客, 实现自动化部署 (一)
前期准备工作
- adduser Git #创建一个 Git 账户, 启用 Linux
- ll /etc/sudoers
- chmod 740 /etc/sudoers
- VIM /etc/sudoers #添加 sudo 权限
- ## Allow root to run any commands anywhere
- root ALL=(ALL) ALL
- Git ALL=(ALL) ALL
- chmod 400 /etc/sudoers
各种安装 -Git Node.JS nginx
- yum install Git
- yum install -y Node.JS
- sudo yum install -y nginx
配置 nginx
- sudo vi /etc/nginx/nginx.conf
- ##########################################################################################
- server {
- listen 80 default_server;
- listen [::]:80 default_server;
- server_name www.igkor.com igkor.com;
- root /usr/share/nginx/html/blog; #设置 nginx 跟目录, 我这里是 / usr/share/nginx/HTML/blog
- index index.HTML index.htm
- # Load configuration files for the default server block.
- include /etc/nginx/default.d/*.conf;
- location / {
- }
- ##########################################################################################
- sudo mkdir -p /usr/share/nginx/HTML/blog #创建根目录
- sudo chown -R Git:Git /usr/share/nginx/HTML/blog #将组和拥有者变为 Git
- service nginx restart #重启应用
安装 GitHub-webhook-handler
- cd /usr/share/nginx/HTML
- NPM install -g GitHub-webhook-handler #安装 GitHub-webhook-handler
- ### 如果没有安装成功, 可以选择法 2 来安装
- NPM install -g cnpm --registry=http://r.cnpmjs.org
- cnpm install -g GitHub-webhook-handler
创建 deploy.sh, 脚本内容如下:
- cd /usr/share/nginx/HTML/blog
- Git reset --hard
- Git pull origin master
- hexo generate
创建 webhooks.JS, 脚本内容如下:
1, 如果在 deploy.log 看到 Error: Cannot find module 'github-webhook-handler', 则说明 GitHub-webhook-handler 路径没有配置正确, 需要查看 GitHub-webhook-handler 安装在了哪里, 我的在 /usr/lib/node_modules/GitHub-webhook-handler
2, 我的端口使用的是 6666, 需要确认安全组策略是否放开 6666.
- var http = require('http')
- var createHandler = require('/usr/lib/node_modules/github-webhook-handler')
- var handler = createHandler({ path: '/', secret: 'NIxCkDI5BPG4' })
- // 上面的 secret 保持和 GitHub 后台设置的一致
- function run_cmd(cmd, args, callback) {
- var spawn = require('child_process').spawn;
- var child = spawn(cmd, args);
- var resp = "";
- child.stdout.on('data', function(buffer) { resp += buffer.toString(); });
- child.stdout.on('end', function() { callback (resp) });
- }
- http.createServer(function (req, res) {
- handler(req, res, function (err) {
- res.statusCode = 404
- res.end('no such location')
- })
- }).listen(6666)
- handler.on('error', function (err) {
- console.error('Error:', err.message)
- })
- handler.on('push', function (event) {
- console.log('Received a push event for %s to %s',
- event.payload.repository.name,
- event.payload.ref);
- run_cmd('sh', ['./deploy.sh',event.payload.repository.name], function(text){ console.log(text) });
- })
启动 webhooks.JS, 完成自动化部署.
- nohup node webhooks.JS> deploy.log & #deploy.log 可以用来排错.
- ll /usr/share/nginx/HTML/blog #愉快的查看文件更新时间吧, 自动化部署已经完成.
来源: http://www.jianshu.com/p/a2dfa0386860