跳至主要內容

CentOS 7源码编译安装Nginx

大约 3 分钟约 821 字

CentOS 7源码编译安装Nginx

创建nginx组和用户

groupadd -r nginx
useradd -r -g nginx nginx

yum源配置

cd /etc/yum.repos.d
rename repo repo.bak *.repo
curl -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo
yum makecache fast

源码编装Nginx依赖包

因为是源码安装,需要安装系统编译环境,以及Nginx依赖的pcre,zlib,openssl软件包。

yum group install "Development Tools" -y
yum install pcre pcre-devel zlib zlib-devel openssl openssl-devel -y

下载Nginx源码包

# 可以去http://nginx.org/download页面中找自己想要的版本,上面包含nginx所有历史发布版本
cd /usr/local/src
# curl -o nginx-1.18.0.tar.gz http://nginx.org/download/nginx-1.18.0.tar.gz
# curl -o nginx-1.18.0.tar.gz http://mirrors.lead.cn/source/nginx/nginx-1.18.0.tar.gz
wget -O  nginx-1.18.0.tar.gz http://download-soft.lead.cn/source/nginx/nginx-1.18.0.tar.gz

解压编译安装Nginx

tar xf nginx-1.18.0.tar.gz 
cd nginx-1.18.0
./configure --prefix=/usr/local/nginx-1.18.0 --with-http_stub_status_module  --with-http_gzip_static_module --with-http_realip_module  --with-http_sub_module --with-http_ssl_module --with-http_flv_module --with-http_mp4_module --with-pcre --user=nginx --group=nginx
if [ $? -eq 0 ]; then
    make && make install
else
    echo "Install nginx failed, please check."
    exit 100
fi
# create nginx soft link
ln -s /usr/local/nginx-1.18.0 /usr/local/nginx
# add nginx command to .bash_profile
echo 'export PATH=/usr/local/nginx/sbin:$PATH' >> ~/.bash_profile
# make it works
source ~/.bash_profile

创建存放虚拟主机配置目录

mkdir /usr/local/nginx/vhosts

为Nginx日志添加日志滚动配置

cat > /etc/logrotate.d/nginx <<EOF
/usr/local/nginx/logs/*.log {
    create 0664 nginx root
    daily
    rotate 10
    missingok
    notifempty
    compress
    sharedscripts
    postrotate
        /bin/kill -USR1 `cat /usr/local/nginx/logs/nginx.pid 2>/dev/null` 2>/dev/null || true
    endscript
}
EOF

添加Nginx开机启动

cat > /usr/lib/systemd/system/nginx.service <<EOF
[Unit]
Description=The nginx HTTP and reverse proxy server
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
# Nginx will fail to start if /run/nginx.pid already exists but has the wrong
# SELinux context. This might happen when running `nginx -t` from the cmdline.
# https://bugzilla.redhat.com/show_bug.cgi?id=1268621
ExecStartPre=/usr/bin/rm -f /usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
KillSignal=SIGQUIT
TimeoutStopSec=5
KillMode=process
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF
# 设置开机自启
systemctl enable nginx

Nginx优化参数

Nginx内核参数优化最佳实践

cat > /usr/local/nginx/conf/nginx.conf <<EOF
# you must set worker processes based on your CPU cores, nginx does not benefit from setting more than that
worker_processes auto; #some last versions calculate it automatically

# number of file descriptors used for nginx
# the limit for the maximum FDs on the server is usually set by the OS.
# if you don't set FD's then OS settings will be used which is by default 2000
worker_rlimit_nofile 100000;

# only log critical errors
error_log /usr/local/nginx/logs/error.log crit;

# PID file
pid /usr/local/nginx/logs/nginx.pid

# provides the configuration file context in which the directives that affect connection processing are specified.
events {
    # determines how much clients will be served per worker
    # max clients = worker_connections * worker_processes
    # max clients is also limited by the number of socket connections available on the system (~64k)
    worker_connections 4000;

    # optimized to serve many clients with each thread, essential for linux -- for testing environment
    use epoll;

    # accept as many connections as possible, may flood worker connections if set too low -- for testing environment
    multi_accept on;
}

http {
    # cache informations about FDs, frequently accessed files
    # can boost performance, but you need to test those values
    open_file_cache max=200000 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;

    # to boost I/O on HDD we can disable access logs
    access_log off;

    # copies data between one FD and other from within the kernel
    # faster than read() + write()
    sendfile on;

    # send headers in one piece, it is better than sending them one by one
    tcp_nopush on;

    # don't buffer data sent, good for small data bursts in real time
    tcp_nodelay on;

    # reduce the data that needs to be sent over network -- for testing environment
    gzip on;
    # gzip_static on;
    gzip_min_length 10240;
    gzip_comp_level 1;
    gzip_vary on;
    gzip_disable msie6;
    gzip_proxied expired no-cache no-store private auth;
    gzip_types
        # text/html is always compressed by HttpGzipModule
        text/css
        text/javascript
        text/xml
        text/plain
        text/x-component
        application/javascript
        application/x-javascript
        application/json
        application/xml
        application/rss+xml
        application/atom+xml
        font/truetype
        font/opentype
        application/vnd.ms-fontobject
        image/svg+xml;

    # allow the server to close connection on non responding client, this will free up memory
    reset_timedout_connection on;

    # request timed out -- default 60
    client_body_timeout 10;

    # if client stop responding, free up memory -- default 60
    send_timeout 2;

    # server will close connection after this time -- default 75
    keepalive_timeout 30;

    # number of requests client can make over keep-alive -- for testing environment
    keepalive_requests 100000;
    
}
EOF
# 设置nginx服务启动参数
mkdir -p /etc/systemd/system/nginx.service.d
cat > /etc/systemd/system/nginx.service.d/nginx.conf <<EOF
[Service]
LimitNOFILE=30000
EOF

systemctl daemon-reload
systemctl restart nginx.service