Nginx

說明

為何需要使用Nginx?

一般如果要在node.js使用vhost的功能,可以用以下的方法來設定

APP.js service進入點

http://a.test 會跑A.js的網站

http://b.test 會跑B.js的網站

var express = require('express');
var http = express();
http.use(express.vhost('a.test', require('./A.js').app));
http.use(express.vhost('b.test', require('./B.js').app));
app.listen(80);

A.js

var express = require('express');
var app = express();
app.get('/*', function(req, res) {
    console.log('A');
    res.send('A');
});

module.exports = app;

B.js

var express = require('express');
var app = express();
app.get('/*', function(req, res) {
    console.log('B');
    res.send('B');
});

module.exports = app;

執行APP.js,A及B兩個網站也一起被開啟

#node APP.js

但以上的做法有一個缺點

就是當網站在執行期間,想要修改A網站

就必須把APP.js停止再重啟

如此B網站就算沒要修改,也會一起被重啟

為了方便解決這個問題,所以利用了Nginx代理vhost的工作

將A及B獨立執行,並用Nginx的vhost設定指向兩個服務上

安裝

windows

下載位置:http://nginx.org/

有寫Windows為windows版

Centos 6.4

# yum install epel-release
# yum install nginx
# yum install epel-release
Loaded plugins: fastestmirror, security
Setting up Install Process
Determining fastest mirrors
epel/metalink                                            | 5.3 kB     00:00
 * base: mirror01.idc.hinet.net
 * epel: mirror01.idc.hinet.net
 * extras: mirror01.idc.hinet.net
 * remi: remi.kazukioishi.net
 * remi-test: remi.kazukioishi.net
 * updates: mirror01.idc.hinet.net
base                                                     | 3.7 kB     00:00
epel                                                     | 4.3 kB     00:00
epel/primary_db                                          | 5.8 MB     00:00
extras                                                   | 3.4 kB     00:00
extras/primary_db                                        |  34 kB     00:00
mongodb                                                  |  951 B     00:00
nodesource                                               | 2.5 kB     00:00
nodesource/primary_db                                    |  20 kB     00:00
remi                                                     | 2.9 kB     00:00
remi/primary_db                                          | 1.4 MB     00:00
remi-test                                                | 2.9 kB     00:00
remi-test/primary_db                                     | 271 kB     00:00
updates                                                  | 3.4 kB     00:00
updates/primary_db                                       | 3.9 MB     00:00
Package epel-release-6-8.noarch already installed and latest version
Nothing to do

# yum install nginx
Loaded plugins: fastestmirror, security
Setting up Install Process
Loading mirror speeds from cached hostfile
 * base: mirror01.idc.hinet.net
 * epel: mirror01.idc.hinet.net
 * extras: mirror01.idc.hinet.net
 * remi: remi.kazukioishi.net
 * remi-test: remi.kazukioishi.net
 * updates: mirror01.idc.hinet.net
Resolving Dependencies
--> Running transaction check
---> Package nginx.x86_64 0:1.0.15-12.el6 will be installed
--> Processing Dependency: nginx-filesystem = 1.0.15-12.el6 for package: nginx-1.0.15-12.el6.x86_64
--> Processing Dependency: nginx-filesystem for package: nginx-1.0.15-12.el6.x86_64
--> Processing Dependency: GeoIP for package: nginx-1.0.15-12.el6.x86_64
--> Processing Dependency: libGeoIP.so.1()(64bit) for package: nginx-1.0.15-12.el6.x86_64
--> Running transaction check
---> Package GeoIP.x86_64 0:1.6.5-1.el6 will be installed
--> Processing Dependency: geoipupdate for package: GeoIP-1.6.5-1.el6.x86_64
--> Processing Dependency: GeoIP-data for package: GeoIP-1.6.5-1.el6.x86_64
---> Package nginx-filesystem.noarch 0:1.0.15-12.el6 will be installed
--> Running transaction check
---> Package GeoIP-GeoLite-data.noarch 0:2015.12-1.el6 will be installed
--> Processing Dependency: GeoIP-GeoLite-data-extra = 2015.12-1.el6 for package: GeoIP-GeoLite-data-2015.12-1.el6.noarch
---> Package geoipupdate.x86_64 0:2.2.1-2.el6 will be installed
--> Running transaction check
---> Package GeoIP-GeoLite-data-extra.noarch 0:2015.12-1.el6 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

================================================================================
 Package                       Arch        Version              Repository
                                                                           Size
================================================================================
Installing:
 nginx                         x86_64      1.0.15-12.el6        epel      404 k
Installing for dependencies:
 GeoIP                         x86_64      1.6.5-1.el6          epel      113 k
 GeoIP-GeoLite-data            noarch      2015.12-1.el6        epel      363 k
 GeoIP-GeoLite-data-extra      noarch      2015.12-1.el6        epel       23 M
 geoipupdate                   x86_64      2.2.1-2.el6          epel       28 k
 nginx-filesystem              noarch      1.0.15-12.el6        epel      8.1 k

Transaction Summary
================================================================================
Install       6 Package(s)

Total download size: 24 M
Installed size: 49 M
Is this ok [y/N]: y
Downloading Packages:
(1/6): GeoIP-1.6.5-1.el6.x86_64.rpm                      | 113 kB     00:00
(2/6): GeoIP-GeoLite-data-2015.12-1.el6.noarch.rpm       | 363 kB     00:00
(3/6): GeoIP-GeoLite-data-extra-2015.12-1.el6.noarch.rpm |  23 MB     00:02
(4/6): geoipupdate-2.2.1-2.el6.x86_64.rpm                |  28 kB     00:00
(5/6): nginx-1.0.15-12.el6.x86_64.rpm                    | 404 kB     00:00
(6/6): nginx-filesystem-1.0.15-12.el6.noarch.rpm         | 8.1 kB     00:00
--------------------------------------------------------------------------------
Total                                           8.7 MB/s |  24 MB     00:02
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
  Installing : GeoIP-GeoLite-data-extra-2015.12-1.el6.noarch                1/6
  Installing : GeoIP-GeoLite-data-2015.12-1.el6.noarch                      2/6
  Installing : geoipupdate-2.2.1-2.el6.x86_64                               3/6
  Installing : GeoIP-1.6.5-1.el6.x86_64                                     4/6
  Installing : nginx-filesystem-1.0.15-12.el6.noarch                        5/6
  Installing : nginx-1.0.15-12.el6.x86_64                                   6/6
  Verifying  : nginx-filesystem-1.0.15-12.el6.noarch                        1/6
  Verifying  : GeoIP-1.6.5-1.el6.x86_64                                     2/6
  Verifying  : GeoIP-GeoLite-data-2015.12-1.el6.noarch                      3/6
  Verifying  : geoipupdate-2.2.1-2.el6.x86_64                               4/6
  Verifying  : GeoIP-GeoLite-data-extra-2015.12-1.el6.noarch                5/6
  Verifying  : nginx-1.0.15-12.el6.x86_64                                   6/6

Installed:
  nginx.x86_64 0:1.0.15-12.el6

Dependency Installed:
  GeoIP.x86_64 0:1.6.5-1.el6
  GeoIP-GeoLite-data.noarch 0:2015.12-1.el6
  GeoIP-GeoLite-data-extra.noarch 0:2015.12-1.el6
  geoipupdate.x86_64 0:2.2.1-2.el6
  nginx-filesystem.noarch 0:1.0.15-12.el6

Complete!

設定

設定檔位置

windows

conf/nginx.conf

CentOS

/etc/nginx/nginx.conf
# vhost的設定路徑如下
/etc/nginx/conf.d/

設定檔說明

/etc/nginx/nginx.conf

# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

events {
    worker_connections 1024;
}

http {
    #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  /var/log/nginx/access.log  main;
    #每秒最多十個請求
    limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    server_tokens off;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;
    upstream nodejs {
        ip_hash;
        server 127.0.0.1:1234;
    }

}

/etc/nginx/conf.d/nodejs.conf

#vhost 1
    #設定http://test:8080/及http://test2:8080/會指向http_nodejs[localhost:1234]
    #listen 為要listen的port
    #server_name 為外部的host名稱
    server {
        listen 443 ssl http2;
        listen [::]:443 ssl http2;
ssl on;
#公鑰文件(Globalsign頒發的憑證)
ssl_certificate /etc/letsencrypt/live/linenet.net/fullchain.pem;
#私鑰文件
ssl_certificate_key /etc/letsencrypt/live/linenet.net/privkey.pem;

ssl_session_timeout 2h;
ssl_session_cache shared:SSL:30m;
ssl_session_tickets off;

ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256';
ssl_prefer_server_ciphers on;

        server_name linenet.net www.linenet.net game.linenet.net;
        charset utf-8;
        access_log  /var/log/nginx/linenet.access.log;
        add_header Strict-Transport-Security max-age=7884000;
        location / {
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $host;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_http_version 1.1;
            proxy_pass http://127.0.0.1:1234;
        }
    }

noip.conf

#ip導向
server {
        listen 443;
        server_name 130.211.242.244;
        return 301 https://www.linenet.net;
}

tossl.conf

#ssl導向

server {
    listen 80;
    listen [::]:80;
    server_name linenet.net www.linenet.net game.linenet.net;
return 301 https://$host$request_uri;
}

Nginx操作

啟用

windows啟用指令

start nginx.exe

CentOS 6.4

/etc/init.d/nginx start

CentOS 7

$ sudo systemctl enable nginx
$ sudo systemctl restart nginx

如果發現有問題

$ sudo systemctl status nginx -l

看是不是

/usr/share/nginx/logs/xxxx.log Permission denied

如果是,就先把設定檔的access_log mark起來

這是SELinux設定上的問題

$ sudo vi /etc/nginx/conf.d/xxx.conf
#access_log  logs/xxx.access.log;

再執行一次看有沒問題

$ sudo systemctl start nginx
#如果沒題題就看看nginx用到什麼role
$ ps -eZ
system_u:system_r:httpd_t:s0     1316 ?        00:00:00 nginx
system_u:system_r:httpd_t:s0     1317 ?        00:00:00 nginx
#是httpd_t
#先暫時關掉SELinux
$ sudo setenforce 0
#設定role
$ sudo chcon -R -t httpd_t /usr/share/nginx/logs/xxx.linenet.log
#開啟SELinux
$ sudo setenforce 1
$ sudo systemctl start nginx
$ sudo systemctl enable nginx

查看目前已啟用的執行緒

tasklist /fi "imagename eq nginx.exe"

Image Name           PID Session Name     Session#    Mem Usage
=============== ======== ============== ========== ============
nginx.exe            652 Console                 0      2 780 K
nginx.exe           1332 Console                 0      3 112 K

相關指令

指令 說明
nginx -s stop fast shutdown
nginx -s quit graceful shutdown
nginx -s reload changing configuration, starting new worker processes with a new configuration, graceful shutdown of old worker processes
nginx -s reopen re-opening log files