Nginx introduction and basic command line operation

Time:2020-10-25

Introduction to nginx

Nginx is a high-performance web server. From 2001 to now, because of nginx’s deep mining of hardware and operating system kernel characteristics, it can maintain high concurrency and high throughput at the same time. Nginx also adopts module design, and there are a large number of third-party modules that can expand the functions of nginx. Therefore, nginx has rich scenarios. At the same time, nginx adopts BSD license, which gives nginx the maximum flexibility. In short, nginx has the following advantages:

  • High concurrency, high performance
  • Good scalability
  • High reliability, downtime may be only a few seconds in a year
  • Hot deployment, can not restart the upgrade
  • Flexibility with BSD license

BSD open source protocol is a protocol that gives users a lot of freedom. Basically, users can “do whatever they want”, freely use and modify the source code, or redistribute the modified code as open source or proprietary software.

As of September 2019, nginx’s market share has reached 33%, and it is still growing, and it is firmly at the top of the market.

Nginx introduction and basic command line operation

background

The background of nginx is the rapid growth of data volume caused by the rapid popularization of the Internet, and at the same time spawned a large number of connections. Traditional Apache and other servers adopt a single process model, which means that a process will be created every time a request is processed. This not only has the cost of process creation, but also the context cost caused by switching between processes is also very CPU consuming Resources, resulting in the traditional server in the face of thousands of concurrent connections, the performance is very low, and this is the rapid development of the Internet can not tolerate.

In this context, nginx adopts the process pool and epoll processing model, which together make nginx have excellent performance. A 32 core machine can support tens of millions of concurrent connections.

Nginx has a master process and several worker processes. The master process is used to manage the worker process. The worker process is responsible for handling specific requests. The worker process is a child process of the master process.

Version of nginx

After introducing the background of nginx, we should talk about the version of nginx. At present, nginx has three main products:

  • Official nginx. Open source version included( nginx.org )And commercial edition( nginx.com )
  • Tengine of Alibaba. Tengine is a web server project initiated by Taobao. It has been open source at present
  • OpenResty。 Openresty extends nginx through Lua, making it very easy to extend nginx module

For our daily study, choose the official open source version of nginx and openresty.

Compiling nginx and openresty

On Linux, you can use package management tools like Yum and apt get to download nginx. However, many modules of nginx are not enabled by default, and many third-party modules are not included. Therefore, if you want to open built-in modules or compile third-party modules, you still need to compile nginx.

Download nginx source code

In http://nginx.org/en/download…. It can download nginx source code directly. Contains the following directories:

nginx-1.17.8
├ - changes # features and bugfix provided by each version
├──  CHANGES.ru  #Russian version of changes file
├── LICENSE
├── Makefile
├── README
𗍊 - Auto ᦖ automatically detects the system environment and compiles related scripts. It helps to determine which modules nginx supports and what features of the current operating system can be used by nginx
├ - conf # sample file, convenient for operation and maintenance configuration, will copy the conf sample file to the installation directory
├ - configure # command script, which is used to generate intermediate files and perform a necessary action before compiling
Contrib provides two PL scripts and VIM tools
╎ - HTML # a default page with 500 errors, and the other is the default index page
Ꮊ -- man # nginx help file for Linux, man. / nginx. 8
└ -- SRC # nginx source code

Configure VIM

If VIM doesn’t have the syntax highlighted, you’d better turn it on

cp -r contrib/vim/* ~/.vim
#Under Mac, you need to create a new. Vimrc file in the home directory and configure it
syntax on

Compiling nginx

The. / configure -- help # -- help command can see which parameters the configuration script supports

The first kind of configuration parameter

--Prefix = path set installation prefix ා you can specify this path, and other files will be created in the prefix directory
--sbin-path=PATH                   set nginx binary pathname
--modules-path=PATH                set modules path
--conf-path=PATH                   set nginx.conf pathname
--error-log-path=PATH              set error log pathname
--pid-path=PATH                    set nginx.pid pathname
--lock-path=PATH                   set nginx.lock pathname

The second type of configuration parameters

You can configure which modules to use or not to use. The prefixes are usually with and with out. If you need to add the with parameter, it will not be compiled by default by nginx, and without will be removed from compilation.

--with-http_ssl_module             enable ngx_http_ssl_module
--with-http_v2_module              enable ngx_http_v2_module
--with-http_realip_module          enable ngx_http_realip_module
...

--without-http_charset_module      disable ngx_http_charset_module
--without-http_gzip_module         disable ngx_http_gzip_module
--without-http_ssi_module          disable ngx_http_ssi_module
...

Start compiling

#1. Use the default parameters to specify the installation directory
./configure --prefix=/Users/mtdp/myproject/nginx/nginx
#After compiling, the objs folder intermediate file is generated
➜  objs ll
total 176
-rw-r--r--  1 mtdp  staff    40K  3  3 07:23 Makefile
-rw-r--r--  1 mtdp  staff    25K  3  3 07:23 autoconf.err
-rw-r--r--  1 mtdp  staff   5.4K  3  3 07:23 ngx_auto_config.h
-rw-r--r--  1 mtdp  staff   531B  3  3 07:23 ngx_auto_headers.h
-rw-r--r--  1 mtdp  staff   5.7K  3  3 07:23 ngx_ modules.c # ngx_ Modules. C determines which modules are generated by the next compilation
drwxr-xr-x  9 mtdp  staff   288B  3  3 07:23 src
2. Compile
Make ා generates a large number of intermediate files. If it is a version upgrade, you cannot make install directly. You need to copy obj to the installation directory. If a dynamic module is generated, it will also be placed in the objs directory after compilation
3. Installation
make install
➜ nginx ll # the following folder will be generated after the installation
total 0
Drwxr-xr-x 17 mtdp staff 544b 3 3 07:29 conf ා
Drwxr-xr-x @ 4 mtdp staff 128B 3 3 07:29 HTML
Drwxr-xr-x 2 mtdp staff 64b 3 07:29 logs ා log file directory, including access log and error log
Drwxr-xr-x 3 mtdp staff 96b 3 3 07:29 SBIN ා nginx binary file directory

Compiling openresty

The compilation and installation steps of openresty are basically the same as those of nginx

In https://openresty.org/en/down… Download openresty’s source code from openresty, and then follow the compilation steps of nginx.

Nginx configuration file

Configuration rules

events {
    worker_connections 1024;
}

http {
    #incloud mime.types;
    #default_type application/octet-stream;
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
    #access_log logs/geek.access.log main;
    sendfile on;
    #tcp_nopush on;
    #keepalive_timeout 0;
    keepalive_timeout 65;

    gzip on;
    gzip_min_length 1;
    gzip_comp_level 2;
    gzip_types text/plain application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png multipart/form-data;
    server {
        listen 8080;
        server_name 127.0.0.1;
        #charset koi8-r;
        access_log logs/geek.access.log main;
        location /lua {
            default_type text/html;
            content_by_lua '
ngx.say("User-Agent: ", ngx.req.get_headers()["User-Agent"])
';
}
        }
        #error_page 404 /404.html;

    }

As shown above, it is an atypical nginx configuration file. The syntax of nginx configuration file follows the following rules:

  • The configuration file consists of instructions and instruction blocks
  • Each instruction ends with; and the instruction and its parameters are separated by a space symbol
  • The instruction block organizes multiple instructions together with {}
Events {ා instruction block
    worker_ Connections 1024; command
}
  • The include statement allows multiple configuration files to be combined to improve maintainability
  • Add comments using ා
  • Use the $sign to add variables
  • The parameters of some instructions support regular expressions

configuration parameter

Time unit

  • MS: ms
  • s: Second
  • m: Minutes
  • h: Hours
  • d: Days
  • M: Month = 30 days
  • y: Year = 365 days

Spatial unit

  • bytes
  • k/K:kilobytes
  • m/M:megabytes
  • g/G:gigabytes

Command block for HTTP configuration

  • Http: indicates that the request is handled by the HTTP module
  • Upstream: represents the upstream server address
  • Server: represents the site address
  • Location: represents the URL

These blocks will be encountered next.

Nginx command line

Under the nginx directory just compiled, there is a SBIN directory, which is used to store the binary files of nginx

➜  sbin ll
total 1712
-rwxr-xr-x  1 mtdp  staff   854K  3  3 07:29 nginx

When nginx is started, there are a series of command line parameters that can be specified, which are described below.

./nginx
-H / -? Open help
-C ා use the specified configuration file instead of the configuration file under the default conf folder
-G ා specifies the configuration command to override the instruction in the configuration file
-P ා specifies the running directory
-S ා send a signal to stop the service immediately; quit to stop the service gracefully; reload to overload the configuration file; reopen to start logging the log file again
-T / - t ා test the configuration file for syntax errors
-V / - V ා print the version information and compilation information of nginx

Hot deployment

When the configuration file changes, you need to reload the configuration file:

nginx -s reload

However, if you want to replace the nginx version, you need to use the hot deployment method

  1. View the PID of the existing master process. You can see that the worker process is a child process of the master process

Nginx introduction and basic command line operation

  1. Copy the new binary to the installation directory, and then kill sends a signal to the existing master process
#The master process PID is 83308
kill -USR2 61333

View the nginx process. It can be found that the new master process is also based on the old master process fork

Nginx introduction and basic command line operation

  1. Close the worker process under the old master process. At this time, it will be found that the worker process based on 61333 has exited
#Gracefully close all the worker processes of the old master. After execution, the old master will not exit, but the worker is gone. To prevent problems in the new process, you can also use reload to roll back
kill -WINCH 61333

Nginx introduction and basic command line operation

  1. If there is no problem, exit the old master process. Check again at this time. The old master process no longer exists
#Elegant exit master
kill -quit 61333

Nginx introduction and basic command line operation

Log cutting

Log cutting can be realized with one command

Nginx - s reopen ා regenerates the log file

The official account of “little young Yang” returned to Nginx to receive knowledge maps.

Nginx introduction and basic command line operation