今天咸鱼给大家分享个源码编译安装 Nginx 的 shell 脚本
这个 shell 脚本可重复执行
完整源码放在最后
-
定义一个变量来存放 nginx 版本号
version=1.15.4
nginx 下载地址:http://nginx.org/download/
-
下列函数功能则是判断当前步骤是否执行成功,并将结果输出出来
-
创建 nginx 用户和用户组
建议用大于 1000 的 GID 和 UID 号,表示普通用户
这段代码里我做了一个条件判断:
如果在 /etc/passwd
和 /etc/group
文件中过滤出 nginx,表示已经创建了 nginx 用户和 nginx 用户组,就不再创建了
-
安装一些扩展包
-
下载 Nginx 并解压缩
-
编译安装 Nginx
这里也做了一个条件判断:
如果 /usr/local/nginx
目录存在,则说明 nginx 已经成功安装好了
-
建立软连接
这一步看个人习惯可做可不做
-
注册服务
将 nginx 注册成服务之后就可以使用 systemctl 控制它了
-
内核参数优化
-
启动 nginx 并设置开机自启动
-
负责配置写入的函数
在上面的内核参数优化函数里面,我并没有使用 echo 将配置直接重定向到 /etc/sysctl.conf
文件里面
而是用了 add_config_tofile
函数,第一个参数是配置项,第二个参数是文件名
-
main 函数
-
完整代码
执行结果如下:
#! /bin/bash version=1.15.4 #判断函数是否执行成功 function show_result(){ if [ "$1" -eq 0 ] then echo -e "\e[32m$2 is Success . [ OK ] \e[0m" else echo -e "\e[31m$2 is Fail . [ FAIL ] \e[0m" fi } #创建 nginx 用户和用户组 function user_create(){ local item="Create User and Group" if [ `cat /etc/{passwd,group} | grep nginx | wc -l ` -ge 2 ]; then echo -e "\e[31mUser and Group exist! \e[0m" else groupadd -g 1004 nginx && \ useradd -u 1004 -g 1004 -M -s /sbin/nologin nginx show_result $? "${item}" fi } #下载一些拓展包 function nginx_pkg(){ local item="Packages Install" yum -y install gcc openssl-devel pcre-devel zlib-devel > /dev/null 2>&1 show_result $? "${item}" } #下载nginx function nginx_download(){ local item="Nginx Download" cd /usr/local/src && \ wget http://nginx.org/download/nginx-${version}.tar.gz > /dev/null 2>&1 test -e /usr/local/src/nginx-${version} || tar zxf nginx-${version}.tar.gz rm -rf /usr/local/src/nginx-${version}.tar.gz show_result $? "${item}" } #编译安装 function nginx_compile(){ local item="Nginx Compile" cd /usr/local/src/nginx-${version} if [ `ls -l /usr/local/ | grep 'nginx' | wc -l` -ge 1 ]; then echo -e "\e[31mNginx exist! \e[0m" else ./configure --prefix=/usr/local/nginx > /dev/null 2>&1 && make > /dev/null 2>&1 && make install > /dev/null 2>&1 fi show_result $? "${item}" } #软连接建立 function nginx_softlink(){ local item="Nginx Softlink" test -d /etc/nginx/ || ln -s /usr/local/nginx/conf/ /etc/nginx test -e /usr/sbin/nginx || ln -s /usr/local/nginx/sbin/nginx /usr/sbin/ show_result $? "${item}" } #注册服务 function nginx_service(){ local item="Nginx Service" test -e /usr/lib/systemd/system/nginx.service || \ echo ' [Unit] Description=The nginx HTTP and reverse proxy server After=network-online.target remote-fs.target nss-lookup.target Wants=network-online.target [Service] Type=forking PIDFile=/usr/local/nginx/logs/nginx.pid # Nginx will fail to start if /run/nginx.pid already exists but has the wrong # SELinux context. This might happen when running `nginx -t` from the cmdline. # https://bugzilla.redhat.com/show_bug.cgi?id=1268621ExecStartPre=/usr/bin/rm-f /usr/local/nginx/logs/nginx.pid ExecStartPre=/usr/local/nginx/sbin/nginx -t ExecStart=/usr/local/nginx/