在15年的时候就开始使用nginx,用的最多地方就是反向代理。但一直没有深入研究nginx架构以及其他用途。最近项目不是很紧,闲暇时间梳理了一下nginx的研究一些体会;先上架构图
一、NGINX架构
Nginx是一款高性能的web服务器和反向代理服务器,同时也是一个 IMAP/POP3/SMTP 代理服务器;而Nginx的高性能实际上和它的架构是分不开的
- Nginx是1个master、多worker形式的多进程工作方式,master进程负责管理worker进程,包括监听外部信号,向worker进程发送信号,管理worker进程的运行状态。
- 多个worker进程相互独立,平等。一个请求只能被一个worker进程消费;对多个worker进程来说,独立的进程,不需要加锁,省去了锁的开销;其次,采用独立的进程,可以让互相之间不会影响,一个进程退出后,其它进程还在工作,服务不会中断,master进程则很快启动新的worker进程。当然,worker进程的异常退出,肯定是程序有bug了,异常退出,会导致当前worker上的所有请求失败,不过不会影响到所有请求,所以降低了风险
- Nginx采用异步非阻塞的方式处理请求,这样就可以处理高并发的请求;建议worker进程数和CPU数相同,减少worker进程过多竞争CPU带来的资源开销,一个worker进程最大不超过1024个连接
二、NGINX启动
1.去官网http://nginx.org/en/download.html下载一个稳定版本,我这里下载的是windows 1.12.2版本的,解压之后,启动nginx.exe,在进程就能看到一个master进程,一个worker进程,启动失败的话可以到logs文件下看error日志
2. 对于重启、退出等可以使用一些命令脚本
nginx -s start 启动
nginx -s stop 快速退出
nginx -s quit 退出
nginx -s reload 重启
三、NGINX配置文件nginx.conf
nginx在conf文件下有很多配置文件,最核心的是nginx.conf文件,正常http模块、负载均衡、反向代理、静态模块等等都是在这个配置文件里配置,先贴上默认的配置文件
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include 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/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;
# location / {
# root html;
# index index.html index.htm;
# }
#}
# HTTPS server
#
#server {
# listen 443 ssl;
# server_name localhost;
# ssl_certificate cert.pem;
# ssl_certificate_key cert.key;
# ssl_session_cache shared:SSL:1m;
# ssl_session_timeout 5m;
# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on;
# location / {
# root html;
# index index.html index.htm;
# }
#}
}