nginx njs docker 試用


主要是基於anadeeppolavarapu/nginx-http3:edge docker 鏡像,使用比較簡單

環境准備

  • docker-compose 文件
version: "3"
services:
    httpservice:
        image: ranadeeppolavarapu/nginx-http3:edge
        volumes:
            - "./nginx.conf:/etc/nginx/nginx.conf"
            - "./h3.nginx.conf:/etc/nginx/conf.d/h3.nginx.conf"
            - "./status.conf:/etc/nginx/conf.d/status.conf"
            - "./localhost.crt:/etc/ssl/localhost.crt"
            - "./localhost.key:/etc/ssl/localhost.key"
            - "./http.js:/opt/http.js"
        ports:
            - "443:443/tcp"
            - "443:443/udp"
            - "8080:8080"
    prome:
        image: nginx/nginx-prometheus-exporter:0.8.0
        command: -nginx.scrape-uri http://httpservice:8080/stub_status
        ports:
            - "9113:9113"
  • njs 加載js配置
  js_import /opt/http.js;
  js_set $foo     http.foo;
  js_set $summary http.summary;
  include /etc/nginx/conf.d/*.conf;
  • http.js
function foo(r) {
    r.log("hello from foo() handler");
    return "foo";
}
function summary(r) {
    var a, s, h;
    s = "JS summary\n\n";
    s += "Method: " + r.method + "\n";
    s += "HTTP version: " + r.httpVersion + "\n";
    s += "Host: " + r.headersIn.host + "\n";
    s += "Remote Address: " + r.remoteAddress + "\n";
    s += "URI: " + r.uri + "\n";
    s += "Headers:\n";
    for (h in r.headersIn) {
        s += " header '" + h + "' is '" + r.headersIn[h] + "'\n";
    }
    s += "Args:\n";
    for (a in r.args) {
        s += " arg '" + a + "' is '" + r.args[a] + "'\n";
    }
    return s;
}
function baz(r) {
    r.status = 200;
    r.headersOut.foo = 1234;
    r.headersOut['Content-Type'] = "text/plain; charset=utf-8";
    r.headersOut['Content-Length'] = 15;
    r.sendHeader();
    r.send("nginx");
    r.send("java");
    r.send("script");
    r.finish();
}
function hello(r) {
    r.return(200, "Hello world!");
}
export default {foo, summary, baz, hello};
 
 
  • nginx location 配置
  location / {
      add_header X-Foo $foo;
      js_content http.baz;
  }
  location = /summary {
      default_type text/plain;
      return 200 $summary;
  }
  location = /hello {
      default_type text/plain;
      js_content http.hello;
  }
  • 訪問效果

 

 

說明

njs 目前來說是越來越強大了,目前就是提供的周邊少點,還好是js ,我們可以使用其他工具加速生成幫助類

參考資料

http://nginx.org/en/docs/njs/node_modules.html
http://nginx.org/en/docs/http/ngx_http_js_module.html
http://nginx.org/en/docs/njs/
http://nginx.org/en/docs/njs/compatibility.html
http://nginx.org/en/docs/njs/reference.html#http_stream


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM