如何在 Linux 系统中使用 systemctl 命令管理 Nginx 服务

how-to-use-systemctl-manage-nginx-service.png

Nginx 正确发音为 “engine x” 是一个免费的,开源的,高性能的 HTTP 和反向代理服务器,很多网站都采用 Nginx 作为 Web server 或者反向代理服务。 Nginx 可以用作独立的Web服务器,也可以用作 Apache 和其他 Web 服务器的反向代理。

如果您是开发人员或系统管理员,或者运维,那么您可能会定期检查,启停,重载 Nginx 服务。

在本指南中,我们将重点介绍使用 systemctl 管理 Nginx 常用命令,包括启动,停止和重新启动 Nginx。

开始之前

所有命令必须以 sudo 或 root 用户身份执行,这些命令应该适用于任何现代 Linux 发行版,如 Ubuntu 18.04CentOS 7 以及 Debian 9/10

启动 Nginx 服务

启动Nginx非常简单。 只需运行以下命令:

sudo systemctl start nginx

成功执行后,该命令不会产生任何输出。

如果您使用的发行版上没有安装 systemd ,可以通过以下命令启动:

sudo service start nginx

除了手动启动 Nginx 服务,建议将其设置为在系统启动时自动启动,通过以下命令进行设置:

sudo systemctl enable nginx

停止 Nginx 服务

即使存在打开的连接,停止Nginx也会快速关闭所有 Nginx 工作进程。

要停止Nginx,请运行以下命令之一:

sudo systemctl stop nginx

如果您使用的发行版上没有安装 systemd ,可以通过以下命令停止:

sudo service stop nginx

重启 Nginx 服务

重启是一种先停止然后再启动 Nginx 服务器的快速方法。

使用以下命令执行 Nginx 重新启动:

sudo systemctl restart nginx

如果您使用的发行版上没有安装 systemd ,可以通过以下命令重启:

sudo service restart nginx

这些是您可能最常使用的命令。

重载 Nginx 配置文件

当您更改其 Nginx 配置时,您都需要重新加载或重新启动 Nginx。

重新加载选项将加载新配置,使用新配置启动新的工作进程并正常关闭旧工作进程。服务并不会中断。

要重新加载Nginx配置,请使用以下命令:

sudo systemctl reload nginx

如果您使用的发行版上没有安装 systemd ,可以通过以下命令重载:

sudo service reload nginx

测试 Nginx 配置

每当您更改 Nginx 服务器的配置文件时,最好在重新启动或重新加载服务之前测试配置。

使用以下命令测试 Nginx 配置是否存在任何语法或系统错误:

sudo nginx -t

输出类似如下:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

如果有任何错误,命令将打印详细消息。

查看 Nginx 状态

要检查 Nginx 服务的状态,请使用以下命令:

sudo systemctl status nginx

输出结果类似如下:

nginx.service - A high performance web server and a reverse proxy server
   Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
   Active: active (running) since Sun 2019-07-18 10:57:01 PDT; 5min ago
     Docs: man:nginx(8)
  Process: 4491 ExecStop=/sbin/start-stop-daemon --quiet --stop --retry QUIT/5 --pidfile /run/nginx.pid (code=exited, status=0/SUCCESS)
  Process: 4502 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
  Process: 4492 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
 Main PID: 4504 (nginx)
    Tasks: 3 (limit: 2319)
   CGroup: /system.slice/nginx.service
           |-4504 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
           |-4516 nginx: worker process
           `-4517 nginx: worker process

结果中的Active: active (running)显示了 Nginx 运行状态。

检查 Nginx 版本

有时您可能需要知道 Nginx 的版本,以便调试问题或确定某个功能是否可用。

您可以通过运行以下方式检查您的 Nginx 版本:

sudo nginx -v

和小写-v不同使用参数-V选项将输出 Nginx 版本以及 configure 选项,注意这个是大写的V

sudo nginx -V

写在最后

在本指南中,我们向您展示了一些最重要的 Nginx 命令。 如果您想了解有关 Nginx 命令行的更多信息,请访问 Nginx 文档

原文地址:http://linux265.com/news/3775.html

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容