SlideShare a Scribd company logo
NGINX + Lua
Using NGINX/OpenResty
with embedded Lua
Epifanov Ivan,
Lead Developer
Lua
• Fast
• Light (241K)
• Simple
• Powerfull
• Embeddable
• Portable
Lua do Pesadelo
(Nightmare Moon)
Who uses Lua?
• Games: WoW, Angry Birds, Baldur's
Gate, Civilization V, Crysis, HoMM V,
L.A. Noire, etc.
• Software: Lightroom, MySQL proxy,
MySQL Workbench, Celestia, Far
Manager, GIMP, MediaWiki, etc.
• Misc.: Mercedes Autos, LG Smart TV,
Space Shuttle Gas Detection, etc.
LuaJIT
• JIT compilation for lua code
• High performance (3-100x)
• Low memory footprint
• Crossplatform
• Cross-architecture (x86, ARM, MIPS,
PPC
• local ffi = require("ffi")
ffi.cdef[[
int printf(const char *fmt, ...);
]]
ffi.C.printf("Hello %s!", "world")
OpenResty/NGINX-LUA
• NGINX bundle with luajit and additional
modules.
• Developed by TaoBao and CloudFlare
• Access to every processing stage of
nginx
• Non-blocking without callback-hell
• co-sockets, shared pool and sub-
requests
Full control
• init_by_lua(file)
• init_worker_by_lua(file)
• set_by_lua(file)
• log_by_lua(file)
• content_by_lua(file)
• header_filter_by_lua(file)
• access_by_lua(file)
• rewrite_by_lua(file)
What
• Databases: lua-resty-redis, lua-resty-
mysql, etc.
• Templates: lua-resty-template, etlua
• Frameworks: Lapis
• Preprocessors: Moonscript
(coffiescript-like syntax)
Where
• Image Server, for image resizes (now)
• Image Server, for queue, API, control
(in the future)
• Mobile detection
• EDGE-side block cache
• Maybe parts of SSO API, like cookie-
setter
For example...
Redis RESTfull api for userscores
• GET /scores
return userid list
• GET/PUT/POST/DELETE /scores/<id>
manipulate user scores
Init
http {
...
init_by_lua '
json = require "cjson";
redis = require "resty.redis"
';
...
server {
...
set $redis_host "192.168.2.104";
set $redis_port "6379";
set $redis_pass "nightmaremoon";
...
}
...
}
Init
local red = redis:new()
local ok, err = red:connect(ngx.var.redis_host, ngx.var.redis_port)
if not ok then
ngx.say("failed to connect: ", err)
return
end
local ok, err = red:auth(ngx.var.redis_pass)
if not ok then
ngx.say("failed to auth: ", err)
return
end
GET /scores
local keys, err = red:keys("*")
local scores = {}
for i, key in ipairs(keys) do
scores[key] = red:get(key)
end
ngx.header.content_type = "text/plain"
ngx.say(json.encode(scores))
GET /score/<userid>
location ~* ^/keys/(?<key>.*)$
{
content_by_lua '
-- ... (connect and auth)
local val, err = red:get("user:score:" ..
ngx.var.key)
ngx.say(json.encode({ value = val }))
';
}
DELETE /scores/<userid>
local method = ngx.req.get_method()
if method == "GET" then
...
elseif method == "PUT" then
...
elseif method == "DELETE" then
red:delete("user:score:" .. ngx.var.key)
ngx.say(json.encode({result = "success"}))
end
PUT /scores/<userid>
data =
json.decode(ngx.req.get_body_data())
red:set("user:score:" .. ngx.var.key,
data.value)
ngx.req.set_method(ngx.HTTP_GET)
ngx.exec("/scores/" .. ngx.var.key)
GET /scores/max
local max = 0
local keys = redis.call('keys', 'user:score:*');
for i, key in ipairs(keys) do
local value = tonumber(redis.call('get', key));
if value > max then
max = value
end
end
return max
GET /scores/max
local sha, err = red:script("load","...")
local val, err = red:evalsha(sha, 0)
ngx.say(json.encode({ max = val }))
GET /scores/max/<id1>,...,<idN>
local max = 0
for key in string.gmatch(ngx.var.key, '([^,]+)') do
local res = ngx.location.capture("/scores/" .. key)
data = json.decode(res.body)
if tonumber(data.value) > max then
max = tonumber(data.value)
end
end
ngx.say(json.encode({ max = max }))
What to read
• https://gist.github.com/isage/509d99cf4
def36014f5c
• http://wiki.nginx.org/HttpLuaModule
• http://openresty.org
• search github for lua-resty*
??????
Questions?
PROFIT!
2015, Epifanov Ivan
http://github.com/isage/

More Related Content

PDF
Nodejs - A quick tour (v6)
PDF
Node.js in production
KEY
Node.js - A practical introduction (v2)
PDF
Nodejs - Should Ruby Developers Care?
PDF
Nodejs - A quick tour (v4)
PDF
Nodejs - A quick tour (v5)
PDF
Nodejs - A-quick-tour-v3
KEY
Node.js - As a networking tool
Nodejs - A quick tour (v6)
Node.js in production
Node.js - A practical introduction (v2)
Nodejs - Should Ruby Developers Care?
Nodejs - A quick tour (v4)
Nodejs - A quick tour (v5)
Nodejs - A-quick-tour-v3
Node.js - As a networking tool

What's hot (20)

PPT
{{more}} Kibana4
PDF
Nodejs a-practical-introduction-oredev
PPT
ELK stack at weibo.com
PDF
Redis - Usability and Use Cases
PDF
Functional Operations (Functional Programming at Comcast Labs Connect)
PDF
Node.js - A Quick Tour II
PDF
Introduction to redis - version 2
ODP
Using Logstash, elasticsearch & kibana
PDF
From zero to hero - Easy log centralization with Logstash and Elasticsearch
PDF
Openstack at NTT Feb 7, 2011
PDF
Everything as Code with Terraform
PDF
Dirty - How simple is your database?
PDF
Paris Redis Meetup Introduction
PDF
并发模型介绍
PDF
Redis modules 101
PDF
PDF
tdc2012
PDF
Redis — The AK-47 of Post-relational Databases
PDF
Object Storage with Gluster
PDF
Ground Control to Nomad Job Dispatch
{{more}} Kibana4
Nodejs a-practical-introduction-oredev
ELK stack at weibo.com
Redis - Usability and Use Cases
Functional Operations (Functional Programming at Comcast Labs Connect)
Node.js - A Quick Tour II
Introduction to redis - version 2
Using Logstash, elasticsearch & kibana
From zero to hero - Easy log centralization with Logstash and Elasticsearch
Openstack at NTT Feb 7, 2011
Everything as Code with Terraform
Dirty - How simple is your database?
Paris Redis Meetup Introduction
并发模型介绍
Redis modules 101
tdc2012
Redis — The AK-47 of Post-relational Databases
Object Storage with Gluster
Ground Control to Nomad Job Dispatch
Ad

Viewers also liked (20)

PDF
Nginx Scripting - Extending Nginx Functionalities with Lua
PDF
Socket programming, and openresty
PDF
Nginx+lua在阿里巴巴的使用
PDF
Hacking Nginx at Taobao
PDF
Lua tech talk
PDF
Lua as a business logic language in high load application
PDF
Using ngx_lua in UPYUN
PPTX
Script up your application with Lua! -- RyanE -- OpenWest 2014
PDF
KEY
淺入淺出 GDB
PDF
Gdb tutorial-handout
PDF
Las16 309 - lua jit arm64 port - status
PDF
Learn C Programming Language by Using GDB
PPT
Perl在nginx里的应用
PDF
基于OpenResty的百万级长连接推送
PDF
The basics and design of lua table
PPT
高性能Web服务器Nginx及相关新技术的应用实践
PDF
Devinsampa nginx-scripting
PDF
LAS16-400K2: TianoCore – Open Source UEFI Community Update
PDF
OAuth and OpenID Connect for Microservices
Nginx Scripting - Extending Nginx Functionalities with Lua
Socket programming, and openresty
Nginx+lua在阿里巴巴的使用
Hacking Nginx at Taobao
Lua tech talk
Lua as a business logic language in high load application
Using ngx_lua in UPYUN
Script up your application with Lua! -- RyanE -- OpenWest 2014
淺入淺出 GDB
Gdb tutorial-handout
Las16 309 - lua jit arm64 port - status
Learn C Programming Language by Using GDB
Perl在nginx里的应用
基于OpenResty的百万级长连接推送
The basics and design of lua table
高性能Web服务器Nginx及相关新技术的应用实践
Devinsampa nginx-scripting
LAS16-400K2: TianoCore – Open Source UEFI Community Update
OAuth and OpenID Connect for Microservices
Ad

Similar to Nginx-lua (20)

PDF
Node.js - async for the rest of us.
PPTX
Building and Scaling Node.js Applications
PPT
Building an ActionScript Game Server with over 15,000 Concurrent Connections
PDF
JavaScript in 2015
PDF
Red Hat Forum Tokyo - OpenStack Architecture
PDF
Game Development with Corona SDK and Lua - Lua Workshop 2014
PDF
Workshop Infrastructure as Code - Suestra
PDF
Node.js
PDF
Docker deploy
ODP
Getting started with RDO Havana
KEY
Writing robust Node.js applications
PPTX
0x01 - Breaking into Linux VMs for Fun and Profit
PDF
Next Generation DevOps in Drupal: DrupalCamp London 2014
PDF
Automating Complex Setups with Puppet
PDF
Automating complex infrastructures with Puppet
PDF
Comredis
KEY
Perl on Amazon Elastic MapReduce
PDF
From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016
PDF
Nko workshop - node js crud & deploy
PDF
R-House (LSRC)
Node.js - async for the rest of us.
Building and Scaling Node.js Applications
Building an ActionScript Game Server with over 15,000 Concurrent Connections
JavaScript in 2015
Red Hat Forum Tokyo - OpenStack Architecture
Game Development with Corona SDK and Lua - Lua Workshop 2014
Workshop Infrastructure as Code - Suestra
Node.js
Docker deploy
Getting started with RDO Havana
Writing robust Node.js applications
0x01 - Breaking into Linux VMs for Fun and Profit
Next Generation DevOps in Drupal: DrupalCamp London 2014
Automating Complex Setups with Puppet
Automating complex infrastructures with Puppet
Comredis
Perl on Amazon Elastic MapReduce
From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016
Nko workshop - node js crud & deploy
R-House (LSRC)

Recently uploaded (20)

PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PDF
null (2) bgfbg bfgb bfgb fbfg bfbgf b.pdf
PPTX
6ME3A-Unit-II-Sensors and Actuators_Handouts.pptx
PDF
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PPTX
Safety Seminar civil to be ensured for safe working.
PDF
III.4.1.2_The_Space_Environment.p pdffdf
PPTX
UNIT 4 Total Quality Management .pptx
PDF
Unit I ESSENTIAL OF DIGITAL MARKETING.pdf
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PDF
R24 SURVEYING LAB MANUAL for civil enggi
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PPTX
Sustainable Sites - Green Building Construction
PPTX
Fundamentals of Mechanical Engineering.pptx
PDF
Categorization of Factors Affecting Classification Algorithms Selection
PPT
Introduction, IoT Design Methodology, Case Study on IoT System for Weather Mo...
PDF
Artificial Superintelligence (ASI) Alliance Vision Paper.pdf
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PDF
737-MAX_SRG.pdf student reference guides
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
null (2) bgfbg bfgb bfgb fbfg bfbgf b.pdf
6ME3A-Unit-II-Sensors and Actuators_Handouts.pptx
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
Safety Seminar civil to be ensured for safe working.
III.4.1.2_The_Space_Environment.p pdffdf
UNIT 4 Total Quality Management .pptx
Unit I ESSENTIAL OF DIGITAL MARKETING.pdf
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
R24 SURVEYING LAB MANUAL for civil enggi
Foundation to blockchain - A guide to Blockchain Tech
Sustainable Sites - Green Building Construction
Fundamentals of Mechanical Engineering.pptx
Categorization of Factors Affecting Classification Algorithms Selection
Introduction, IoT Design Methodology, Case Study on IoT System for Weather Mo...
Artificial Superintelligence (ASI) Alliance Vision Paper.pdf
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
737-MAX_SRG.pdf student reference guides

Nginx-lua

  • 1. NGINX + Lua Using NGINX/OpenResty with embedded Lua Epifanov Ivan, Lead Developer
  • 2. Lua • Fast • Light (241K) • Simple • Powerfull • Embeddable • Portable Lua do Pesadelo (Nightmare Moon)
  • 3. Who uses Lua? • Games: WoW, Angry Birds, Baldur's Gate, Civilization V, Crysis, HoMM V, L.A. Noire, etc. • Software: Lightroom, MySQL proxy, MySQL Workbench, Celestia, Far Manager, GIMP, MediaWiki, etc. • Misc.: Mercedes Autos, LG Smart TV, Space Shuttle Gas Detection, etc.
  • 4. LuaJIT • JIT compilation for lua code • High performance (3-100x) • Low memory footprint • Crossplatform • Cross-architecture (x86, ARM, MIPS, PPC • local ffi = require("ffi") ffi.cdef[[ int printf(const char *fmt, ...); ]] ffi.C.printf("Hello %s!", "world")
  • 5. OpenResty/NGINX-LUA • NGINX bundle with luajit and additional modules. • Developed by TaoBao and CloudFlare • Access to every processing stage of nginx • Non-blocking without callback-hell • co-sockets, shared pool and sub- requests
  • 6. Full control • init_by_lua(file) • init_worker_by_lua(file) • set_by_lua(file) • log_by_lua(file) • content_by_lua(file) • header_filter_by_lua(file) • access_by_lua(file) • rewrite_by_lua(file)
  • 7. What • Databases: lua-resty-redis, lua-resty- mysql, etc. • Templates: lua-resty-template, etlua • Frameworks: Lapis • Preprocessors: Moonscript (coffiescript-like syntax)
  • 8. Where • Image Server, for image resizes (now) • Image Server, for queue, API, control (in the future) • Mobile detection • EDGE-side block cache • Maybe parts of SSO API, like cookie- setter
  • 9. For example... Redis RESTfull api for userscores • GET /scores return userid list • GET/PUT/POST/DELETE /scores/<id> manipulate user scores
  • 10. Init http { ... init_by_lua ' json = require "cjson"; redis = require "resty.redis" '; ... server { ... set $redis_host "192.168.2.104"; set $redis_port "6379"; set $redis_pass "nightmaremoon"; ... } ... }
  • 11. Init local red = redis:new() local ok, err = red:connect(ngx.var.redis_host, ngx.var.redis_port) if not ok then ngx.say("failed to connect: ", err) return end local ok, err = red:auth(ngx.var.redis_pass) if not ok then ngx.say("failed to auth: ", err) return end
  • 12. GET /scores local keys, err = red:keys("*") local scores = {} for i, key in ipairs(keys) do scores[key] = red:get(key) end ngx.header.content_type = "text/plain" ngx.say(json.encode(scores))
  • 13. GET /score/<userid> location ~* ^/keys/(?<key>.*)$ { content_by_lua ' -- ... (connect and auth) local val, err = red:get("user:score:" .. ngx.var.key) ngx.say(json.encode({ value = val })) '; }
  • 14. DELETE /scores/<userid> local method = ngx.req.get_method() if method == "GET" then ... elseif method == "PUT" then ... elseif method == "DELETE" then red:delete("user:score:" .. ngx.var.key) ngx.say(json.encode({result = "success"})) end
  • 15. PUT /scores/<userid> data = json.decode(ngx.req.get_body_data()) red:set("user:score:" .. ngx.var.key, data.value) ngx.req.set_method(ngx.HTTP_GET) ngx.exec("/scores/" .. ngx.var.key)
  • 16. GET /scores/max local max = 0 local keys = redis.call('keys', 'user:score:*'); for i, key in ipairs(keys) do local value = tonumber(redis.call('get', key)); if value > max then max = value end end return max
  • 17. GET /scores/max local sha, err = red:script("load","...") local val, err = red:evalsha(sha, 0) ngx.say(json.encode({ max = val }))
  • 18. GET /scores/max/<id1>,...,<idN> local max = 0 for key in string.gmatch(ngx.var.key, '([^,]+)') do local res = ngx.location.capture("/scores/" .. key) data = json.decode(res.body) if tonumber(data.value) > max then max = tonumber(data.value) end end ngx.say(json.encode({ max = max }))
  • 19. What to read • https://gist.github.com/isage/509d99cf4 def36014f5c • http://wiki.nginx.org/HttpLuaModule • http://openresty.org • search github for lua-resty*