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

What's hot (20)

PPT
{{more}} Kibana4
琛琳 饶
 
PDF
Nodejs a-practical-introduction-oredev
Felix Geisendörfer
 
PPT
ELK stack at weibo.com
琛琳 饶
 
PDF
Redis - Usability and Use Cases
Fabrizio Farinacci
 
PDF
Functional Operations (Functional Programming at Comcast Labs Connect)
Susan Potter
 
PDF
Node.js - A Quick Tour II
Felix Geisendörfer
 
PDF
Introduction to redis - version 2
Dvir Volk
 
ODP
Using Logstash, elasticsearch & kibana
Alejandro E Brito Monedero
 
PDF
From zero to hero - Easy log centralization with Logstash and Elasticsearch
Rafał Kuć
 
PDF
Openstack at NTT Feb 7, 2011
Open Stack
 
PDF
Everything as Code with Terraform
Mitchell Pronschinske
 
PDF
Dirty - How simple is your database?
Felix Geisendörfer
 
PDF
Paris Redis Meetup Introduction
Gregory Boissinot
 
PDF
并发模型介绍
qiang
 
PDF
Redis modules 101
Dvir Volk
 
PDF
Redis
Socialmetrix
 
PDF
tdc2012
Juan Lopes
 
PDF
Redis — The AK-47 of Post-relational Databases
Karel Minarik
 
PDF
Object Storage with Gluster
Gluster.org
 
PDF
Ground Control to Nomad Job Dispatch
Michael Lange
 
{{more}} Kibana4
琛琳 饶
 
Nodejs a-practical-introduction-oredev
Felix Geisendörfer
 
ELK stack at weibo.com
琛琳 饶
 
Redis - Usability and Use Cases
Fabrizio Farinacci
 
Functional Operations (Functional Programming at Comcast Labs Connect)
Susan Potter
 
Node.js - A Quick Tour II
Felix Geisendörfer
 
Introduction to redis - version 2
Dvir Volk
 
Using Logstash, elasticsearch & kibana
Alejandro E Brito Monedero
 
From zero to hero - Easy log centralization with Logstash and Elasticsearch
Rafał Kuć
 
Openstack at NTT Feb 7, 2011
Open Stack
 
Everything as Code with Terraform
Mitchell Pronschinske
 
Dirty - How simple is your database?
Felix Geisendörfer
 
Paris Redis Meetup Introduction
Gregory Boissinot
 
并发模型介绍
qiang
 
Redis modules 101
Dvir Volk
 
tdc2012
Juan Lopes
 
Redis — The AK-47 of Post-relational Databases
Karel Minarik
 
Object Storage with Gluster
Gluster.org
 
Ground Control to Nomad Job Dispatch
Michael Lange
 

Viewers also liked (20)

PDF
Nginx Scripting - Extending Nginx Functionalities with Lua
Tony Fabeen
 
PDF
Socket programming, and openresty
Tavish Naruka
 
PDF
Nginx+lua在阿里巴巴的使用
OpenRestyCon
 
PDF
Hacking Nginx at Taobao
Joshua Zhu
 
PDF
Lua tech talk
Locaweb
 
PDF
Lua as a business logic language in high load application
Ilya Martynov
 
PDF
Using ngx_lua in UPYUN
Cong Zhang
 
PPTX
Script up your application with Lua! -- RyanE -- OpenWest 2014
ryanerickson
 
PDF
Nginx lua
Moriyoshi Koizumi
 
KEY
淺入淺出 GDB
Jim Chang
 
PDF
Gdb tutorial-handout
Suraj Kumar
 
PDF
Las16 309 - lua jit arm64 port - status
Linaro
 
PDF
Learn C Programming Language by Using GDB
National Cheng Kung University
 
PPT
Perl在nginx里的应用
琛琳 饶
 
PDF
基于OpenResty的百万级长连接推送
OpenRestyCon
 
PDF
The basics and design of lua table
Shuai Yuan
 
PPT
高性能Web服务器Nginx及相关新技术的应用实践
rewinx
 
PDF
Devinsampa nginx-scripting
Tony Fabeen
 
PDF
LAS16-400K2: TianoCore – Open Source UEFI Community Update
Linaro
 
PDF
OAuth and OpenID Connect for Microservices
Twobo Technologies
 
Nginx Scripting - Extending Nginx Functionalities with Lua
Tony Fabeen
 
Socket programming, and openresty
Tavish Naruka
 
Nginx+lua在阿里巴巴的使用
OpenRestyCon
 
Hacking Nginx at Taobao
Joshua Zhu
 
Lua tech talk
Locaweb
 
Lua as a business logic language in high load application
Ilya Martynov
 
Using ngx_lua in UPYUN
Cong Zhang
 
Script up your application with Lua! -- RyanE -- OpenWest 2014
ryanerickson
 
淺入淺出 GDB
Jim Chang
 
Gdb tutorial-handout
Suraj Kumar
 
Las16 309 - lua jit arm64 port - status
Linaro
 
Learn C Programming Language by Using GDB
National Cheng Kung University
 
Perl在nginx里的应用
琛琳 饶
 
基于OpenResty的百万级长连接推送
OpenRestyCon
 
The basics and design of lua table
Shuai Yuan
 
高性能Web服务器Nginx及相关新技术的应用实践
rewinx
 
Devinsampa nginx-scripting
Tony Fabeen
 
LAS16-400K2: TianoCore – Open Source UEFI Community Update
Linaro
 
OAuth and OpenID Connect for Microservices
Twobo Technologies
 
Ad

Similar to Nginx-lua (20)

PDF
JDD 2017: Nginx + Lua = OpenResty (Marcin Stożek)
PROIDEA
 
PDF
Developing a user-friendly OpenResty application
Thibault Charbonnier
 
PDF
Using ngx_lua in UPYUN 2
Cong Zhang
 
PDF
Developing OpenResty Framework
Aapo Talvensaari
 
PDF
Using ngx_lua in upyun 2
OpenRestyCon
 
ODP
Introduction to Lua Luajit Openresty Luvit
Lionel Duboeuf
 
PPTX
Implementing a Fileserver with Nginx and Lua
Andrii Gakhov
 
PPTX
Inside Sqale's Backend at RubyConf Taiwan 2012
Gosuke Miyashita
 
PDF
Fun with Ruby and Redis
javier ramirez
 
PDF
Developing OpenResty Framework
OpenRestyCon
 
PDF
Redis 101
Geoff Hoffman
 
PPTX
Session: A Reference Architecture for Running Modern APIs with NGINX Unit and...
NGINX, Inc.
 
PPT
Python redis talk
Josiah Carlson
 
PPTX
Inside Sqale's Backend at Sapporo Ruby Kaigi 2012
Gosuke Miyashita
 
PDF
Alternative Infrastucture
Marc Seeger
 
PPTX
Inside Sqale's Backend at YAPC::Asia Tokyo 2012
Gosuke Miyashita
 
PDF
Paris container day june17
Paris Container Day
 
PDF
A Tale of a Server Architecture (Frozen Rails 2012)
Flowdock
 
KEY
Redis, Resque & Friends
Christopher Spring
 
PDF
What is few?
Shota Fukumori
 
JDD 2017: Nginx + Lua = OpenResty (Marcin Stożek)
PROIDEA
 
Developing a user-friendly OpenResty application
Thibault Charbonnier
 
Using ngx_lua in UPYUN 2
Cong Zhang
 
Developing OpenResty Framework
Aapo Talvensaari
 
Using ngx_lua in upyun 2
OpenRestyCon
 
Introduction to Lua Luajit Openresty Luvit
Lionel Duboeuf
 
Implementing a Fileserver with Nginx and Lua
Andrii Gakhov
 
Inside Sqale's Backend at RubyConf Taiwan 2012
Gosuke Miyashita
 
Fun with Ruby and Redis
javier ramirez
 
Developing OpenResty Framework
OpenRestyCon
 
Redis 101
Geoff Hoffman
 
Session: A Reference Architecture for Running Modern APIs with NGINX Unit and...
NGINX, Inc.
 
Python redis talk
Josiah Carlson
 
Inside Sqale's Backend at Sapporo Ruby Kaigi 2012
Gosuke Miyashita
 
Alternative Infrastucture
Marc Seeger
 
Inside Sqale's Backend at YAPC::Asia Tokyo 2012
Gosuke Miyashita
 
Paris container day june17
Paris Container Day
 
A Tale of a Server Architecture (Frozen Rails 2012)
Flowdock
 
Redis, Resque & Friends
Christopher Spring
 
What is few?
Shota Fukumori
 
Ad

Recently uploaded (20)

PPTX
ETP Presentation(1000m3 Small ETP For Power Plant and industry
MD Azharul Islam
 
PPTX
Precedence and Associativity in C prog. language
Mahendra Dheer
 
PDF
勉強会資料_An Image is Worth More Than 16x16 Patches
NABLAS株式会社
 
PPTX
Sensor IC System Design Using COMSOL Multiphysics 2025-July.pptx
James D.B. Wang, PhD
 
PPT
IISM Presentation.ppt Construction safety
lovingrkn
 
PPTX
Inventory management chapter in automation and robotics.
atisht0104
 
PDF
Machine Learning All topics Covers In This Single Slides
AmritTiwari19
 
PDF
STUDY OF NOVEL CHANNEL MATERIALS USING III-V COMPOUNDS WITH VARIOUS GATE DIEL...
ijoejnl
 
PDF
20ME702-Mechatronics-UNIT-1,UNIT-2,UNIT-3,UNIT-4,UNIT-5, 2025-2026
Mohanumar S
 
PPTX
Basics of Auto Computer Aided Drafting .pptx
Krunal Thanki
 
PDF
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
PPTX
Introduction to Fluid and Thermal Engineering
Avesahemad Husainy
 
PPTX
22PCOAM21 Session 1 Data Management.pptx
Guru Nanak Technical Institutions
 
PPTX
quantum computing transition from classical mechanics.pptx
gvlbcy
 
PDF
Biodegradable Plastics: Innovations and Market Potential (www.kiu.ac.ug)
publication11
 
PDF
Construction of a Thermal Vacuum Chamber for Environment Test of Triple CubeS...
2208441
 
PDF
CAD-CAM U-1 Combined Notes_57761226_2025_04_22_14_40.pdf
shailendrapratap2002
 
PPTX
IoT_Smart_Agriculture_Presentations.pptx
poojakumari696707
 
PDF
Natural_Language_processing_Unit_I_notes.pdf
sanguleumeshit
 
PDF
All chapters of Strength of materials.ppt
girmabiniyam1234
 
ETP Presentation(1000m3 Small ETP For Power Plant and industry
MD Azharul Islam
 
Precedence and Associativity in C prog. language
Mahendra Dheer
 
勉強会資料_An Image is Worth More Than 16x16 Patches
NABLAS株式会社
 
Sensor IC System Design Using COMSOL Multiphysics 2025-July.pptx
James D.B. Wang, PhD
 
IISM Presentation.ppt Construction safety
lovingrkn
 
Inventory management chapter in automation and robotics.
atisht0104
 
Machine Learning All topics Covers In This Single Slides
AmritTiwari19
 
STUDY OF NOVEL CHANNEL MATERIALS USING III-V COMPOUNDS WITH VARIOUS GATE DIEL...
ijoejnl
 
20ME702-Mechatronics-UNIT-1,UNIT-2,UNIT-3,UNIT-4,UNIT-5, 2025-2026
Mohanumar S
 
Basics of Auto Computer Aided Drafting .pptx
Krunal Thanki
 
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
Introduction to Fluid and Thermal Engineering
Avesahemad Husainy
 
22PCOAM21 Session 1 Data Management.pptx
Guru Nanak Technical Institutions
 
quantum computing transition from classical mechanics.pptx
gvlbcy
 
Biodegradable Plastics: Innovations and Market Potential (www.kiu.ac.ug)
publication11
 
Construction of a Thermal Vacuum Chamber for Environment Test of Triple CubeS...
2208441
 
CAD-CAM U-1 Combined Notes_57761226_2025_04_22_14_40.pdf
shailendrapratap2002
 
IoT_Smart_Agriculture_Presentations.pptx
poojakumari696707
 
Natural_Language_processing_Unit_I_notes.pdf
sanguleumeshit
 
All chapters of Strength of materials.ppt
girmabiniyam1234
 

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*