您的位置:首页 > 运维架构 > Nginx

Nginx启动脚本

2012-07-31 12:21 302 查看
Nginx启动脚本

Nginx ("engine x") 是一个高性能的HTTP和反向代理服务器,也是一个 IMAP/POP3/SMTP 代理服务器。因稳定性、丰富的功能、低资源消耗而闻名。

但Nginx本身不自带启动脚本,需要我们手动编写一份,现在网上所提供的大多数脚本都是有针对行的,可移植性很差。

大多数这样的脚本依赖于系统中functions函数,但该函数仅在个别系统中存在。

为了使脚本更加通用,以下编写的脚本可以很轻松的移植到各种Unix、Linux系统中,同时还兼容CentOS的chkconfig功能。

测试证明无需修改即可在CentOS、Ubuntu、FreeBSD上测试运行正常。

脚本的思路是通过nginx.pid文件来判断进程是否启动,当然如果你看了http://manual.blog.51cto.com/3300438/932958这篇文章,就可以通过awk过滤端口号判断进程是否开启,效果更好。

备注:通过pid判断服务的启动与否,可能会导致stop指令执行结束后pid文件没有及时删除(有延迟),而这时进行start启动服务会报服务已启动(而不会真的启动服务)。这种情况会在开启服务后进行restart指令时出现。所以通过端口判断服务的开启与否会更稳定,效果更好...

脚本提供了Nginx所支持的6种进程管理信号中的4种启动用控制信号,同时额外附件了一个查看进程状态的功能。

脚本全文如下:[root@centos6 ~] cat /etc/init.d/nginx
#!/bin/sh
#
# Startup script for the Nginx
# chkconfig: - 88 63
# description: Nginx is a free,open-source,high-performance HTTP Server and reverse proxy.
# program:/usr/local/nginx/sbin/nginx
# config:/usr/local/nginx/conf/nginx.conf
# pidfile:/usr/local/nginx/logs/nginx.pid

# Synopsis:
#        nginx [--help] [--version] {start|stop|restart|reload|status|update}

# Define variable
nginx=/usr/local/nginx/sbin/nginx
pidfile=/usr/local/nginx/logs/nginx.pid
PROGRAM=`basename $0`
VERSION=1.0
# Functions
usage(){
echo "Usage: $PROGRAM [--help] [--version] {start|stop|restart|reload|status|update}"
}

version(){
echo "Version:$VERSION"
}

start(){
if [ -e $pidfile ]
then
echo "Nginx already running..."
else
echo -e "Starting Nginx:\t\t\t\t\t\t\t\c"
/usr/local/nginx/sbin/nginx
echo -e "[ \c"
echo -e "\033[0;32mOK\033[0m\c"
echo -e " ]\c"
echo -e "\r"
fi
}

stop(){
if [ -e $pidfile ]
then
echo -e "Stopping Nginx:\t\t\t\t\t\t\t\c"
kill -TERM `cat ${pidfile}`
echo -e "[ \c"
echo -e "\033[0;32mOK\033[0m\c"
echo -e " ]\c"
echo -e "\r"
else
echo "Nginx already stopped..."
fi
}

reload(){
if [ -e $pidfile ]
then
echo -e "Reloading Nginx:\t\t\t\t\t\t\c"
kill -HUP `cat ${pidfile}`
echo -e "[ \c"
echo -e "\033[0;32mOK\033[0m\c"
echo -e " ]\c"
echo -e "\r"
else
echo "Nginx is not running..."
fi
}

status(){
if [ -e $pidfile ]
then
PID=`cat $pidfile`
echo  "Nginx (pid $PID) is running..."
else
echo  "Nginx is stopped"
fi
}

update(){
if [ -e $pidfile ]
then
echo -e "Updateing Nginx:\t\t\t\t\t\t\c"
kill -USR2 `cat ${pidfile}`
echo -e "[ \c"
echo -e "\033[0;32mOK\033[0m\c"
echo -e " ]\c"
echo -e "\r"
else
echo "Nginx is not running..."
fi
}
if [ $# -gt 0 ]
then
case $1 in
start)
start
;;
stop)
stop
;;
restart)
stop
start
;;
reload)
reload
;;
status)
status
;;
update)
update
;;
--help)
usage
;;
--version)
version
;;
*)
usage
esac
else
usage
fi

如果你的系统使用的是CentOS或RedHat的系统,可以通过chkconfig将其设置为开机启动项。

[root@centos6 ~] chkconfig --add nginx

[root@centos6 ~] chkconfig nginx on

脚本运行效果如图:






本文出自 “丁丁历险” 博客,请务必保留此出处http://manual.blog.51cto.com/3300438/948874
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: