Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux綜合 >> 學習 Linux

用 Shell 撰寫 Nginx 一鍵自動部署腳本

一、功能描述

1. 安裝編譯依賴套件,從軟體源下載自訂版本的 Nginx 包,並建立 Nginx 使用者與群組。

2. 編譯安裝並初始化 Nginx 配置。

3. 啟動 Nginx 並檢查運行狀態。

二、實作

#!/bin/bash
# eastmoney public tools
# version: v1.0.1
# create by XuHoo, 2016-9-28

# function environment()
function environment() {
    if [[ "$USER" != "root" ]]; then
        echo "Current user is not root"
        return 1
    fi
    yum -y install wget curl pcre pcre-devel zlib zlib-devel gcc gcc-c++ &> /tmp/nginx_install.log
    # getUrl: 自訂下載來源位址
    # getUrl='https://172.16.1.1\nginx-1.8.1.tar.gz'
    wget -P /tmp/ $getUrl/nginx.tar.gz
    grep "nginx" /etc/passwd > /dev/null
    if [[ $? -ne 0 ]]; then
        # 檢查並建立使用者與群組
        groupadd nginx
        useradd -M -g nginx -s /sbin/nologin nginx
    fi
    cd /tmp; tar -zxf nginx.tar.gz; cd nginx
    return 0
};
environment; [ $? -ne 0 ] && exit 1

function install() {
    # 安裝前先做編譯配置
    ./configure --prefix=/usr/local/nginx \
        --user=nginx --group=nginx \
        --with-http_stub_status_module \
        &> /tmp/nginx_install.log
    if [[ $? -ne 0 ]]; then
        return 1
    else
        make &> /tmp/nginx_install.log
        make install &> /tmp/nginx_install.log
        if [[ $? -ne 0 ]]; then
            return 1
        fi
        return 0
    fi
};
install; [ $? -ne 0 ] && exit 1

function optimize() {
    ln -s /usr/local/nginx/sbin/* /usr/local/sbin/ > /dev/null
    cp -f /tmp/nginx_control.sh /etc/init.d/nginx
    cp -f /tmp/nginx.conf /usr/local/nginx/conf/nginx.conf
    # 依 CPU 核心數調整 worker_processes
    processor=`cat /proc/cpuinfo | grep "processor" | wc -l`
    sed -i "s/^w.*;$/worker_processes ${processor};/g" /usr/local/nginx/conf/nginx.conf
    chmod +x /etc/init.d/nginx
    chkconfig --add nginx
    retval=`chkconfig --level 3 nginx on`
    # 設定開機自啟動
    return $retval
};
optimize; [ $? -ne 0 ] && exit 1

function run() {
    # 先測試 nginx.conf 語法是否正確
    /etc/init.d/nginx test &> /tmp/nginx_run.log
    if [[ $? -ne 0 ]]; then
        retval=$?
    else
        # 啟動 nginx
        /etc/init.d/nginx start &> /tmp/nginx_run.log
        if [[ $? -ne 0 ]]; then
            retval=$?
        fi
    fi
    return 0
};
run; [ $? -ne 0 ] && exit 1

function check() {
    # 修改首頁內容以便驗證
    content=$"deployment on $(date "+%Y-%m-%d %H:%M:%S")"
    echo $content > /usr/local/nginx/html/index.html
    # 查看狀態並抓取首頁輸出
    /etc/init.d/nginx status
    echo -n ": "; curl https://localhost
};
check

腳本把環境準備、編譯安裝、優化、啟動與驗證拆成獨立函數,每一步都用返回碼攔截失敗並提前退出,方便在批量部署時定位問題。

Copyright © Linux教程網 All Rights Reserved