RHEL BasedRocky Linux

How To Install OpenResty on Rocky Linux 10

Install OpenResty on Rocky Linux 10

OpenResty transforms standard web server capabilities into a powerful, scriptable platform that handles enterprise-scale traffic with remarkable efficiency. This high-performance web platform, built on Nginx and LuaJIT, delivers exceptional speed while enabling dynamic content generation through Lua scripting. Rocky Linux 10, as a robust RHEL-compatible distribution, provides the perfect foundation for OpenResty deployments in production environments.

System administrators and developers choose OpenResty for its ability to handle thousands of concurrent connections while maintaining low memory usage. The platform’s unique architecture combines Nginx’s proven stability with Lua’s programming flexibility, creating opportunities for advanced web application development, API gateways, and reverse proxy configurations.

This comprehensive guide walks through every step of installing OpenResty on Rocky Linux 10, from initial system preparation to advanced configuration options. Whether you’re deploying a simple web server or building complex load-balancing solutions, this tutorial provides the foundation for successful OpenResty implementation.

Prerequisites and System Preparation

System Requirements

Rocky Linux 10 requires specific hardware specifications for optimal OpenResty performance. Your server should have at least 2GB of RAM, though 4GB or more is recommended for production workloads. CPU requirements are minimal, but multi-core processors significantly improve compilation speed and runtime performance.

Storage needs vary based on your intended use case. A basic installation requires approximately 500MB of disk space, while development environments with additional modules may need 2GB or more. Ensure adequate free space in the /usr/local directory where OpenResty installs by default.

Network connectivity is essential for downloading packages and dependencies. Your Rocky Linux 10 system must have internet access during installation, particularly for repository-based installations. Configure DNS resolution properly to avoid package download failures.

Initial System Setup

Begin by updating your Rocky Linux 10 system to ensure all packages are current. This prevents compatibility issues and security vulnerabilities that could affect the installation process.

sudo dnf update -y
sudo dnf install -y epel-release

Install essential development tools and libraries required for OpenResty compilation and operation. These packages provide the foundation for both repository and source-based installations.

sudo dnf groupinstall -y "Development Tools"
sudo dnf install -y wget curl gcc gcc-c++ pcre-devel openssl-devel zlib-devel make

The development tools group includes essential utilities like make, gcc, and various header files. PCRE development libraries enable regular expression functionality, while OpenSSL provides cryptographic capabilities for HTTPS connections.

Verify your system architecture matches OpenResty requirements. Rocky Linux 10 on x86_64 architecture offers the best compatibility and performance optimization.

uname -m
cat /etc/rocky-release

User Permissions and Security

Configure appropriate user permissions before proceeding with installation. OpenResty typically runs under a dedicated user account for security isolation, though installation requires root privileges.

Create a dedicated user for OpenResty processes if one doesn’t exist:

sudo useradd -r -s /sbin/nologin -d /var/cache/openresty openresty

Ensure your user account has sudo privileges for installation commands. Test sudo access before proceeding to avoid interruptions during the installation process.

sudo whoami

Stopping Conflicting Services

Identify and stop existing web servers that might conflict with OpenResty installation. Apache HTTP Server and standard Nginx installations commonly bind to ports 80 and 443, preventing OpenResty from starting properly.

Check for running web servers:

sudo systemctl status httpd
sudo systemctl status nginx
sudo netstat -tlnp | grep :80

Stop and disable conflicting services:

sudo systemctl stop httpd nginx
sudo systemctl disable httpd nginx

Remove existing Nginx packages if present to prevent configuration conflicts:

sudo dnf remove nginx nginx-*

Installation Method 1: Package Repository Installation

Adding OpenResty Repository

The official OpenResty repository provides pre-compiled packages optimized for various Linux distributions, including Rocky Linux 10. This method offers the quickest installation path with automatic dependency resolution.

Download the OpenResty repository configuration file:

wget https://openresty.org/package/rocky/openresty2.repo
sudo mv openresty2.repo /etc/yum.repos.d/openresty.repo

Import the GPG key to verify package authenticity:

sudo rpm --import https://openresty.org/package/pubkey.gpg

Update repository metadata to include OpenResty packages:

sudo dnf makecache

Verify repository configuration by listing available OpenResty packages:

dnf list available | grep openresty

Installing OpenResty Core Package

Install the main OpenResty package along with essential dependencies. The package manager automatically resolves and installs required libraries and components.

sudo dnf install -y openresty

The installation process creates the /usr/local/openresty directory structure containing binaries, configuration files, and documentation. This directory becomes the primary location for all OpenResty components and custom configurations.

Verify the installation directory structure:

ls -la /usr/local/openresty/
ls -la /usr/local/openresty/nginx/

The installation includes the core Nginx binary with embedded Lua interpreter, configuration templates, and essential modules for web server functionality.

Installing Additional OpenResty Tools

OpenResty provides supplementary tools that enhance development and management capabilities. These utilities streamline Lua script development and package management tasks.

Install the OpenResty command-line Lua interpreter:

sudo dnf install -y openresty-resty

Install the OpenResty Package Manager for third-party modules:

sudo dnf install -y openresty-opm

Install documentation utilities and help files:

sudo dnf install -y openresty-doc

These tools provide significant value for developers and administrators. The resty command enables Lua script testing without full server restarts, while opm simplifies module installation from the OpenResty package ecosystem.

Verifying Package Installation

Confirm successful installation by checking OpenResty version information and available tools:

/usr/local/openresty/bin/openresty -v
/usr/local/openresty/bin/resty -V

Test the Lua interpreter functionality:

/usr/local/openresty/bin/resty -e 'print("OpenResty installation successful")'

List all installed OpenResty packages:

dnf list installed | grep openresty

If version commands fail, verify the installation path and check for permission issues. The binaries should be executable by all users with appropriate file permissions.

Installation Method 2: Source Compilation

Downloading OpenResty Source Code

Source compilation provides maximum flexibility and optimization opportunities for specific hardware configurations. This method requires more time and technical knowledge but enables custom module integration and performance tuning.

Create a dedicated directory for source compilation:

mkdir ~/openresty-build
cd ~/openresty-build

Download the latest stable OpenResty release:

wget https://openresty.org/download/openresty-1.27.1.2.tar.gz

Verify download integrity using provided checksums:

wget https://openresty.org/download/openresty-1.27.1.2.tar.gz.asc
gpg --verify openresty-1.27.1.2.tar.gz.asc openresty-1.27.1.2.tar.gz

Extract the source archive:

tar -xzf openresty-1.27.1.2.tar.gz
cd openresty-1.27.1.2

Configuring Build Environment

Install additional compilation dependencies beyond the basic development tools:

sudo dnf install -y readline-devel ncurses-devel gdbm-devel tk-devel db4-devel libpcap-devel xz-devel libffi-devel

Configure the build environment with custom options tailored to your requirements:

./configure \
    --prefix=/usr/local/openresty \
    --with-pcre-jit \
    --with-ipv6 \
    --with-http_ssl_module \
    --with-http_realip_module \
    --with-http_stub_status_module \
    --with-http_gzip_static_module \
    --with-file-aio \
    --with-http_secure_link_module

The configuration script checks system compatibility and prepares build files. Each option enables specific functionality that may be required for your use case.

Compilation Process

Begin compilation using all available CPU cores for faster build times:

make -j$(nproc)

The compilation process takes several minutes depending on system performance. Monitor output for errors or warnings that might indicate configuration issues.

Install compiled binaries and files:

sudo make install

Create symbolic links for system-wide binary access:

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

Post-Compilation Setup

Configure environment variables for easier command access:

echo 'export PATH=/usr/local/openresty/bin:$PATH' >> ~/.bashrc
source ~/.bashrc

Create a systemd service file for source installations:

sudo tee /etc/systemd/system/openresty.service > /dev/null <

Reload systemd configuration:

sudo systemctl daemon-reload

Configuration and Service Management

Creating SystemD Service File

Proper service management ensures OpenResty starts automatically during system boot and integrates seamlessly with Rocky Linux 10’s systemd infrastructure. Repository installations typically include service files, but source installations require manual configuration.

For repository installations, the service file should already exist. Verify its presence:

sudo systemctl cat openresty

If modifications are needed, create a custom service override:

sudo systemctl edit openresty

Basic OpenResty Configuration

OpenResty uses Nginx configuration syntax with additional Lua-specific directives. The main configuration file location depends on your installation method.

For repository installations, edit the main configuration:

sudo vim /usr/local/openresty/nginx/conf/nginx.conf

Create a basic configuration that demonstrates OpenResty’s capabilities:

worker_processes auto;
error_log /var/log/openresty/error.log;
pid /run/openresty.pid;

events {
    worker_connections 1024;
    use epoll;
}

http {
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';

    access_log /var/log/openresty/access.log main;

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;

    include /usr/local/openresty/nginx/conf/mime.types;
    default_type application/octet-stream;

    server {
        listen 80 default_server;
        listen [::]:80 default_server;
        server_name _;
        root /usr/local/openresty/nginx/html;

        location / {
            index index.html index.htm;
        }

        location /lua {
            content_by_lua_block {
                ngx.say("Hello from OpenResty Lua!")
                ngx.say("Server time: ", os.date())
            }
        }

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
            root /usr/local/openresty/nginx/html;
        }
    }
}

Create log directories:

sudo mkdir -p /var/log/openresty
sudo chown openresty:openresty /var/log/openresty

Starting and Enabling OpenResty Service

Test configuration syntax before starting the service:

sudo /usr/local/openresty/bin/openresty -t

Start OpenResty service:

sudo systemctl start openresty

Enable automatic startup during boot:

sudo systemctl enable openresty

Verify service status and functionality:

sudo systemctl status openresty
sudo systemctl is-active openresty
sudo systemctl is-enabled openresty

Firewall Configuration

Rocky Linux 10 includes firewalld for network security management. Configure appropriate rules to allow web traffic while maintaining system security.

Check current firewall status:

sudo firewall-cmd --state
sudo firewall-cmd --list-all

Open standard HTTP and HTTPS ports:

sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload

For custom ports, use specific port numbers:

sudo firewall-cmd --permanent --add-port=8080/tcp
sudo firewall-cmd --reload

Verify firewall rules:

sudo firewall-cmd --list-services
sudo firewall-cmd --list-ports

Directory Structure and Permissions

Understanding OpenResty’s directory layout helps with configuration management and troubleshooting. The installation creates several key directories with specific purposes.

Main installation directory structure:

/usr/local/openresty/
├── bin/           # Executable binaries
├── luajit/        # LuaJIT interpreter
├── lualib/        # Lua libraries
├── nginx/         # Nginx components
│   ├── conf/      # Configuration files
│   ├── html/      # Default web content
│   ├── logs/      # Log files
│   └── sbin/      # Nginx binary
└── pod/           # Documentation

Set appropriate permissions for web content and configuration directories:

sudo chown -R root:root /usr/local/openresty
sudo chmod -R 755 /usr/local/openresty
sudo chown -R openresty:openresty /usr/local/openresty/nginx/logs

Testing and Verification

Basic Functionality Testing

Verify OpenResty responds correctly to HTTP requests using various testing methods. These tests confirm proper installation and basic configuration functionality.

Test local connectivity:

curl -I http://localhost
curl http://localhost

Expected response should include OpenResty identification in server headers and return the default welcome page content.

Test the Lua integration endpoint:

curl http://localhost/lua

This should return the Lua-generated content demonstrating successful script execution within the OpenResty environment.

Creating Test Configuration

Develop a comprehensive test configuration that exercises various OpenResty features and confirms proper operation across different scenarios.

Create a test server block:

server {
    listen 8080;
    server_name test.local;

    location /info {
        content_by_lua_block {
            ngx.header["Content-Type"] = "text/plain"
            ngx.say("OpenResty Version: ", ngx.var.nginx_version)
            ngx.say("Server Address: ", ngx.var.server_addr)
            ngx.say("Request Time: ", ngx.var.request_time)
            ngx.say("Connection: ", ngx.var.connection)
        }
    }

    location /echo {
        content_by_lua_block {
            local args = ngx.req.get_uri_args()
            for key, val in pairs(args) do
                ngx.say(key, ": ", val)
            end
        }
    }
}

Test the configuration syntax:

sudo /usr/local/openresty/bin/openresty -t

Reload configuration:

sudo systemctl reload openresty

Test new endpoints:

curl http://localhost:8080/info
curl "http://localhost:8080/echo?name=test&value=123"

Performance and Load Testing

Conduct basic performance testing to establish baseline metrics and verify system stability under load conditions.

Install Apache Bench for simple load testing:

sudo dnf install -y httpd-tools

Perform basic load testing:

ab -n 1000 -c 10 http://localhost/
ab -n 500 -c 5 http://localhost/lua

Monitor system resources during testing:

top -p $(pgrep openresty)
iostat -x 1 5

Use the built-in stub_status module for monitoring:

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

Log Analysis and Debugging

Proper log analysis helps identify issues and optimize performance. OpenResty generates various log types that provide insights into system behavior.

Monitor error logs in real-time:

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

Analyze access patterns:

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

Check for common configuration issues:

sudo /usr/local/openresty/bin/openresty -T

Debug Lua script issues by enabling detailed logging:

error_log /var/log/openresty/error.log debug;

Network Connectivity Verification

Confirm OpenResty binds to appropriate network interfaces and responds to remote connections as expected.

Check listening ports and processes:

sudo netstat -tlnp | grep openresty
sudo ss -tlnp | grep openresty

Test remote connectivity (from another machine):

curl -I http://your-server-ip/
telnet your-server-ip 80

Verify IPv6 functionality if configured:

curl -I http://[::1]/
netstat -tlnp6 | grep openresty

Security Hardening and Best Practices

Initial Security Configuration

Implement fundamental security measures to protect your OpenResty installation from common vulnerabilities and attacks.

Hide server version information:

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

Configure secure file permissions:

sudo chmod 640 /usr/local/openresty/nginx/conf/nginx.conf
sudo chown root:openresty /usr/local/openresty/nginx/conf/nginx.conf

Set up proper user separation:

user openresty;

SSL/TLS Setup Recommendations

Configure robust encryption for production deployments using modern TLS protocols and cipher suites.

Generate a self-signed certificate for testing:

sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
    -keyout /etc/ssl/private/openresty.key \
    -out /etc/ssl/certs/openresty.crt

Configure HTTPS server block:

server {
    listen 443 ssl http2;
    server_name your-domain.com;

    ssl_certificate /etc/ssl/certs/openresty.crt;
    ssl_certificate_key /etc/ssl/private/openresty.key;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512;
    ssl_prefer_server_ciphers off;

    add_header Strict-Transport-Security "max-age=63072000" always;
    add_header X-Frame-Options DENY;
    add_header X-Content-Type-Options nosniff;
}

Access Control and Rate Limiting

Implement protective measures against abuse and unauthorized access attempts.

Configure rate limiting:

http {
    limit_req_zone $binary_remote_addr zone=api:10m rate=1r/s;
    limit_req_zone $binary_remote_addr zone=login:10m rate=1r/m;

    server {
        location /api/ {
            limit_req zone=api burst=5 nodelay;
        }

        location /login {
            limit_req zone=login burst=2;
        }
    }
}

Set up IP-based access control:

location /admin {
    allow 192.168.1.0/24;
    allow 10.0.0.0/8;
    deny all;
}

Security Updates and Maintenance

Establish procedures for maintaining security patches and monitoring for vulnerabilities.

Configure automatic security updates:

sudo dnf install -y dnf-automatic
sudo systemctl enable --now dnf-automatic.timer

Monitor OpenResty security announcements and subscribe to relevant mailing lists for timely notifications of security issues.

Create backup procedures for configuration files:

sudo mkdir -p /etc/openresty-backup
sudo cp -r /usr/local/openresty/nginx/conf/ /etc/openresty-backup/

Common Issues and Troubleshooting

Installation Problems

Address frequent installation challenges that occur during OpenResty setup on Rocky Linux 10.

Repository connectivity issues:
If repository downloads fail, verify internet connectivity and DNS resolution:

ping openresty.org
nslookup openresty.org
curl -I https://openresty.org

Clear DNF cache and retry:

sudo dnf clean all
sudo dnf makecache

Dependency conflicts:
Resolve package conflicts by identifying conflicting packages:

dnf check
dnf history list

Remove conflicting packages if necessary:

sudo dnf remove conflicting-package

Permission denied errors:
Ensure proper sudo configuration and file permissions:

sudo visudo
ls -la /etc/sudoers.d/

Service Startup Issues

Diagnose and resolve common service startup problems that prevent OpenResty from running correctly.

Configuration syntax errors:
Always test configuration before restarting services:

sudo /usr/local/openresty/bin/openresty -t

Common syntax issues include missing semicolons, incorrect directive placement, and invalid Lua syntax.

Port binding conflicts:
Identify processes using required ports:

sudo lsof -i :80
sudo fuser -v 80/tcp

Service file problems:
Verify systemd service file syntax and permissions:

sudo systemctl cat openresty
sudo journalctl -u openresty -f

Performance and Configuration Issues

Optimize OpenResty performance and resolve common configuration challenges.

Memory usage optimization:
Monitor and adjust worker process settings:

worker_processes auto;
worker_rlimit_nofile 65535;
worker_connections 4096;

Connection limit adjustments:
Increase system limits for high-traffic scenarios:

echo "* soft nofile 65535" | sudo tee -a /etc/security/limits.conf
echo "* hard nofile 65535" | sudo tee -a /etc/security/limits.conf

Load balancing configuration:
Configure upstream servers for load distribution:

upstream backend {
    server 192.168.1.10:8080 weight=3;
    server 192.168.1.11:8080 weight=2;
    server 192.168.1.12:8080 backup;
}

Lua Script Debugging

Address common Lua scripting issues and debugging techniques specific to OpenResty environments.

Module loading issues:
Verify Lua module paths and availability:

content_by_lua_block {
    for k, v in pairs(package.loaded) do
        ngx.say(k, " = ", tostring(v))
    end
}

Performance debugging:
Use timing measurements to identify bottlenecks:

content_by_lua_block {
    local start_time = ngx.now()
    -- Your Lua code here
    local end_time = ngx.now()
    ngx.log(ngx.ERR, "Execution time: ", end_time - start_time)
}

Error handling:
Implement proper error handling in Lua scripts:

content_by_lua_block {
    local ok, err = pcall(function()
        -- Your code that might fail
    end)
    if not ok then
        ngx.log(ngx.ERR, "Lua error: ", err)
        ngx.status = 500
        ngx.say("Internal Server Error")
    end
}

Congratulations! You have successfully installed OpenResty. Thanks for using this tutorial for installing OpenResty on Rocky Linux 10 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