通过shell编程实现:开发 Nginx 服务(编译安装)启动停止脚本

#!/bin/bash

# 定义Nginx源代码下载地址和安装目录
NGINX_SOURCE_URL="http://nginx.org/download/nginx-1.18.0.tar.gz"
NGINX_SOURCE_TAR="nginx-1.18.0.tar.gz"
NGINX_SOURCE_DIR="nginx-1.18.0"
INSTALL_DIR="/usr/local/nginx"

# 编译安装Nginx
install_nginx() {
    echo "开始安装Nginx..."
    # 下载Nginx源代码
    wget $NGINX_SOURCE_URL
    # 解压源代码
    tar zxvf $NGINX_SOURCE_TAR
    cd $NGINX_SOURCE_DIR
    # 配置安装选项
    ./configure --prefix=$INSTALL_DIR
    # 编译和安装
    make && make install
    echo "Nginx安装完成."
}

# 启动Nginx服务
start_nginx() {
    echo "启动Nginx..."
    $INSTALL_DIR/sbin/nginx
    echo "Nginx已启动."
}

# 停止Nginx服务
stop_nginx() {
    echo "停止Nginx..."
    $INSTALL_DIR/sbin/nginx -s stop
    echo "Nginx已停止."
}

# 设置开机自启动(CentOS 6)
setup_autostart_centos6() {
    echo "设置CentOS 6开机自启动..."
    # 创建chkconfig脚本
    cat > /etc/init.d/nginx <<EOF
#!/bin/bash
# chkconfig: 345 85 15
# description: Nginx web server

case "\$1" in
    start)
        $INSTALL_DIR/sbin/nginx
        ;;
    stop)
        $INSTALL_DIR/sbin/nginx -s stop
        ;;
    restart)
        $INSTALL_DIR/sbin/nginx -s stop
        $INSTALL_DIR/sbin/nginx
        ;;
    *)
        echo "Usage: \$0 {start|stop|restart}"
        exit 1
esac
EOF
    # 使脚本可执行
    chmod +x /etc/init.d/nginx
    # 添加到chkconfig
    chkconfig --add nginx
    chkconfig nginx on
    echo "CentOS 6开机自启动设置完成."
}

# 设置开机自启动(CentOS 7)
setup_autostart_centos7() {
    echo "设置CentOS 7开机自启动..."
    # 创建systemd服务文件
    cat > /etc/systemd/system/nginx.service <<EOF
[Unit]
Description=The NGINX HTTP and reverse proxy server
After=network.target

[Service]
Type=forking
ExecStart=$INSTALL_DIR/sbin/nginx
ExecReload=$INSTALL_DIR/sbin/nginx -s reload
ExecStop=$INSTALL_DIR/sbin/nginx -s quit
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF
    # 重新加载systemd管理配置
    systemctl daemon-reload
    # 启用Nginx服务
    systemctl enable nginx
    echo "CentOS 7开机自启动设置完成."
}

# 根据系统版本选择设置方法
if [ -f /etc/redhat-release ]; then
    version=$(cat /etc/redhat-release)
    if [[ $version == *"CentOS release 6"* ]]; then
        setup_autostart_centos6
    elif [[ $version == *"CentOS Linux release 7"* ]]; then
        setup_autostart_centos7
    else
        echo "不支持的CentOS版本"
    fi
else
    echo "这不是一个CentOS系统"
fi

# 解析命令行参数执行相应操作
case $1 in
    install)
        install_nginx
        ;;
    start)
        start_nginx
        ;;
    stop)
        stop_nginx
        ;;
    *)
        echo "Usage: $0 {install|start|stop}"
        exit 1
esac

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值