DebianDebian Based

How To Install OpenResty on Debian 12

Install OpenResty on Debian 12

OpenResty has emerged as a powerful platform for building high-performance web applications and API gateways. By extending NGINX with Lua scripting capabilities, OpenResty provides developers with a flexible and efficient solution for handling web traffic. Debian 12, also known as Debian Bookworm, offers a stable and reliable foundation for deploying OpenResty in production environments. This comprehensive guide will walk you through the process of installing OpenResty on Debian 12, from preparation to advanced configuration and optimization.

What is OpenResty?

OpenResty is a full-fledged web platform that integrates NGINX, a high-performance web server, with LuaJIT, a just-in-time compiler for the Lua programming language. This integration allows developers to extend NGINX functionality using Lua scripts, transforming it from a simple web server into a versatile web application platform.

The project was created by Yichun Zhang (also known as agentzh) in 2007 and has since grown into a robust ecosystem of modules and tools. At its core, OpenResty consists of:

  • NGINX as the foundation web server
  • LuaJIT for scripting capabilities
  • Various Lua libraries and modules
  • Built-in support for non-blocking I/O operations

OpenResty excels in scenarios requiring high concurrency and low latency, making it ideal for content delivery networks, API gateways, web application firewalls, and microservices architectures. Unlike standard NGINX installations, OpenResty can handle complex application logic directly within the web server layer, eliminating the need for separate application servers in many cases.

Performance benchmarks consistently demonstrate OpenResty’s ability to handle tens of thousands of concurrent connections with minimal resource consumption, outperforming traditional web server setups by significant margins.

Prerequisites for Installation

Before beginning the OpenResty installation process on Debian 12, ensure that your system meets the following requirements:

  • A Debian 12 (Bookworm) system with at least 1GB RAM and 2GB disk space
  • Root access or sudo privileges
  • Basic familiarity with Linux command line operations
  • Internet connectivity for downloading packages
  • No critical production workloads running on the same system during installation

If you already have NGINX installed, you’ll need to handle this situation carefully as OpenResty includes its own NGINX component that may conflict with existing installations.

Additionally, verify that your system is up-to-date and that you have basic tools installed:

sudo apt update
sudo apt upgrade -y
sudo apt install -y curl wget gnupg2 ca-certificates lsb-release

It’s also recommended to check your firewall settings to ensure that HTTP (port 80) and HTTPS (port 443) traffic is allowed if you plan to serve web content.

Preparing Your Debian 12 System

Proper preparation is crucial for a smooth OpenResty installation experience. Follow these steps to prepare your Debian 12 system:

1. First, ensure your package database is current:

sudo apt update && sudo apt upgrade -y

2. If you have an existing NGINX installation, you should stop and disable it to prevent conflicts with OpenResty:

sudo systemctl disable nginx
sudo systemctl stop nginx

This step is essential as OpenResty includes its own NGINX component, and running both simultaneously will cause port conflicts and other issues.

3. Install required dependencies for the repository management:

sudo apt-get -y install --no-install-recommends wget gnupg ca-certificates

These packages are necessary for downloading and verifying the OpenResty repository information securely.

4. Create a backup of any important configuration files if you’re migrating from a standard NGINX setup:

sudo mkdir -p /backup/nginx
sudo cp -r /etc/nginx/* /backup/nginx/

This precaution ensures you don’t lose any custom configurations if you need to revert changes later.

5. Check for available disk space to ensure successful installation:

df -h

Make sure you have at least 500MB of free space for the installation process and additional space for logs and configurations.

Method 1: Installing OpenResty via APT Repository

Installing OpenResty through the official APT repository is the recommended method for Debian 12 systems. This approach ensures you receive security updates and can easily upgrade to newer versions in the future.

1. Import the OpenResty GPG key to verify package authenticity:

wget -O - https://openresty.org/package/pubkey.gpg | sudo apt-key add -

2. Add the OpenResty repository to your APT sources. The command differs depending on your system architecture.

  • For x86_64/amd64 systems:
codename=`grep -Po 'VERSION="[0-9]+ \(\K[^)]+' /etc/os-release`
echo "deb http://openresty.org/package/debian $codename openresty" | sudo tee /etc/apt/sources.list.d/openresty.list
  • For arm64/aarch64 systems:
codename=`grep -Po 'VERSION="[0-9]+ \(\K[^)]+' /etc/os-release`
echo "deb http://openresty.org/package/arm64/debian $codename openresty" | sudo tee /etc/apt/sources.list.d/openresty.list

3. Update the APT package index to include the newly added repository:

sudo apt update

4. Install OpenResty with a single command:

sudo apt -y install openresty

This command installs the main OpenResty package along with necessary dependencies.

5. Verify the installation by checking the OpenResty version:

openresty -v

You should see output indicating the OpenResty version and compile-time configurations.

6. For a more detailed verification, check:

openresty -V

This will display comprehensive information about the installed OpenResty version, including all enabled modules and compilation options.

Method 2: Building OpenResty from Source

While the APT repository method is convenient, building from source offers greater customization options and potentially better performance through architecture-specific optimizations.

1. Install build dependencies:

sudo apt install -y build-essential libpcre3-dev libssl-dev zlib1g-dev unzip git

2. Download the latest stable OpenResty source code:

cd /tmp
wget https://openresty.org/download/openresty-1.21.4.1.tar.gz
tar -xzf openresty-1.21.4.1.tar.gz
cd openresty-1.21.4.1

3. Configure the build with desired options:

./configure \
    --prefix=/usr/local/openresty \
    --with-luajit \
    --with-pcre-jit \
    --with-http_ssl_module \
    --with-http_realip_module \
    --with-http_stub_status_module \
    --with-http_v2_module

You can add or remove modules based on your specific requirements. The `–prefix` option specifies the installation directory.

4. Compile and install:

make -j$(nproc)
sudo make install

The `-j$(nproc)` option utilizes all available CPU cores to speed up compilation.

5. Create symbolic links for easier access:

sudo ln -sf /usr/local/openresty/bin/openresty /usr/local/bin/
sudo ln -sf /usr/local/openresty/bin/resty /usr/local/bin/

6. Verify the installation:

openresty -v

7. Clean up temporary files:

cd /tmp
rm -rf openresty-1.21.4.1*

Source compilation takes longer than using pre-built packages but gives you complete control over the included modules and optimization flags.

Post-Installation Configuration

After successfully installing OpenResty, proper configuration is essential for optimal performance and security.

1. Understand the OpenResty directory structure:

For APT installations:

  • Configuration files: `/etc/openresty/`
  • Main configuration file: `/etc/openresty/nginx.conf`
  • Log files: `/var/log/openresty/`
  • Web content: `/usr/local/openresty/nginx/html/`

For source installations:

  • Configuration files: `/usr/local/openresty/nginx/conf/`
  • Main configuration file: `/usr/local/openresty/nginx/conf/nginx.conf`
  • Log files: `/usr/local/openresty/nginx/logs/`
  • Web content: `/usr/local/openresty/nginx/html/`

2. Create a backup of the default configuration:

sudo cp /etc/openresty/nginx.conf /etc/openresty/nginx.conf.original

3. Set up proper file permissions:

sudo chown -R root:root /etc/openresty
sudo chmod -R 755 /etc/openresty
sudo chmod 644 /etc/openresty/nginx.conf

4. Update environment variables by adding the following to your `.bashrc` or `.zshrc` file:

export PATH=$PATH:/usr/local/openresty/bin:/usr/local/openresty/nginx/sbin

Apply the changes immediately:

source ~/.bashrc

5. Create a dedicated user for running OpenResty if you’re security-conscious:

sudo useradd -r -s /sbin/nologin nginx

Then update your configuration to use this user.

Starting and Managing the OpenResty Service

OpenResty can be managed through systemd on Debian 12, making it easy to control its lifecycle.

1. Start the OpenResty service:

sudo systemctl start openresty

2. Check the service status:

sudo systemctl status openresty

This command displays detailed information about the current state of the OpenResty service, including any error messages if the service failed to start.

3. Enable OpenResty to start automatically at boot:

sudo systemctl enable openresty

4. Common service management commands:

  • Stop OpenResty: `sudo systemctl stop openresty`
  • Restart OpenResty: `sudo systemctl restart openresty`
  • Reload configuration without downtime: `sudo systemctl reload openresty`

5. Check for errors in the log files if the service fails to start:

sudo tail -f /var/log/openresty/error.log

6. Test the configuration syntax before applying changes:

sudo openresty -t

This command validates your configuration files and reports any syntax errors without restarting the service.

7. If you encounter permission issues, check the service user and group:

grep "user" /etc/openresty/nginx.conf

The user specified here must have appropriate permissions to access the web content directories.

Basic OpenResty Configuration

Understanding and customizing the basic configuration will help you set up OpenResty for your specific needs.

1. The main configuration file structure:

# Main context
user nginx;
worker_processes auto;
error_log /var/log/openresty/error.log;
pid /run/openresty.pid;

# Events context
events {
    worker_connections 1024;
}

# HTTP context
http {
    include /etc/openresty/mime.types;
    default_type application/octet-stream;
    
    # Server context
    server {
        listen 80;
        server_name localhost;
        
        location / {
            root /usr/local/openresty/nginx/html;
            index index.html index.htm;
        }
        
        # Example Lua code integration
        location /hello {
            default_type text/plain;
            content_by_lua_block {
                ngx.say("Hello, OpenResty!")
            }
        }
    }
}

2. Create a simple virtual host:

server {
    listen 80;
    server_name example.com www.example.com;
    
    root /var/www/example.com;
    index index.html;
    
    location / {
        try_files $uri $uri/ =404;
    }
}

Save this to `/etc/openresty/conf.d/example.com.conf` and reload OpenResty.

3. Implement a basic Lua script:

Create a file `/etc/openresty/lua/hello.lua`:

return function()
    ngx.header.content_type = "text/plain"
    ngx.say("Hello from Lua script!")
    return ngx.exit(ngx.HTTP_OK)
end

Reference it in your configuration:

location /hello {
    content_by_lua_file /etc/openresty/lua/hello.lua;
}

4. Test your configuration:

sudo openresty -t && sudo systemctl reload openresty

5. Verify it works:

curl http://localhost/hello

This should return “Hello from Lua script!”

Advanced Configuration Options

OpenResty’s power lies in its advanced configuration capabilities, allowing fine-tuning for performance and functionality.

1. Optimize worker processes and connections:

worker_processes auto;
worker_rlimit_nofile 65535;

events {
    worker_connections 4096;
    multi_accept on;
    use epoll;
}

2. Configure buffer sizes for better performance:

http {
    client_body_buffer_size 10K;
    client_header_buffer_size 1k;
    client_max_body_size 8m;
    large_client_header_buffers 2 1k;
    
    client_body_timeout 12;
    client_header_timeout 12;
    keepalive_timeout 15;
    send_timeout 10;
}

3. Enable gzip compression:

http {
    gzip on;
    gzip_vary on;
    gzip_min_length 10240;
    gzip_proxied expired no-cache no-store private auth;
    gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml;
    gzip_disable "MSIE [1-6]\.";
}

4. Set up SSL/TLS for secure connections:

server {
    listen 443 ssl http2;
    server_name example.com;
    
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    ssl_session_timeout 1d;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    
    # HSTS (optional)
    add_header Strict-Transport-Security "max-age=63072000" always;
}

5. Implement a simple load balancer:

upstream backend {
    server backend1.example.com;
    server backend2.example.com;
    server backend3.example.com;
}

server {
    listen 80;
    server_name example.com;
    
    location / {
        proxy_pass http://backend;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

Testing Your OpenResty Installation

Thorough testing helps ensure your OpenResty installation is working correctly.

1. Verify the installation with a basic check:

openresty -v
openresty -V

2. Create a simple test application:

Create a file `/usr/local/openresty/nginx/html/test.html`:

<!DOCTYPE html>
<html>
<head>
    <title>OpenResty Test Page</title>
</head>
<body>
    <h1>OpenResty is working!</h1>
</body>
</html>

3. Check access to this page:

curl http://localhost/test.html

4. Test Lua functionality:

Create a new location in your configuration:

location /lua-test {
    default_type text/html;
    content_by_lua_block {
        ngx.say("<p>Lua is working! Current time: ", os.date(), "</p>")
    }
}

Reload OpenResty and check:

curl http://localhost/lua-test

5. Perform a basic load test:

sudo apt install -y apache2-utils
ab -n 1000 -c 100 http://localhost/

This command sends 1000 requests with 100 concurrent connections to test performance.

Common Issues and Troubleshooting

Even with careful installation, you may encounter some challenges. Here are solutions to common issues:

1. Issue: OpenResty fails to start
Solution: Check error logs and permissions:

sudo tail -f /var/log/openresty/error.log
sudo chmod -R 755 /var/log/openresty

2. Issue: “Address already in use” error
Solution: Find and stop the process using port 80/443:

sudo netstat -tulpn | grep :80
sudo kill -9 [PID]

3. Issue: GPG key import fails
Solution: Use an alternative method:

wget -O /tmp/pubkey.gpg https://openresty.org/package/pubkey.gpg
sudo apt-key add /tmp/pubkey.gpg

4. Issue: Lua script execution errors
Solution: Enable debug logging and check syntax:

location /debug {
    content_by_lua_block {
        ngx.log(ngx.ERR, "Debug info: ", debug.traceback())
        -- Your code here
    }
}

5. Issue: Configuration test fails
Solution: Fix syntax issues one by one:

sudo openresty -t

Address each error reported until the test passes.

6. Issue: Memory allocation errors
Solution: Increase worker connections or reduce buffer sizes:

worker_rlimit_nofile 65535;
events {
    worker_connections 2048;
}

Security Considerations

Security should be a priority for any web server installation:

1. Implement proper firewall rules:

sudo apt install -y ufw
sudo ufw allow OpenSSH
sudo ufw allow 'Nginx Full'
sudo ufw enable

2. Hide server information:

http {
    server_tokens off;
    more_set_headers "Server: ";
}

3. Implement rate limiting:

http {
    limit_req_zone $binary_remote_addr zone=mylimit:10m rate=10r/s;
    
    server {
        location / {
            limit_req zone=mylimit burst=20 nodelay;
        }
    }
}

4. Set up basic authentication:

sudo apt install -y apache2-utils
sudo htpasswd -c /etc/openresty/.htpasswd admin

Add to your configuration:

location /admin {
    auth_basic "Restricted Area";
    auth_basic_user_file /etc/openresty/.htpasswd;
}

5. Configure Content Security Policy:

add_header Content-Security-Policy "default-src 'self';" always;

6. Regularly update OpenResty:

sudo apt update
sudo apt upgrade openresty

Performance Optimization

Fine-tuning OpenResty can significantly improve performance:

1. Enable file system caching:

http {
    open_file_cache max=1000 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;
}

2. Optimize keepalive connections:

http {
    keepalive_timeout 65;
    keepalive_requests 100;
}

3. Configure microcaching for dynamic content:

proxy_cache_path /var/cache/openresty levels=1:2 keys_zone=microcache:10m max_size=1g inactive=60m;

server {
    location / {
        proxy_cache microcache;
        proxy_cache_valid 200 302 10s;
        proxy_cache_use_stale updating error timeout invalid_header http_500 http_502 http_503 http_504;
    }
}

4. Use the PageSpeed module:

Install and configure PageSpeed for automatic optimization of web assets:

pagespeed on;
pagespeed FileCachePath /var/cache/ngx_pagespeed;
pagespeed EnableFilters combine_css,combine_javascript,flatten_css_imports,lazyload_images;

5. Monitor performance:

sudo apt install -y prometheus-node-exporter

Add status monitoring:

location /status {
    stub_status on;
    allow 127.0.0.1;
    deny all;
}

Congratulations! You have successfully installed OpenResty. Thanks for using this tutorial for installing OpenResty on Debian 12 “Bookworm” system. For additional help or useful information, we recommend you check the official OpenResty website.

VPS Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “VPS Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is an experienced Linux enthusiast and technical writer with a passion for open-source software. With years of hands-on experience in various Linux distributions, r00t has developed a deep understanding of the Linux ecosystem and its powerful tools. He holds certifications in SCE and has contributed to several open-source projects. r00t is dedicated to sharing her knowledge and expertise through well-researched and informative articles, helping others navigate the world of Linux with confidence.
Back to top button