做者 | WenasWeijavascript
Nginx 是一款高性能的 HTTP 服务器/反向代理服务器及 IMAP/POP3/SMTP 代理服务器。由俄罗斯的程序设计师 Igor Sysoev 所开发,官方测试 Nginx 可以支支撑 5 万并发连接,而且 CPU、内存等资源消耗却很是低,运行很是稳定。css
Nginx 代码彻底用C语言从头写成,以事件驱动的方式编写,因此有很是好的性能,同时也是一个很是高效的反向代理、负载平衡服务器。在性能上,Nginx占用不多的系统资源,能支持更多的并发链接,达到更高的访问效率;在功能上,Nginx是优秀的代理服务器和负载均衡服务器;在安装配置上,Nginx安装简单、配置灵活。html
截至2019年12月,差很少世界上每3个网站中就有1个使用 Nginx。前端
Nginx支持热部署,启动速度特别快,还能够在不间断服务的状况下对软件版本或配置进行升级,即便运行数月也无需从新启动。java
在微服务的体系之下,Nginx正在被愈来愈多的项目采用做为网关来使用,配合Lua作限流、熔断等控制。linux
nginx 的使用比较简单,就是几条命令。nginx
nginx -s stop #快速关闭Nginx,可能不保存相关信息,并迅速终止web服务。 nginx -s quit #平稳关闭Nginx,保存相关信息,有安排的结束web服务。 nginx -s reload #因改变了Nginx相关配置,须要从新加载配置而重载。 nginx -s reopen #从新打开日志文件。 nginx -c filename #为 Nginx 指定一个配置文件,来代替缺省的。 nginx -t #不运行,而仅仅测试配置文件。nginx将检查配置文件的语法的正确性,并尝试打开配置文件中所引用到的文件。 nginx -v #显示 nginx 的版本。 nginx -V #显示 nginx 的版本,编译器版本和配置参数。
在linux的sbin目录下中输入:./nginx
代替上面的 nginx
程序员
若是不想每次都敲命令,能够在 nginx 安装目录下新添一个启动批处理文件 startup.bat,双击便可运行。内容以下:web
验证Nginx配置文件是否正确docker
nginx -t -c /conf/nginx.conf
@echo off #rem 若是启动前已经启动nginx并记录下pid文件,会kill指定进程 nginx -s stop #rem 测试配置文件语法正确性 nginx -t -c nginx.conf #rem 显示版本信息 nginx -v #rem 按照指定配置去启动nginx nginx -c nginx.conf
windows 下其余经常使用命令
nginx.exe -s stop #快速关闭Nginx,可能不保存相关信息,并迅速终止web服务。 nginx.exe -s quit #平稳关闭Nginx,保存相关信息,有安排的结束web服务。 nginx.exe -s reload #因改变了Nginx相关配置,须要从新加载配置而重载。 nginx.exe -s reopen #从新打开日志文件。 nginx.exe -c filename #为 Nginx 指定一个配置文件,来代替缺省的。 nginx.exe -t #不运行,而仅仅测试配置文件。nginx将检查配置文件的语法的正确性,并尝试打开配置文件中所引用到的文件。 nginx.exe -v #显示 nginx 的版本。 nginx.exe -V #显示 nginx 的版本,编译器版本和配置参数。
cmd 命令窗口查看 Nginx 启动命令
tasklist /fi "imagename eq nginx.exe"
下图结果为启动成功
验证Nginx配置文件是否正确
nginx.exe -t -c \conf\nginx.conf
下面将介绍 Nginx 的三种部署使用案例:
最新版本nginx-1.9.9,下载地址:
http://nginx.org/download/nginx-1.9.9.zip
下载后解压,解压后以下
有不少种方法启动nginx
nginx.exe
或者 start nginx
,回车便可注意:
启动前能够看到Nginx默认使用启动监听端口为 80, 须要检查 80 端口是否被占用,可以使用命令:
netstat -ano | findstr 0.0.0.0:80
netstat -ano | findstr "80"
如若须要自定义其余端口也须要检查端口是否被占用,修改配置文件启动前也能够进行配置文件检查是否配置正常,检查命令:
nginx.exe -t -c \conf\nginx.conf
检查结果以下图所示:
当咱们修改了nginx 的配置文件 nginx.conf 时,不须要关闭 nginx 后从新启动 nginx,只须要执行命令 nginx -s reload
便可让改动生效
直接在浏览器地址栏输入网址 http://localhost:80,回车,出现如下页面说明启动成功
404test
测试文件夹,添加测试 index.html,html内容页面代码地址:以下两张图所示:
新增修改配置文件: \conf\nginx.conf
server { listen 80; server_name localhost; location / { root C:/Users/wenas/Downloads/nginx-1.9.9/conf/; index index.html index.htm; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } }
访问结果如图所示:
添加转发百度页面地址
server { listen 80; server_name localhost; # 配置建立的 testindex.html 目录地址 location / { root C:/Users/wenas/Downloads/nginx-1.9.9/404test/; index index.html index.htm; } location /baidu { proxy_pass http://www.baidu.com/; proxy_connect_timeout 10s; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } }
访问结果如图所示:
能够看到url地址为代理的百度地址,内容数据由百度的接口提供。
若是使用cmd命令窗口启动nginx,关闭 cmd 窗口是不能结束nginx进程的,可以使用两种方法关闭 nginx
nginx -s stop
(快速中止nginx) 或 nginx -s quit
(完整有序的中止nginx)taskkill /f /t /im nginx.exe
使用 lsb_release -a
查看到 Linux 系统为 Ubuntu 18.04.2 LTS
$ lsb_release -a LSB Version: core-9.20170808ubuntu1-noarch:security-9.20170808ubuntu1-noarch Distributor ID: Ubuntu Description: Ubuntu 18.04.2 LTS Release: 18.04 Codename: bionic
$ vi /etc/apt/sources.list
sources.list
全部的文件内容,可使用 echo > sources.lis
一键清空deb http://mirrors.aliyun.com/ubuntu/ xenial main restricted universe multiverse deb http://mirrors.aliyun.com/ubuntu/ xenial-security main restricted universe multiverse deb http://mirrors.aliyun.com/ubuntu/ xenial-updates main restricted universe multiverse deb http://mirrors.aliyun.com/ubuntu/ xenial-backports main restricted universe multiverse
$ apt-get update
# 切换至root用户 $ sudo su root
Linux 部署 Nginx 目前支持两种安装方式, 一种是 apt-get 的方式, 另外一种是根据包安装的方式。
$ apt-get install nginx
$ nginx -v nginx version: nginx/1.10.3 (Ubuntu)
Nginx文件安装完成以后的文件位置
进入到配置文件地址修改配置文件 nginx.conf
:
$ cd /etc/nginx $ ll total 64 drwxr-xr-x 6 root root 4096 Apr 26 23:55 ./ drwxr-xr-x 94 root root 4096 Apr 25 15:40 ../ drwxr-xr-x 2 root root 4096 Jan 11 2020 conf.d/ -rw-r--r-- 1 root root 1077 Feb 12 2017 fastcgi.conf -rw-r--r-- 1 root root 1007 Feb 12 2017 fastcgi_params -rw-r--r-- 1 root root 2837 Feb 12 2017 koi-utf -rw-r--r-- 1 root root 2223 Feb 12 2017 koi-win -rw-r--r-- 1 root root 3957 Feb 12 2017 mime.types -rw-r--r-- 1 root root 2959 Apr 26 23:55 nginx.conf -rw-r--r-- 1 root root 180 Feb 12 2017 proxy_params -rw-r--r-- 1 root root 636 Feb 12 2017 scgi_params drwxr-xr-x 2 root root 4096 Apr 25 15:40 sites-available/ drwxr-xr-x 2 root root 4096 Apr 25 15:40 sites-enabled/ drwxr-xr-x 2 root root 4096 Apr 25 15:40 snippets/ -rw-r--r-- 1 root root 664 Feb 12 2017 uwsgi_params -rw-r--r-- 1 root root 3071 Feb 12 2017 win-utf
修改配置文件以下:
#user nobody; worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; server { listen 7070; server_name localhost; location / { # 上传程序员404-index.html到该指定目录下 root /usr/share/nginx/html/; index index.html index.htm; } } }
验证配置文件是否配置正确
$ nginx -t -c /etc/nginx/nginx.conf
验证结果以下:
$ nginx -t -c /etc/nginx/nginx.conf nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful
启动Nginx指令:
service nginx start
查看Nginx启动进程:
$ ps -ef|grep nginx root 1980 1 0 20:14 ? 00:00:00 nginx: master process /usr/sbin/nginx -g daemon on; master_process on; nobody 1983 1980 0 20:14 ? 00:00:00 nginx: worker process root 2051 11018 0 20:14 pts/0 00:00:00 grep --color=auto nginx root 25087 25065 0 Apr25 ? 00:00:00 nginx: master process nginx -g daemon off; systemd+ 25160 25087 0 Apr25 ? 00:00:00 nginx: worker process
在浏览器面上打开URL: ip:7070
就能看到咱们可爱的程序猿404了
# 完全卸载nginx $ apt-get --purge autoremove nginx #查看nginx的版本号 $ nginx -v
apt-get install gcc apt-get install libpcre3 libpcre3-dev apt-get install zlib1g zlib1g-dev # Ubuntu14.04的仓库中没有发现openssl-dev,由下面openssl和libssl-dev替代 #apt-get install openssl openssl-dev sudo apt-get install openssl sudo apt-get install libssl-dev
cd /usr/local mkdir nginx cd nginx wget http://nginx.org/download/nginx-1.13.7.tar.gz tar -xvf nginx-1.13.7.tar.gz
# 进入nginx目录 /usr/local/nginx/nginx-1.13.7 # 执行命令 ./configure # 执行make命令 make # 执行make install命令 make install
#进入nginx启动目录 cd /usr/local/nginx/sbin # 启动nginx ./nginx
访问nginx
网页输入ip地址: 开放端口,访问成功,到此,nginx安装完毕
本篇部署须要使用到 Docker 容器化引擎技术部署,须要在 Linux 上安装 Docker环境与Docker-compose环境
$ docker -v Docker version 18.09.7, build 2d0083d $ docker-compose -v docker-compose version 1.25.0-rc4, build 8f3c9c58
docker pull nginx
操做文件目录为: /usr/local/docker/nginx
文件目录为:
- conf/ - nginx.conf - docker-compose.yml
(1)docker-compose.yml配置文件
version: '3.1' services: nginx: restart: always image: nginx container_name: nginx ports: - 8081:80 volumes: - ./conf/nginx.conf:/etc/nginx/nginx.conf - /home/wenas/html/:/home/wenas/html/
(2)nginx.conf配置文件
user nginx; worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; # 配置一个虚拟主机 server { listen 80; location /testhtml/ { alias /home/wenas/html/; autoindex on; } } }
启动命令
$ docker-compose up -d Starting nginx ... done
查看启动的Nginx容器
$ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 8141bae75054 nginx "nginx -g 'daemon of…" 12 days ago Up 26 seconds 0.0.0.0:8081->80/tcp nginx
访问URL : IP:8081/testhtml/
网站在实际运营过程当中,多半都是有多台服务器运行着一样的app,这时须要使用负载均衡来分流。
nginx也能够实现简单的负载均衡功能。
假设这样一个应用场景:将应用部署在 192.168.1.11:80、192.168.1.12:80、192.168.1.13:80 三台linux环境的服务器上。网站域名叫 www.helloworld.com,公网IP为 192.168.1.11。在公网IP所在的服务器上部署 nginx,对全部请求作负载均衡处理。
nginx.conf 配置以下:
http { #设定mime类型,类型由mime.type文件定义 include /etc/nginx/mime.types; default_type application/octet-stream; #设定日志格式 access_log /var/log/nginx/access.log; #设定负载均衡的服务器列表 upstream load_balance_server { #weigth参数表示权值,权值越高被分配到的概率越大 server 192.168.1.11:80 weight=5; server 192.168.1.12:80 weight=1; server 192.168.1.13:80 weight=6; } #HTTP服务器 server { #侦听80端口 listen 80; #定义使用www.xx.com访问 server_name www.helloworld.com; #对全部请求进行负载均衡请求 location / { root /root; #定义服务器的默认网站根目录位置 index index.html index.htm; #定义首页索引文件的名称 proxy_pass http://load_balance_server ;#请求转向load_balance_server 定义的服务器列表 #如下是一些反向代理的配置(可选择性配置) #proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; #后端的Web服务器能够经过X-Forwarded-For获取用户真实IP proxy_set_header X-Forwarded-For $remote_addr; proxy_connect_timeout 90; #nginx跟后端服务器链接超时时间(代理链接超时) proxy_send_timeout 90; #后端服务器数据回传时间(代理发送超时) proxy_read_timeout 90; #链接成功后,后端服务器响应时间(代理接收超时) proxy_buffer_size 4k; #设置代理服务器(nginx)保存用户头信息的缓冲区大小 proxy_buffers 4 32k; #proxy_buffers缓冲区,网页平均在32k如下的话,这样设置 proxy_busy_buffers_size 64k; #高负荷下缓冲大小(proxy_buffers*2) proxy_temp_file_write_size 64k; #设定缓存文件夹大小,大于这个值,将从upstream服务器传 client_max_body_size 10m; #容许客户端请求的最大单文件字节数 client_body_buffer_size 128k; #缓冲区代理缓冲用户端请求的最大字节数 } } }
当一个网站功能愈来愈丰富时,每每须要将一些功能相对独立的模块剥离出来,独立维护。这样的话,一般,会有多个 webapp。
举个例子:假如 www.helloworld.com 站点有好几个webapp,finance(金融)、product(产品)、admin(用户中心)。访问这些应用的方式经过上下文(context)来进行区分:
www.helloworld.com/finance/
www.helloworld.com/product/
www.helloworld.com/admin/
咱们知道,http的默认端口号是80,若是在一台服务器上同时启动这3个 webapp 应用,都用80端口,确定是不成的。因此,这三个应用须要分别绑定不一样的端口号。
那么,问题来了,用户在实际访问 www.helloworld.com 站点时,访问不一样 webapp,总不会还带着对应的端口号去访问吧。因此,你再次须要用到反向代理来作处理。
配置也不难,来看看怎么作吧:
http { #此处省略一些基本配置 upstream product_server{ server www.helloworld.com:8081; } upstream admin_server{ server www.helloworld.com:8082; } upstream finance_server{ server www.helloworld.com:8083; } server { #此处省略一些基本配置 #默认指向product的server location / { proxy_pass http://product_server; } location /product/{ proxy_pass http://product_server; } location /admin/ { proxy_pass http://admin_server; } location /finance/ { proxy_pass http://finance_server; } } }
一些对安全性要求比较高的站点,可能会使用 HTTPS(一种使用ssl通讯标准的安全HTTP协议)。
这里不科普 HTTP 协议和 SSL 标准。可是,使用 nginx 配置 https 须要知道几点:
#HTTP服务器 server { #监听443端口。443为知名端口号,主要用于HTTPS协议 listen 443 ssl; #定义使用www.xx.com访问 server_name www.helloworld.com; #ssl证书文件位置(常见证书文件格式为:crt/pem) ssl_certificate cert.pem; #ssl证书key位置 ssl_certificate_key cert.key; #ssl配置参数(选择性配置) ssl_session_cache shared:SSL:1m; ssl_session_timeout 5m; #数字签名,此处使用MD5 ssl_ciphers HIGH:!aNULL:!MD5; ssl_prefer_server_ciphers on; location / { root /root; index index.html index.htm; } }
有时候,咱们须要配置静态站点(即 html 文件和一堆静态资源)。
举例来讲:若是全部的静态资源都放在了 /app/dist 目录下,咱们只须要在 nginx.conf 中指定首页以及这个站点的 host 便可。
配置以下:
worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; gzip on; gzip_types text/plain application/x-javascript text/css application/xml text/javascript application/javascript image/jpeg image/gif image/png; gzip_vary on; server { listen 80; server_name static.zp.cn; location / { root /app/dist; index index.html; #转发任何请求到 index.html } } }
而后,添加 HOST:
127.0.0.1 static.zp.cn
此时,在本地浏览器访问 static.zp.cn ,就能够访问静态站点了。
web 领域开发中,常常采用先后端分离模式。这种模式下,前端和后端分别是独立的 web 应用程序,例如:后端是 Java 程序,前端是 React 或 Vue 应用。
各自独立的 web app 在互相访问时,势必存在跨域问题。解决跨域问题通常有两种思路:
在后端服务器设置 HTTP 响应头,把你须要运行访问的域名加入加入 Access-Control-Allow-Origin 中。
把后端根据请求,构造json数据,并返回,前端用 jsonp 跨域。
这两种思路,本文不展开讨论。
须要说明的是,nginx 根据第一种思路,也提供了一种解决跨域的解决方案。
举例:www.helloworld.com 网站是由一个前端 app ,一个后端 app 组成的。前端端口号为 9000, 后端端口号为 8080。
前端和后端若是使用 http 进行交互时,请求会被拒绝,由于存在跨域问题。来看看,nginx 是怎么解决的吧:
首先,在 enable-cors.conf 文件中设置 cors :
# allow origin list set $ACAO '*'; # set single origin if ($http_origin ~* (www.helloworld.com)$) { set $ACAO $http_origin; } if ($cors = "trueget") { add_header 'Access-Control-Allow-Origin' "$http_origin"; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type'; } if ($request_method = 'OPTIONS') { set $cors "${cors}options"; } if ($request_method = 'GET') { set $cors "${cors}get"; } if ($request_method = 'POST') { set $cors "${cors}post"; }
接下来,在你的服务器中 include enable-cors.conf 来引入跨域配置:
# ---------------------------------------------------- # 此文件为项目 nginx 配置片断 # 能够直接在 nginx config 中 include(推荐) # 或者 copy 到现有 nginx 中,自行配置 # www.helloworld.com 域名需配合 dns hosts 进行配置 # 其中,api 开启了 cors,需配合本目录下另外一份配置文件 # ---------------------------------------------------- upstream front_server{ server www.helloworld.com:9000; } upstream api_server{ server www.helloworld.com:8080; } server { listen 80; server_name www.helloworld.com; location ~ ^/api/ { include enable-cors.conf; proxy_pass http://api_server; rewrite "^/api/(.*)$" /$1 break; } location ~ ^/ { proxy_pass http://front_server; } }