Backend Development 23 min read

Using Nginx + Lua (ngx_lua) for High‑Performance Web Applications

This article introduces the advantages of Nginx and Lua, explains the ngx_lua module and OpenResty ecosystem, describes common architectural patterns such as load balancing and caching, and provides a step‑by‑step guide to building, configuring, and deploying a Lua‑based web application on Nginx.

Architecture Digest
Architecture Digest
Architecture Digest
Using Nginx + Lua (ngx_lua) for High‑Performance Web Applications

Almost every Internet company treats Nginx as a standard component for load balancing, reverse proxy, caching, and rate limiting, but using it as a full‑featured web container is less common. Nginx’s high performance is well known, yet developing native modules in C/C++ is costly, which is why the community created nginxScript and, more maturely, the ngx_lua module that embeds Lua into Nginx. OpenResty bundles Nginx, LuaJIT, ngx_lua, and useful Lua libraries, allowing developers to write web services in Lua without touching C.

1. ngx_lua Overview

Nginx runs a master process with multiple worker processes, each handling many connections via non‑blocking I/O, resulting in low memory usage and high concurrency. Lua is a lightweight, embeddable scripting language offering coroutines, closures, and garbage collection, making it easy to embed a Lua VM in each request.

ngx_lua embeds Lua into Nginx, exposing a rich set of APIs that resemble servlet handling: receive request, parse parameters, process logic, and send a response. Developers only need to learn these APIs to build web applications.

2. Development Environment

OpenResty provides a ready‑to‑use environment. Installing OpenResty gives you Nginx, LuaJIT, ngx_lua, and many third‑party modules, so you can start writing Lua scripts and deploy them directly on Nginx.

Typical OpenResty modules include lua‑resty‑memcached , lua‑resty‑mysql , lua‑resty‑redis , lua‑resty‑dns , lua‑resty‑limit‑traffic , and lua‑resty‑template , covering caching, database access, rate limiting, and template rendering.

3. Common Architecture Patterns

• Load Balancing : Use LVS+HAProxy to distribute traffic to core Nginx nodes, then route to business‑specific Nginx instances. Core Nginx handles stateless functions like grouping, caching, header filtering, failover, and rate limiting, while business Nginx performs content compression, A/B testing, and degradation.

• Single‑Machine Closed Loop : For simple use‑cases (e.g., cookie whitelist), all data resides on the same server, eliminating network hops.

• Distributed Closed Loop : Combine local cache, distributed cache (Redis/JIMDB), and fallback to backend services (Tomcat, DB) to ensure consistency and scalability.

• Access Gateway : Core Nginx performs dynamic load balancing, DDoS protection, request filtering, aggregation, header stripping, and proxy caching. Business Nginx adds fine‑grained rate limiting, degradation strategies, A/B testing, and QoS monitoring.

4. Building a Web Application with Nginx + Lua

4.1 Project Structure

/export/App/nginx-app
├─ bin/               # start.sh, stop.sh
├─ config/            # nginx.conf, domain/*.conf, resources.properties
├─ lua/               # init.lua, product_controller.lua
├─ template/          # product.html
└─ lualib/            # jd/*.lua, resty/*.lua

4.2 Start/Stop Scripts

# start.sh (pseudo‑code)
if nginx not running then
    sudo /export/servers/nginx/sbin/nginx -t -c /export/App/nginx-app/config/nginx.conf
    sudo /export/servers/nginx/sbin/nginx -c /export/App/nginx-app/config/nginx.conf
else
    sudo /export/servers/nginx/sbin/nginx -t
    sudo /export/servers/nginx/sbin/nginx -s reload
fi
# stop.sh
sudo /export/servers/nginx/sbin/nginx -s quit

4.3 Configuration Files

# nginx.conf (excerpt)
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  text/html;
    lua_package_path  "/export/App/nginx-app/lualib/?.lua;;";
    lua_package_cpath "/export/App/nginx-app/lualib/?.so;;";
    include /export/App/nginx-app/config/domains/*;
    init_by_lua_file "/export/App/nginx-app/lua/init.lua";
}

Domain‑specific config (nginx_product.conf) defines upstream servers, shared dictionaries, and location blocks that invoke Lua scripts, e.g.:

# nginx_product.conf (excerpt)
upstream item_http_upstream {
    server 192.168.1.1 max_fails=2 fail_timeout=30s weight=5;
    server 192.168.1.2 max_fails=2 fail_timeout=30s weight=5;
}
lua_shared_dict item_local_shop_cache 600m;
server {
    listen 80;
    server_name item.jd.com item.jd.hk;
    set $template_root "/export/App/nginx-app/template";
    location ~* "^/(\d{6,12})\.html$" {
        default_type text/html;
        charset gbk;
        lua_code_cache on;
        content_by_lua_file "/export/App/nginx-app/lua/product_controller.lua";
    }
}

4.4 Business Logic (Lua)

-- product_controller.lua (excerpt)
local template = require("resty.template")
local skuId = ngx.req.get_uri_args()["skuId"]
local data = api.getData(skuId)   -- call backend service
local func = template.compile("product.html")
local content = func(data)
ngx.say(content)

The controller fetches request parameters, calls backend services, renders a template, and returns the result.

5. Common Functions Summary

Dynamic load balancing

Firewall (DDOS, IP/URL/User‑Agent blacklists)

Rate limiting

Degradation (active/passive)

A/B testing / gray release

Multi‑level caching

Server‑side request aggregation

Service quality monitoring

In conclusion, combining Nginx with Lua via ngx_lua (or OpenResty) provides a powerful, lightweight platform for building high‑performance web services, access gateways, API gateways, and auxiliary tools, especially when business logic is relatively simple and code size remains modest.

Backendload balancingcachingWeb DevelopmentNginxLuaOpenResty
Architecture Digest
Written by

Architecture Digest

Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.