shell脚本一键部署nginx
shell脚本代码如下:
#!/bin/bash
#判断用户是否为root用户
if [ $UID != 0 ];then
echo "Must be Root"
exit 1
fi
exit_script(){
exit 1
}
#若80端口被占用则调用exit_script程序退出脚本
lsof -i:80 | wc -l
if [ ! $? -ne 0 ];then
echo "您的80端口被占用或您的nginx已经安装完毕"
echo "即将退出程序"
echo "请查看后再安装"
exit_script
else
echo "您的80端口未被使用 将继续安装"
fi
#关闭防火墙
systemctl stop firewalld
setenforce 0
#清除缓存
yum clean all && yum makecache fast
#安装nginx相关依赖包
yum -y install gcc zlib zlib-devel openssl openssl-devel pcre pcre-devel wget lsof curl curl-devel net-tools
#设置路径
nginx_dir=nginx-1.20.1.tar.gz
nginx_file=nginx-1.20.1
#wget下载nginx到root目录下
wget -P /root http://nginx.org/download/nginx-1.20.1.tar.gz
#nginx安装
nginx_install(){
useradd nginx && cd /root && tar -zxvf $nginx_dir #创建nginx用户并进入root目录下解压下载好的压缩包
cd $nginx_file #进入解压好的nginx文件
./configure \ #编译nginx
--prefix=/usr/local/nginx \
--user=nginx \
--group=nginx \
--sbin-path=/usr/local/nginx/sbin/nginx \
--conf-path=/usr/local/nginx/conf/nginx.conf \
--error-log-path=/usr/local/nginx/logs/error.log \
--http-log-path=/usr/local/nginx/logs/access.log \
--pid-path=/var/run/nginx.pid \
--lock-path=/var/lock/subssys/nginx.lock \
--with-http_stub_status_module \
--with-http_ssl_module \
--with-http_flv_module \
--with-http_gzip_static_module \
--with-pcre
make && make install #安装nginx
}
#nginx启动
nginx_start(){
/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf #在sbin目录下启动nginx
}
main(){
nginx_install
nginx_start
}
#运行主程序
main
#查看80端口是否被nginx占用
lsof -i:80 | wc -l
if [ $? -ne 0 ];then
echo "nginx service is error "
else
echo "nginx service is ok"
fi
使用netstat -tupln查看后发现nginx已经启动
在浏览器中输入 ip地址:80 查看
成功安装部署nginx!!!
部署中遇到的困难总结
1、在虚拟机中部署好nginx后使用浏览器测试发现测试不成功 解决方法:shell脚本中写入关闭防火墙的命令。
2、在shell脚本中最后测试nginx是否安装成功时发现有可能系统中本身存在http、nginx服务占用80端口使得最终测试的结果不准确 解决方法:在shell脚本刚开始的时候加入对80端口使用情况的判定 若存在80端口被占用的情况 则调用exit_script退出脚本。
3、刚开始编写脚本的时候 nginx_install() 中是这样写的useradd nginx && cd /root && tar -zxvf $nginx_dir && cd $nginx_file 每次执行脚本的时候./configure时总出现错误 后发现cd /root && cd $nginx_file不能同时使用 否则将不能进入$nginx_file中。