Nginx负载均衡的lnmp环境初始化脚本

一、安装必要的工具和修改系统配置

wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo && yum makecache && yum install screen && yum install nodejs && npm install -g pm2@2.10.2 && vi /etc/sudoers/

www ALL=(ALL) NOPASSWD:ALL

二、安装LNMP环境

wget http://soft.vpser.net/lnmp/lnmp1.6.tar.gz -cO lnmp1.6.tar.gz && tar zxf lnmp1.6.tar.gz && cd lnmp1.6 && ./install.sh lnmp

三、克隆代码到本地并修改配置

git clone 
# 替换脚本

四、创建虚拟站点

cd /usr/local/nginx/conf/vhost/ && vi master.conf && lnmp nginx restart

master.conf

server{
    listen 80;
    server_name domain;
    location / {
        proxy_pass http://slaveServers;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Host $host;
        proxy_set_header Connection "Upgrade";
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto  $scheme;
    }
}
upstream slaveServers{
        server 10.0.10.81 weight=5;
}

五、创建webhook

cd /home/wwwroot/ && vi webhook.js && su www && pm2 start webhook.js

webhook.js

const httpPort = 12001;
var exec = require('child_process').exec;
var http = require('http');
var colors = require("colors");
var httpServer = http.createServer(function(req, res) {
    res.writeHead(200, {
        'Content-Type': 'text/plain;charset=utf-8'
    });
    if (req.method.toUpperCase() != 'POST' && req.method.toUpperCase() != 'GET') {
        res.end("Request by GET/POST only!");
        return;
    }
    switch (req.url) {
        case "/favicon.ico":
            // ignore the web icon request
            res.end();
            break;
        default:
            debug("Webhook run " + ("async").red + " --->  " + req.url);
            res.end("Webhook Success");
            exec("cd /home/wwwroot" + req.url + " && git pull", function(err, stdout, stderr) {
                if (err) {
                    console.log(stdout.red);
                    debug("Webhook error!");
                } else {
                    console.log(stdout.blue);
                    debug("Webhook success!");
                }
            });
    }
});
httpServer.listen(httpPort);
debug("Webhook start success!");

function debug(msg) {
    console.log(getTime().yellow + "\t" + msg);
}

function getTime() {
    var now = new Date();
    var hours = now.getHours();
    var minutes = now.getMinutes();
    var seconds = now.getSeconds();
    if (hours < 10) {
        hours = "0" + hours;
    }
    if (minutes < 10) {
        minutes = "0" + minutes;
    }
    if (seconds < 10) {
        seconds = "0" + seconds;
    }
    return hours + ":" + minutes + ":" + seconds;
}