centos安装nginx通过编译安装的方式安装好后,把启动重启后每次都需要去 /usr/local/nginx/sbin/nginx 启动服务,很不方便,所以centos7设置nginx-1.11.10开机启动服务是很有用处的。大致流程是通过创建开机启动脚本,把nginx服务加入开机启动。
创建开机启动命令脚本文件:
bash
- vi /etc/init.d/nginx
在这个nginx文件中插入一下启动脚本代码,启动脚本代码来源网络复制,实测有效
bash
- #! /bin/bash
- # chkconfig: - 85 15
- PATH=/usr/local/nginx
- DESC="nginx daemon"
- NAME=nginx
- DAEMON=$PATH/sbin/$NAME
- CONFIGFILE=$PATH/conf/$NAME.conf
- PIDFILE=$PATH/logs/$NAME.pid
- scriptNAME=/etc/init.d/$NAME
- set -e
- [ -x "$DAEMON" ] || exit 0
- do_start() {
- $DAEMON -c $CONFIGFILE || echo -n "nginx already running"
- }
- do_stop() {
- $DAEMON -s stop || echo -n "nginx not running"
- }
- do_reload() {
- $DAEMON -s reload || echo -n "nginx can't reload"
- }
- case "$1" in
- start)
- echo -n "Starting $DESC: $NAME"
- do_start
- echo "."
- ;;
- stop)
- echo -n "Stopping $DESC: $NAME"
- do_stop
- echo "."
- ;;
- reload|graceful)
- echo -n "Reloading $DESC configuration..."
- do_reload
- echo "."
- ;;
- restart)
- echo -n "Restarting $DESC: $NAME"
- do_stop
- do_start
- echo "."
- ;;
- *)
- echo "Usage: $scriptNAME {start|stop|reload|restart}" >&2
- exit 3
- ;;
- esac
- exit 0
设置所有人都有对这个启动脚本nginx文件的执行权限
bash
- chmod a+x /etc/init.d/nginx
把nginx加入系统服务中
bash
- chkconfig --add nginx
把服务设置为开机启动
bash
- chkconfig nginx on
reboot重启系统生效
bash
- #启动nginx服务
- systemctl start nginx.service
- #停止nginx服务
- systemctl stop nginx.service
- #重启nginx服务
- #同时也可以通过下面的命令进行服务重启,停止操作
- service nginx restart
- service nginx start
- service nginx stop
如果服务启动的时候出现 Restarting nginx daemon: nginxnginx: [error] open() "/usr/local/nginx/logs/nginx.pid" failed (2: No such file or directory)
nginx not running 的错误,通过nginx -c 参数指定配置文件即可解决
bash
- /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
如果服务启动中出现 nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use) 的错误,可以先通过service nginx stop 停止服务,再启动就好。