shell脚本部署nginx
1. 编译安装nginx
首先创建一个目录,用来存放脚本
[root@localhost ~]# mkdir /nginx
[root@localhost ~]# cd /nginx/
[root@localhost nginx]# chmod +x nginx.sh //赋予脚本的执行权限
2. 下载安装nginx的安装包
可以去nginx官网下载相应版本的tar包
[root@localhost nginx]# wget https://nginx.org/download/nginx-1.20.1.tar.gz
在同级目录创建一个放安装包的目录
[root@localhost nginx]# mkdir packages/
[root@localhost packages]# ls
nginx-1.20.1.tar.gz
3. 创建脚本文件
[root@localhost nginx]# touch nginx.sh
4. 编写脚本
[root@localhost nginx]# cat nginx.sh
#!/bin/bash
route=/usr/local
server=/usr/lib/systemd/system
id nginx &>/dev/null //判断是否有nginx用户,没有就创建用户
if [ $? -ne 0 ];then
useradd -r -M -s /sbin/nologin nginx
fi
yum -y install pcre-devel pcre gcc gcc-c++ openssl-devel zlib zlib-devel make vim wget openssl openssl-devel gd-devel //解决依赖关系
mkdir /var/log/nginx
chown -R nginx.nginx /var/log/nginx
if [ ! -d $route/nginx-1.20.1 ];then
tar xf packages/nginx-1.20.1.tar.gz -C $route //解压到/usr/local
fi
cd $route/nginx-1.20.1
if [ ! -d $route/nginx ];then //若没有nginx目录就进行进行编译
./configure --prefix=/usr/local/nginx \
--user=nginx \
--group=nginx \
--with-debug \
--with-http_ssl_module \
--with-http_realip_module \
--with-http_image_filter_module \
--with-http_gunzip_module \
--with-http_gzip_static_module \
--with-http_stub_status_module \
--http-log-path=/var/log/nginx/access.log \
--error-log-path=/var/log/nginx/error.log
make && make install
fi
cd $server //配置service文件使用systemctl控制nginx
cat > nginx.service << EOF
[Unit]
Description=Nginx server daemon
After=network.target
[Service]
Type=forking
ExecStart=/usr/local/nginx/sbin/nginx
ExecStop=/usr/local/nginx/sbin/nginx -s quit
ExecReload=/bin/kill -HUP \$MAINPID
[Install]
WantedBy=multi-user.target
EOF
echo 'export PATH=/usr/local/nginx/sbin:$PATH' > /etc/profile.d/nginx.sh //配置环境变量
bash /etc/profile.d/nginx.sh //重新加载生效
systemctl daemon-reload
systemctl enable --now nginx.service
if [ $? -eq 0 ];then
echo "nginx is ok"
else
echo "nginx is error"
fi
开机自启成功就输出nginx is ok,否则就输出nginx is error。