安装环境说明

  • 系统centos7
  • Nginx版本 nginx-1.12.0.tar.gz
  • Nginx安装包百度云链接 密码:6q92

安装依赖包

# yum install gcc pcre pcre-devel zlib zlib-devel openssl openssl-devel libxml2 libxml2-devel libxslt libxslt-devel gd-devel geoip geoip-devel –y
# yum install gd fontconfig-devel freetype-devel libX11-devel libXpm-devel libjpeg-devel libpng-devel -y

创建用户

# useradd -M -s /sbin/nologin nginx            #创建用户

编译安装

#  cd nginx-1.12.0/ #进入解压文件夹
# ./configure \
 --prefix=/usr/local/nginx \
 --user=nginx \
 --group=nginx \
 --with-pcre \
 --with-http_ssl_module \
 --with-http_v2_module \
 --with-http_realip_module \
 --with-http_addition_module \
 --with-http_sub_module \
 --with-http_dav_module \
 --with-http_flv_module \
 --with-http_mp4_module \
 --with-http_gunzip_module \
 --with-http_gzip_static_module \
 --with-http_random_index_module \
 --with-http_secure_link_module \
 --with-http_stub_status_module \
 --with-http_auth_request_module \
 --with-http_image_filter_module \
 --with-mail \
 --with-mail_ssl_module \
 --with-stream_ssl_module

# make && make install

系统服务配置

# vim /usr/lib/systemd/system/nginx.service
[Unit]
 Description=The nginx HTTP and reverse proxy server
 After=syslog.target network.target remote-fs.target nss-lookup.target

[Service]
 Type=forking
 PIDFile=/usr/local/nginx/logs/nginx.pid
 ExecStartPre=/usr/local/nginx/sbin/nginx -t
 ExecStart=/usr/local/nginx/sbin/nginx
 ExecReload=/bin/kill -s HUP /usr/local/nginx/logs/nginx.pid
 ExecStop=/bin/kill -s QUIT /usr/local/nginx/logs/nginx.pid
 PrivateTmp=true

[Install]
 WantedBy=multi-user.target

启动命令

# systemctl enable nginx     #设置开启自启动
# systemctl start nginx         #启动nginx服务
# systemctl stop nginx

报错解决

启动Nginx后,查看状态,发现虽然正在Nginx正在运行,但是提示Failed to read PID from file /run/nginx.pid: Invalid argument 这个错误

  • 造成的原因是

因为 nginx 启动需要一点点时间,而 systemd 在 nginx 完成启动前就去读取
pid file 造成读取 pid 失败
解决方法很简单,让 systemd 在执行 ExecStart 的指令后等待一点点时间即可如果你的 nginx 启动需要时间更长,可以把 sleep 时间改长一点

# mkdir -p /etc/systemd/system/nginx.service.d 
# printf "[Service]\nExecStartPost=/bin/sleep 0.1\n" > /etc/systemd/system/nginx.service.d/override.conf
# systemctl daemon-reload   #重新加载配置文件
# systemctl restart nginx.service   #重新启动