美文网首页
编译安装Nginx并将其加入系统服务

编译安装Nginx并将其加入系统服务

作者: 辛晓坤Vincent | 来源:发表于2020-04-21 09:49 被阅读0次

    [toc]

    安装准备

    安装包准备与依赖安装

    yum install -y wget
    #安装wget下载工具
    wget http://nginx.org/download/nginx-1.14.2.tar.gz
    #下载nginx安装包
    yum -y install gcc gcc-c++ zlib zlib-devel openssl openssl-devel pcre-devel
    #下载安装依赖
    

    gcc:gcc-c++编译环境
    gzip模块需要:zlib 库
    rewrite模块需要:pcre 库
    ssl功能需要:openssl库

    创建用户与组

    groupadd nginx
    #创建nginx组
    useradd nginx -g nginx -s /sbin/nologin -M
    #创建一个不能登录属于nginx组的用户nginx
    

    编译安装

    tar -zxvf nginx-1.14.2.tar.gz
    #解压
    cd nginx-1.14.2
    #切换目录
    ./configure --user=nginx --group=nginx --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module --with-http_realip_module --with-http_gzip_static_module
    #预编译
    

    --user=nginx(用户名)
    --group=nginx(组)
    --prefix=/usr/local/nginx(程序安装路径)
    --with-http_stub_status_module (网页状态查看)
    --with-http_ssl_module (ssl模块)
    --with-http_realip_module (后台Nginx服务器记录原始客户端的IP地址 )
    --with-http_gzip_static_module (压缩模块)

    echo $?
    #查看预编译安装结果,显示最后命令的退出状态,0表示没有错误,其他表示有错误
    make && make install
    #编译安装
    echo $?
    #再次查看编译安装结果
    

    将nginx永久添加到系统变量

    vim /etc/profile
    #编辑系统变量文件
    
    export NGINX_HOME=/usr/local/nginx
    export PATH=$PATH:$NGINX_HOME/sbin
    #将nginx变量添加到文件内后,wq保存
    
    source /etc/profile
    #使配置文件生效
    

    将nginx加入系统服务

    写法参考

    找一台直接使用yum安装nginx的服务器,参考写法

    systemctl status nginx
    
    image.png
    cat /usr/lib/systemd/system/nginx.service
    
    image.png

    撰写脚本

    vim /usr/lib/systemd/system/nginx.service
    #编辑系统服务脚本
    
    [Unit]
    Description=nginx
    After=network.target remote-fs.target nss-lookup.target
     
    [Service]
    Type=forking
    PIDFile=/usr/local/nginx/logs/nginx.pid
    #PID路径,一定要写上面编译安装时候设置的路径,我的在/usr/local/nginx/logs/nginx.pid
    ExecStartPre=/usr/bin/rm -f /usr/local/nginx/logs/nginx.pid
    ExecStartPre=/usr/local/nginx/sbin/nginx -t
    #在执行ExecStart之前的操作,先删除有关nginx的PID也就是停止nginx,然后再检查nginx -t配置文件是否正确
    ExecStart=/usr/local/nginx/sbin/nginx
    #nginx启动操作,如果是按照上面编译时候设置的路径,那就在/usr/local/nginx/sbin/nginx
    ExecReload=/bin/kill -s HUP $MAINPID
    #nginx重启操作,这里HUP是平滑重启,重新加载配置文件
    ExecStop=/bin/kill -s QUIT $MAINPID
    #nginx停止操作,实际是使用了QUIT从容关闭nginx
    PrivateTmp=true
     
    [Install]
    WantedBy=multi-user.target
    

    使用说明

    systemctl start|stop|reload|restart|status nginx.service
    #对nginx进行启动|关闭|重载|重启|查看状态
    systemctl enable|disable nginx
    #开启|关闭nginx的开机自启动
    

    相关文章

      网友评论

          本文标题:编译安装Nginx并将其加入系统服务

          本文链接:https://www.haomeiwen.com/subject/qlbyihtx.html