How To Install OpenResty on Ubuntu 24.04 LTS
OpenResty has emerged as a powerful platform for building high-performance web applications by extending NGINX with Lua capabilities. If you’re running Ubuntu 24.04 LTS (Noble Numbat) and need to harness the power of OpenResty for your web projects, this comprehensive guide will walk you through the installation process step by step. Whether you’re a systems administrator, developer, or DevOps professional, you’ll find detailed instructions to get OpenResty up and running smoothly on your Ubuntu system.
Understanding OpenResty
OpenResty is not simply another web server – it’s a full-fledged platform that bundles the standard NGINX core with various Lua-based modules. This powerful combination allows you to embed Lua scripts directly into NGINX configuration files, enabling dynamic, high-performance web applications without sacrificing the speed and efficiency that NGINX is known for.
Unlike standard NGINX, OpenResty focuses on extending functionality through Lua modules rather than C modules. This architectural difference makes OpenResty exceptionally flexible for developing sophisticated web applications. The platform includes LuaJIT, a Just-In-Time compiler for Lua that dramatically improves performance compared to standard Lua interpreters.
The key benefits of OpenResty include:
- Exceptional performance with minimal resource consumption
- Non-blocking, asynchronous processing capabilities
- Direct database connections without external proxies
- Easily extensible through Lua modules
- Built-in caching mechanisms for optimal speed
OpenResty excels in scenarios requiring high concurrency, such as API gateways, content delivery networks, web application firewalls, and microservices architectures. Many high-traffic websites and services rely on OpenResty to handle millions of requests per second with minimal latency.
Prerequisites
Before diving into the OpenResty installation process, ensure your system meets all necessary requirements. Ubuntu 24.04 LTS provides an excellent foundation for OpenResty, but you’ll need to prepare your environment properly.
First, you must have sudo or root access to your Ubuntu system. Without administrative privileges, you won’t be able to install packages or modify system configurations. Additionally, verify that your system has at least 512MB of RAM and 1GB of free disk space, though more is recommended for production environments.
Update your system packages to ensure compatibility and security:
sudo apt update
sudo apt upgrade -y
Check if any web servers like Apache or NGINX are already running on your system, as they might conflict with OpenResty by occupying the same ports:
sudo systemctl status apache2
sudo systemctl status nginx
If any existing web servers are running, either stop them or note that you’ll need to configure OpenResty to use different ports.
Finally, create a backup of any existing web server configurations if you plan to migrate from another platform to OpenResty.
Preparing Your Ubuntu 24.04 Environment
Before installing OpenResty, take a few moments to properly prepare your Ubuntu 24.04 system. First, verify your Ubuntu version to ensure compatibility:
lsb_release -a
Ensure your system clock is synchronized to prevent issues with package verification:
sudo apt install ntpdate -y
sudo ntpdate time.nist.gov
Next, install essential packages required for the installation process:
sudo apt install wget gnupg ca-certificates apt-transport-https software-properties-common -y
If you have other web servers running that might conflict with OpenResty, consider disabling them:
# If using Apache
sudo systemctl stop apache2
sudo systemctl disable apache2
# If using standard NGINX
sudo systemctl stop nginx
sudo systemctl disable nginx
Check your available disk space to ensure you have sufficient room for the installation:
df -h /
For production environments or systems with multiple services, consider creating a dedicated user for OpenResty operations:
sudo useradd -r -s /bin/false openresty
This dedicated user will improve security by limiting the permissions of the OpenResty processes.
Method 1: Installing OpenResty via APT Repository
The most straightforward way to install OpenResty on Ubuntu 24.04 is through the official APT repository. This method ensures you receive updates and security patches directly from the OpenResty team.
First, import the GPG key used to sign the packages:
wget -O - https://openresty.org/package/pubkey.gpg | sudo apt-key add -
You might receive a deprecation warning about apt-key, which is expected on newer Ubuntu versions. Next, add the OpenResty repository to your system:
echo "deb http://openresty.org/package/ubuntu jammy main" | sudo tee /etc/apt/sources.list.d/openresty.list
Note that at the time of writing, Ubuntu 24.04-specific repositories might not yet be available, so we’re using the “jammy” (22.04) repository, which is compatible with 24.04 in most cases.
Update your package lists to include the new repository:
sudo apt update
Now, install OpenResty and its recommended packages:
sudo apt install openresty -y
The installation process will automatically handle dependencies, including required libraries like libpcre
, libssl
, and zlib
.
Verify your installation by checking the OpenResty version:
openresty -v
You should see output indicating the OpenResty version along with the NGINX version it’s based on. If you encounter errors specific to Ubuntu 24.04, they might relate to library version differences between Ubuntu 22.04 and 24.04. In most cases, these can be resolved by installing specific library versions or proceeding with the source installation method.
Method 2: Building OpenResty from Source
While the repository installation is sufficient for most users, building from source offers greater flexibility and control over the compilation options. This approach is particularly valuable when you need specific optimizations or custom modules.
Begin by installing the required build dependencies:
sudo apt install build-essential libpcre3-dev libssl-dev perl make cmake unzip -y
Download the latest OpenResty source code from the official website:
wget https://openresty.org/download/openresty-1.21.4.1.tar.gz
Note: Replace the version number with the latest available version at the time of installation.
Extract the downloaded archive:
tar -xvf openresty-1.21.4.1.tar.gz
cd openresty-1.21.4.1
Configure the build with options tailored to your needs. A standard configuration with common modules might look like this:
./configure \
--prefix=/usr/local/openresty \
--with-luajit \
--with-http_ssl_module \
--with-http_realip_module \
--with-http_stub_status_module \
--with-http_gzip_static_module
For production environments, you might want to add more modules or optimization flags based on your specific requirements.
Compile OpenResty using multiple processor cores to speed up the build process:
make -j$(nproc)
Install the compiled binaries:
sudo make install
Add OpenResty to your system path for easier access:
echo 'export PATH=/usr/local/openresty/bin:/usr/local/openresty/nginx/sbin:$PATH' | sudo tee /etc/profile.d/openresty.sh
source /etc/profile.d/openresty.sh
Verify the installation:
openresty -v
The source installation gives you complete control over which modules are included and allows you to apply specific optimization flags tailored to your hardware and use case.
Basic Configuration of OpenResty
After successful installation, you’ll need to understand and configure OpenResty to suit your needs. The configuration structure follows NGINX conventions but with additional Lua-specific directives.
The main configuration files are located in:
/usr/local/openresty/nginx/conf/
(for source installation)/etc/openresty/
(for repository installation)
The primary configuration file is nginx.conf
, which includes global settings and can include other configuration files. OpenResty enhances the standard NGINX configuration with Lua-specific directives like lua_package_path
and lua_code_cache
.
Here’s a minimal configuration example:
worker_processes auto;
error_log logs/error.log;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
lua_package_path "/usr/local/openresty/lualib/?.lua;;";
lua_package_cpath "/usr/local/openresty/lualib/?.so;;";
server {
listen 80;
server_name localhost;
location / {
default_type text/html;
content_by_lua_block {
ngx.say("<h1>Hello from OpenResty on Ubuntu 24.04!</h1>")
}
}
}
}
After making changes to the configuration, always test the syntax before reloading:
openresty -t
If the test passes, reload the configuration:
sudo systemctl reload openresty
Setting Up OpenResty as a Service
To ensure OpenResty starts automatically when your system boots, set it up as a systemd service. If you installed from the repository, this is typically done automatically. For source installations, create a custom service file:
sudo nano /etc/systemd/system/openresty.service
Add the following content:
[Unit]
Description=OpenResty - Enhanced NGINX with Lua
After=network.target
[Service]
Type=forking
PIDFile=/usr/local/openresty/nginx/logs/nginx.pid
ExecStartPre=/usr/local/openresty/nginx/sbin/nginx -t
ExecStart=/usr/local/openresty/nginx/sbin/nginx
ExecReload=/usr/local/openresty/nginx/sbin/nginx -s reload
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target
Enable and start the service:
sudo systemctl daemon-reload
sudo systemctl enable openresty
sudo systemctl start openresty
Verify that the service is running correctly:
sudo systemctl status openresty
You can now use standard systemd commands to manage the OpenResty service:
sudo systemctl start openresty # Start the service
sudo systemctl stop openresty # Stop the service
sudo systemctl restart openresty # Restart the service
sudo systemctl reload openresty # Reload configuration
Configuring Firewall Rules
If you’re using Ubuntu’s default firewall (UFW), you’ll need to allow HTTP and HTTPS traffic to reach your OpenResty server:
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
If you’ve configured OpenResty to use non-standard ports, adjust these commands accordingly. To apply the changes and check the status:
sudo ufw reload
sudo ufw status
For more restrictive environments, consider limiting access to only specific IP addresses:
sudo ufw allow from 192.168.1.0/24 to any port 80
sudo ufw allow from 192.168.1.0/24 to any port 443
Always ensure that SSH access remains open to prevent locking yourself out of the server:
sudo ufw allow 22/tcp
Creating Your First OpenResty Application
Let’s create a simple “Hello World” application to verify that OpenResty is working correctly with Lua. Create a new directory for your application:
sudo mkdir -p /usr/local/openresty/nginx/lua
Create a simple Lua script:
sudo nano /usr/local/openresty/nginx/lua/hello.lua
Add the following Lua code:
local _M = {}
function _M.say_hello()
ngx.header.content_type = "text/html"
ngx.say("<h1>Hello from OpenResty!</h1>")
ngx.say("<p>Lua is running within NGINX on Ubuntu 24.04</p>")
ngx.say("<p>Current time: ", os.date(), "</p>")
end
return _M
Now update your NGINX configuration to use this Lua module:
sudo nano /usr/local/openresty/nginx/conf/nginx.conf
Add a new location block within your server block:
location /hello {
content_by_lua_block {
local hello = require "hello"
hello.say_hello()
}
}
Test the configuration and reload:
sudo openresty -t
sudo systemctl reload openresty
Access your application by visiting http://your_server_ip/hello
in your web browser. You should see the greeting message along with the current time, confirming that OpenResty is correctly executing Lua code.
Advanced Configuration Options
Fine-tuning OpenResty can significantly impact performance and resource utilization. Here are key areas to consider:
Worker Processes and Connections
Adjust the number of worker processes based on your CPU cores:
worker_processes auto; # or set a specific number
worker_rlimit_nofile 65535;
events {
worker_connections 10240;
use epoll;
multi_accept on;
}
Buffer and Timeout Settings
Optimize buffer sizes and timeouts based on your traffic patterns:
http {
client_body_buffer_size 128k;
client_max_body_size 10m;
client_body_timeout 12;
client_header_timeout 12;
keepalive_timeout 15;
send_timeout 10;
}
Lua Module Configuration
Configure Lua-specific settings for optimal performance:
lua_code_cache on; # Disable during development, enable in production
lua_package_path "/path/to/lua/lib/?.lua;;";
lua_package_cpath "/path/to/lua/lib/?.so;;";
lua_shared_dict my_cache 10m; # Shared memory between workers
FastCGI and Proxy Settings
If you’re integrating with PHP or proxying to backend services:
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}
location /api/ {
proxy_pass http://backend_servers;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
Caching Configuration
Implement caching for improved performance:
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m inactive=60m;
proxy_cache_key "$scheme$request_method$host$request_uri";
location / {
proxy_cache my_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
}
Performance Optimization
For high-traffic environments, performance optimization becomes crucial. Start by tuning the worker processes to match your CPU resources:
worker_processes auto; # Automatically sets to number of CPU cores
worker_cpu_affinity auto;
Adjust the number of open file descriptors to handle high concurrency:
sudo nano /etc/security/limits.conf
Add these lines:
openresty soft nofile 65535
openresty hard nofile 65535
Enable TCP optimization in your NGINX configuration:
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
}
Implement HTTP/2 for improved performance with modern browsers:
server {
listen 443 ssl http2;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
}
Monitor OpenResty’s performance using the stub status module:
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
This information can be collected by monitoring tools like Prometheus with NGINX exporter to track metrics over time.
Securing Your OpenResty Installation
Security should be a priority for any web server deployment. Start by implementing SSL/TLS encryption:
sudo apt install certbot -y
sudo certbot certonly --standalone -d yourdomain.com
Configure OpenResty to use the certificates:
server {
listen 443 ssl http2;
server_name yourdomain.com;
ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384';
ssl_session_cache shared:SSL:10m;
# Redirect HTTP to HTTPS
listen 80;
return 301 https://$host$request_uri;
}
Implement security headers to protect against common web vulnerabilities:
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
add_header X-XSS-Protection "1; mode=block";
add_header Content-Security-Policy "default-src 'self'";
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
Restrict access to sensitive directories and files:
location ~ /\.ht {
deny all;
}
location ~ /\.git {
deny all;
}
Implement rate limiting to protect against brute force attacks:
http {
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
server {
location /login {
limit_req zone=one burst=5;
}
}
}
Troubleshooting Common Issues
When working with OpenResty on Ubuntu 24.04, you might encounter various issues. Here are solutions for common problems:
Permission Errors
If you see “Permission denied” errors in logs:
sudo chown -R openresty:openresty /usr/local/openresty/nginx/logs/
sudo chmod 755 /usr/local/openresty/nginx/logs/
Configuration Syntax Errors
If OpenResty fails to start due to configuration errors:
openresty -t -c /path/to/nginx.conf
This command provides detailed information about the syntax error and its location.
Lua Module Not Found
When Lua modules cannot be located:
lua_package_path "/usr/local/openresty/lualib/?.lua;/path/to/custom/lua/?.lua;;";
lua_package_cpath "/usr/local/openresty/lualib/?.so;/path/to/custom/lua/?.so;;";
Ensure the paths point to the correct locations of your Lua modules.
Log Analysis
Check error logs for troubleshooting:
tail -f /usr/local/openresty/nginx/logs/error.log
Debugging Lua Scripts
For Lua script debugging, disable code cache during development:
lua_code_cache off; # Remember to enable in production
Add debug output in your Lua code:
ngx.log(ngx.ERR, "Debug: variable value is ", some_variable)
Integrating with Other Services
OpenResty can be integrated with various services to create a complete application stack.
Database Connection
Connect to MySQL using Lua:
local mysql = require "resty.mysql"
local db, err = mysql:new()
if not db then
ngx.log(ngx.ERR, "Failed to instantiate mysql: ", err)
return
end
db:set_timeout(1000)
local ok, err, errcode, sqlstate = db:connect{
host = "127.0.0.1",
port = 3306,
database = "mydb",
user = "user",
password = "password"
}
Redis Integration
Implement Redis caching:
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000)
local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
ngx.say("Failed to connect to Redis: ", err)
return
end
local res, err = red:get("some_key")
Load Balancing
Configure load balancing across multiple backend servers:
upstream backend {
server backend1.example.com weight=5;
server backend2.example.com;
server backend3.example.com backup;
}
server {
location / {
proxy_pass http://backend;
}
}
Maintenance and Updates
Regular maintenance ensures your OpenResty installation remains secure and performant.
Keep OpenResty updated with the latest security patches:
# For repository installation
sudo apt update
sudo apt upgrade openresty -y
# For source installation
# Download new source, compile and replace
Back up your configuration before major changes:
sudo cp -r /usr/local/openresty/nginx/conf /usr/local/openresty/nginx/conf.bak
Implement log rotation to manage disk space:
sudo nano /etc/logrotate.d/openresty
Add these lines:
/usr/local/openresty/nginx/logs/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 0640 openresty openresty
sharedscripts
postrotate
[ -s /usr/local/openresty/nginx/logs/nginx.pid ] && kill -USR1 `cat /usr/local/openresty/nginx/logs/nginx.pid`
endscript
}
Congratulations! You have successfully installed OpenResty. Thanks for using this tutorial for installing OpenResty on the Ubuntu 24.04 LTS system. For additional help or useful information, we recommend you check the official OpenResty website.