将Nginx作为Linux系统服务运行并自启动

在 /etc/init.d/ 目录下创建 nginx 文件,并编辑

touch nginx

vi nginx

nginx 文件里添加如下内容

#!/bin/bash

# nginx Startup script for the Nginx HTTP Server

# it is v.0.0.2 version.

# chkconfig: - 85 15

# description: Nginx is a high-performance web and proxy server.

#              It has a lot of features, but it's not for everyone.

# processname: nginx

# pidfile: /var/run/nginx.pid

# config: /usr/local/nginx/conf/nginx.conf

nginxd=/usr/local/nginx/sbin/nginx

nginx_config=/usr/local/nginx/conf/nginx.conf

nginx_pid=/var/run/nginx.pid

RETVAL=0

prog="nginx"

# Source function library.

. /etc/rc.d/init.d/functions

# Source networking configuration.

. /etc/sysconfig/network

# Check that networking is up.

[ ${NETWORKING} = "no" ] && exit 0

[ -x $nginxd ] || exit 0

# Start nginx daemons functions.

start() {

if [ -e $nginx_pid ];then

echo "nginx already running...."

exit 1

fi

echo -n $"Starting $prog: "

daemon $nginxd -c ${nginx_config}

RETVAL=$?

echo

[ $RETVAL = 0 ] && touch /var/lock/subsys/nginx

return $RETVAL

}

# Stop nginx daemons functions.

stop() {

echo -n $"Stopping $prog: "

killproc $nginxd

RETVAL=$?

echo

[ $RETVAL = 0 ] && rm -f /var/lock/subsys/nginx /var/run/nginx.pid

}

# reload nginx service functions.

reload() {

echo -n $"Reloading $prog: "

#kill -HUP `cat ${nginx_pid}`

killproc $nginxd -HUP

RETVAL=$?

echo

}

# See how we were called.

case "$1" in

start)

start

;;

stop)

stop

;;

reload)

reload

;;

restart)

stop

start

;;

status)

status $prog

RETVAL=$?

;;

*)

echo $"Usage: $prog {start|stop|restart|reload|status|help}"

exit 1

esac

exit $RETVAL

执行命令

chmod 755 /etc/init.d/nginx

/sbin/chkconfig nginx --level=5

chkconfig --add /etc/init.d/nginx

chkconfig --add nginx

启动服务,停止服务,重启服务

service nginx start

service nginx stop

service nginx restart

我最后弄出来有点问题,只能选择以命令的方式运行和停止

进入到nginx的sbin目录下

./nginx

./nginx -s stop

将 Nginx 添加到系统变量(profile.d形式)

cd /etc/profile.d/

touch nginx.sh

vi nginx.sh

添加以下代码:

export PATH=$PATH:/usr/local/nginx/sbin

编辑完后保存,然后重新加载source

source  /etc/profile.d/nginx.sh

所以,以后可以使用以下命令启动和停止 Nginx

nginx -v

nginx    运行nginx

nginx -s stop    停止nginx

nginx -s reload    重启nginx

开机自动启动

设置开机自启动

systemctl enable nfs-server.service

或者


服务无法启动:

尝试1:

groupadd nginx

adduser nginx

chmod 755 nginx

然后修改 nginx/conf/nginx.conf 文件

在user一栏中把 user 修改为 nginx

user nginx nginx;

尝试2:

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容