200字
Performance optimization configuration suggestions for OpenResty
2025-12-09
2026-11-02

Foreword

As the user base of 1Panel continues to grow, so does the usage of its built-in web service, OpenResty. However, there are few tutorials available online on how to optimize it. I, the blogger, previously used BT Panel and have also switched to 1Panel, so today I'm sharing some optimization tips for OpenResty. There are limited configurable settings for optimization, so feel free to adjust the configurations based on your actual needs. If you are unsure how to migrate your website, please refer to: [How a Novice Can Replace BT Panel with 1Panel].

1Panel OpenResty Performance Optimization Guide

Most of OpenResty's optimization settings are inherited from Nginx. In the 1Panel environment, you typically need to make adjustments in the configuration files (such as nginx.conf or the corresponding virtual host configuration).

1. Core Worker Process Optimization (in nginx.conf's main or events block)

This is the most critical configuration for determining the server's concurrent processing capability.

Setting

Recommended Configuration

Explanation and Optimization Points

worker_processes

auto or CPU core count

Recommended to set to auto to let Nginx automatically detect the number of CPU cores. Generally set to the number of CPU cores, e.g., 4 for a 4-core CPU. Setting it too high may increase overhead due to context switching.

worker_connections

10240 or higher

The maximum number of connections a single Worker process can open. Formula: Max concurrent connections = worker_processes * worker_connections. In a production environment, it is recommended to set it to $10,240$ or higher, but ensure the system's file descriptor limit (ulimit) is sufficiently high.

multi_accept

on

When enabled, a Worker process can accept all new connections at once, instead of one at a time. This can improve performance in high-concurrency scenarios.

use

epoll (Linux)

Suitable for Linux systems, this is the high-performance I/O event model. It is the default and best choice on most modern Linux distributions.

Note: In 1Panel, you must ensure that the system-level ulimit -n value is greater than the set value of worker_connections, otherwise the configuration will not take effect.

2. HTTP Request and Connection Optimization (in the http block)

These settings affect the efficiency of client-server communication.

Setting

Recommended Configuration

Explanation and Optimization Points

keepalive_timeout

65 (seconds)

The timeout for client persistent connections. Too long wastes resources; too short increases connection establishment overhead. $65$ seconds is a common recommended value.

sendfile

on

Allows the operating system to send files directly in the kernel, avoiding data copies between user-space and kernel-space. This is essential for static file serving.

tcp_nopush

on

Used with sendfile on, it sends data only after the response header is sent and the TCP buffer is full. This effectively reduces the number of network packets and improves I/O efficiency.

tcp_nodelay

on

Immediately sends small data packets. This is crucial for Keepalive connections and can reduce response latency. Recommended to enable.

client_header_buffer_size

$1\text{k}$ (default)

The buffer size for client request headers. Keep the default unless you encounter an HTTP 400 Bad Request error.

3. Enabling Gzip Compression

Although it increases CPU load, it greatly reduces the amount of data transferred, improving user experience, especially in environments with limited bandwidth.

Setting

Recommended Configuration

Explanation and Optimization Points

gzip

on

Enables Gzip compression.

gzip_comp_level

5 or 6

Compression level. $1$ is fastest, $9$ has the highest ratio. $5$ or $6$ usually offers a good balance between CPU consumption and compression ratio.

gzip_min_length

1024

Only compresses files larger than this byte size. Avoid compressing small files, as the CPU overhead may outweigh the bandwidth savings.

gzip_types

text/plain application/javascript ...

Specifies the MIME types of files to be compressed. Do not compress already compressed formats (e.g., .jpg, .png, .zip), as this wastes CPU resources.

4. OpenResty LuaJIT Optimization (in the http block)

OpenResty's core performance advantage lies in LuaJIT. Ensuring that Lua code caching is enabled is vital.

Setting

Recommended Configuration

Explanation and Optimization Points

lua_code_cache

on (Production)

Must be enabled in production. When enabled, LuaJIT compiles and performs JIT optimization on the Lua code, resulting in massive performance gains. Set to off only for debugging.

lua_shared_dict

Configure as needed

If your Lua code uses shared memory (for caching, rate limiting, etc.), this must be configured. E.g.: lua_shared_dict cache_dict 100m;. Allocate size reasonably to avoid waste or insufficiency.

5. Log Optimization

In high-concurrency scenarios, frequent disk I/O for writing logs can become a bottleneck.

Setting

Recommended Configuration

Explanation and Optimization Points

access_log

Can be disabled or buffered as needed

If traffic is extremely high and detailed logs are not needed: access_log off;. If logs are required: consider writing logs to a Ring Buffer or using the buffer and flush parameters to reduce I/O frequency.

6. server_names_hash_bucket_size Parameter Optimization

Category

Parameter Name

Meaning

Nginx Core

server_names_hash_bucket_size

Server name hash table bucket size. Used to store the domain names (server_name) for Virtual Hosts.

Core Principle and Significance

  • Hash Table: Nginx uses a hash table to quickly determine which server block corresponds to the client's Host header. server_names_hash_bucket_size defines the maximum byte size for each bucket in this hash table.

  • Error Trigger: If your configured domain name is too long or you have too many domain names, Nginx may fail to load all domains into the hash table buckets during initialization, leading to an error: could not build server_names_hash, you should increase server_names_hash_bucket_size.

  • Optimization Goal: To avoid hash collisions and ensure all domain names are successfully loaded, while minimizing lookup time.

Optimization Recommendations

Optimization Scenario

Recommended Value

Rationale

Standard/General Config

$64$

Default or slightly increased to $64$ bytes is usually sufficient.

Many or Long Domain Names

$128$ or $256$

When there are many domains or very long wildcard domains (e.g., *.subdomain.longdomainname.com), increase this value to accommodate the longest key.

High-Performance Server

$256$

Setting directly to $256$ bytes is a safe, conservative value for high-spec servers, ensuring quick loading and future-proofing.

Rule of Thumb

$\frac{\text{server\_names\_hash\_max\_size}}{2}$

Recommended to be $\frac{1}{2}$ to $\frac{1}{3}$ of the server_names_hash_max_size value, as the two parameters work in tandem.

Configuration Location: Typically in the Nginx configuration file's http block:

Nginx

http {
    # Recommended to configure here
    server_names_hash_bucket_size 128; 
    # server_names_hash_max_size 512; # Another related parameter
    ...
}

Key Takeaway: Increasing this value slightly increases memory usage but significantly improves domain lookup stability and initialization success rate. For many web services in the 1Panel environment, $128$ or $256$ is recommended.

7. client_header_buffer_size Parameter Optimization

Category

Parameter Name

Meaning

Nginx HTTP

client_header_buffer_size

The buffer size for reading client request headers.

Core Principle and Significance

  • Function: Defines the memory size Nginx allocates to store the client request line (e.g., GET /path HTTP/1.1) and request headers (e.g., Host, User-Agent, Cookie).

  • Default Value: Usually $1\text{k}$ byte (i.e., 1024 bytes).

  • Error Trigger: If the total size of client request headers (especially the Cookie field or requests with numerous custom headers) exceeds this limit, Nginx cannot read the header completely and immediately returns an HTTP 400 Bad Request error.

Optimization Recommendations

Optimization Scenario

Recommended Value

Rationale

Standard/Regular Service

Maintain default $1\text{k}$

Request headers are usually small for most standard websites and APIs; the default is sufficient.

Large Cookies/SSO Scenarios

$4\text{k}$ or $8\text{k}$

The Cookie field is the most common reason for increased header size, particularly with complex authentication (SSO/OAuth) or large session data.

Special Business Needs

$16\text{k}$ or $32\text{k}$

In rare cases requiring very large custom headers or huge cookies, increase further. $32\text{k}$ is a high upper bound.

Suggestion: Adjust incrementally. Prioritize increasing the buffer size from $1\text{k}$ to $4\text{k}$ or $8\text{k}$. Only consider increasing to $16\text{k}$ or $32\text{k}$ if $8\text{k}$ still results in 400 errors.

8. client_max_body_size Parameter Optimization

Category

Parameter Name

Meaning

Nginx HTTP

client_max_body_size

Limits the maximum allowed size of the client request body.

Core Principle and Significance

  • Function: Controls the upper limit of the data body carried by HTTP requests (like POST or PUT), such as form data, file content, or JSON/XML payloads.

  • Default Value: Typically $1\text{m}$ (1 Megabyte).

  • Error Trigger: If the client's request body size exceeds this limit, Nginx immediately returns an HTTP 413 Request Entity Too Large error.

  • Importance: Setting a reasonable limit is a crucial security measure to prevent Denial of Service (DoS) attacks by exhausting server resources with oversized requests.

Optimization Recommendations

Business Scenario

Recommended Value

Rationale

General Web Forms

$1\text{m}$ - $10\text{m}$

$1\text{m}$ to $5\text{m}$ is usually enough for standard submissions. Increase to $10\text{m}$ if small image uploads are included.

Large File Uploads

$50\text{m}$ - $512\text{m}$

Must be set according to the maximum allowed file size (e.g., $100\text{m}$ for video uploads).

API Services

$1\text{m}$ - $10\text{m}$

Data payloads are usually small. $1\text{m}$ to $10\text{m}$ provides good security unless the business requires passing very large data objects.

Configuration Location: Can be set in the http, server, or location block.

Nginx

http {
    client_max_body_size 10m; # Default value
    
    server {
        location /upload/videos {
            client_max_body_size 512m; # Relax limit for specific upload path
        }
    }
}

Proxy Chain: If OpenResty is behind a load balancer or CDN, ensure that all devices in the proxy chain have a request body limit greater than or equal to this value.

9. keepalive_timeout Parameter Optimization

Category

Parameter Name

Meaning

Nginx HTTP

keepalive_timeout

Sets the timeout for persistent (Keep-Alive) connections.

Core Principle and Significance

  • Function: Defines the maximum seconds a connection can remain idle after being established between the client and server.

  • Keep-Alive: Allows multiple HTTP requests/responses to be sent over the same TCP connection, avoiding the overhead of frequent connection establishment/teardown.

  • Importance: Improves efficiency and reduces latency for loading web pages with multiple resources.

  • Timeout Consequence: Nginx closes the TCP connection when the idle time exceeds keepalive_timeout.

Optimization Recommendations

Optimization Scenario

Recommended Value

Rationale

Standard Web Service

$65$ seconds

A globally recommended value. Long enough for page loading, but doesn't waste resources by holding connections too long.

Behind LB/CDN

Must match upstream

Must be less than or equal to the timeout set by the upstream Load Balancer or CDN to prevent unexpected errors.

Mobile/High Concurrency

$30$ - $60$ seconds

Can be slightly shorter to release idle connections faster, making resources available for new connections.

Configuration Location: Typically in the Nginx configuration file's http block.

Nginx

http {
    keepalive_timeout 60; # Recommended value
    # keepalive_requests 100; # Another related parameter
    ...
}

Conclusion: Keeping keepalive_timeout in the $60$ - $75$ second range is the best practice for balancing performance improvement and resource utilization.

Optimized Configuration Example

Nginx

http {
    # Gzip Configuration
    gzip on;
    gzip_min_length 1k;
    gzip_comp_level 6;
    gzip_buffers 4 16k;
    gzip_http_version 1.1;
    gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php application/json;
    gzip_vary on;
    gzip_proxied any;
    gzip_disable "msie6";

    # Server Name Hash Table Size
    server_names_hash_bucket_size 128;

    # Client Header Buffer Size
    client_header_buffer_size 32k;
    large_client_header_buffers 4 32k;

    # Client Request Body Max Size
    client_max_body_size 32m;

    # Keep-Alive Timeout
    keepalive_timeout 60;

    # Other configurations...
}

Conclusion

That concludes today's sharing, which was based on tinkering with a VMRack Premium Triple-Network 4-Core 4G machine. You can adjust these settings based on your website's load type (more static serving or dynamic computing) and resource configuration (CPU cores, memory size), and perform stress testing in your actual environment to find the optimal balance.

Comment