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