Original author: Maxim Ivanitskiy of F5
Original link: SSL/TLS certificate rotation can be achieved without restarting NGINX open source version
Reprint source: NGINX open source community
The only official Chinese community of NGINX, all at nginx.org.cn
In the world of high-performance web servers, NGINX is a popular choice because its lightweight and efficient architecture allows it to handle large amounts of traffic. By introducing the shared dictionary function in the NGINX JavaScript module (njs) , the performance of NGINX has been taken to the next level.
In this article, we explore the features and benefits of njs shared dictionaries and show how to set up NGINX Open Source to rotate SSL/TLS certificates without restarting.
Introduction to shared dictionaries and their advantages
The new directive allows NGINX open source users to enable shared memory areas to efficiently exchange data between worker processes. These shared memory areas act as key-value dictionaries, storing dynamic configuration settings that can be accessed and modified in real time. js_shared_dict_zone
The main advantages of shared dictionaries include:
- Minimal overhead and easy to use – Built directly into njs, it is easy to configure and use thanks to an intuitive API and simple implementation. It also helps you simplify data management and sharing between worker processes.
- Lightweight and efficient – seamlessly integrates with NGINX, leveraging its event-driven, non-blocking I/O model. This method reduces memory usage and improves concurrent processing capabilities, allowing NGINX to efficiently handle a large number of concurrent connections.
- Scalability – With NGINX’s ability to scale horizontally across multiple worker processes, you can share and synchronize data between these processes without the need for complex inter-process communication mechanisms. Time-to-live (TTL) settings allow you to manage records in shared dictionary entries and remove inactive entries from the zone. The evict parameter deletes the oldest key-value pair to make room for new entries.
SSL rotation using shared dictionary
One of the most effective use cases for shared dictionaries is SSL/TLS rotation. When used , SSL/TLS certificates or keys can be updated without restarting NGINX. Additionally, it provides a REST-like API for managing certificates on NGINX. js_shared_dict_zone
Below is an example NGINX configuration file that uses the and directives to set up an HTTPS server. A JavaScript handler that reads an SSL/TLS certificate or key from a file. js_set
ssl_certificate
js_set
This configuration snippet uses a shared dictionary to store certificates and keys as a cache in shared memory. If there is no key, the certificate or key is read from disk and placed in the cache.
You can also expose a location to manually clear the cache. Once files on disk are updated (such as certificate and key updates), the shared dictionary reads these updates from disk. This adjustment allows certificate/key rotation without restarting the NGINX process.
http {
...
js_shared_dict_zone zone=kv:1m;
server {
…
# Sets an njs function for the variable. Returns a value of cert/key
js_set $dynamic_ssl_cert main.js_cert;
js_set $dynamic_ssl_key main.js_key;
# use variable's data
ssl_certificate data:$dynamic_ssl_cert;
ssl_certificate_key data:$dynamic_ssl_key;
# a location to clear cache
location = /clear {
js_content main.clear_cache;
# allow 127.0.0.1;
# deny all;
}
...
}
Here is a JavaScript implementation using rotating SSL/TLS certificates and keys: js_shared_dict_zone
function js_cert(r) {
if (r.variables['ssl_server_name']) {
return read_cert_or_key(r, '.cert.pem');
} else {
return '';
}
}
function js_key(r) {
if (r.variables['ssl_server_name']) {
return read_cert_or_key(r, '.key.pem');
} else {
return '';
}
}
/**
* Retrieves the key/cert value from Shared memory or fallback to disk
*/
function read_cert_or_key(r, fileExtension) {
let data = '';
let path = '';
const zone = 'kv';
let certName = r.variables.ssl_server_name;
let prefix = '/etc/nginx/certs/';
path = prefix + certName + fileExtension;
r.log('Resolving ${path}');
const key = ['certs', path].join(':');
const cache = zone && ngx.shared && ngx.shared[zone];
if (cache) {
data = cache.get(key) || '';
if (data) {
r.log(`Read ${key} from cache`);
return data;
}
}
try {
data = fs.readFileSync(path, 'utf8');
r.log('Read from cache');
} catch (e) {
data = '';
r.log(`Error reading from file:${path}. Error=${e}`);
}
if (cache && data) {
try {
cache.set(key, data);
r.log('Persisted in cache');
} catch (e) {
const errMsg = `Error writing to shared dict zone: ${zone}. Error=${e}`;
r.log(errMsg);
}
}
return data
}
You can invalidate the cache by sending a request so that NGINX loads the SSL/TLS certificate or key from disk during the next SSL/TLS handshake. Additionally, you can use to obtain an SSL/TLS certificate or key from the request while persisting and updating the cache. /clear
js_content
The complete code for this example can be found in the njs GitHub repository .
start immediately
共享字典功能是一款强大的应用可编程性工具,在简化和可扩展性方面具有显著优势。利用 js_shared_dict_zone
的功能,您可以发掘新的增长机遇,并高效处理不断增长的流量需求。
Ready to speed up your NGINX deployment? You can upgrade your NGINX deployment to unlock new use cases. For more information about this feature, please see our documentation . Additionally, you can see a complete example of shared dictionary functionality in the recently launched njs-acme project , which enables the njs module runtime to work with ACME providers. js_shared_dict_zone
js_shared_dict_zone
If you are interested in the NGINX open source version or have any questions, you are welcome to add Xiao N Assistant on WeChat (WeChat ID: nginxoss) to join the NGINX official WeChat group to learn more, ask questions and get feedback about the NGINX open source version.
The only official Chinese community of NGINX, all at nginx.org.cn
More NGINX-related technical information, interactive Q&A, series of courses, and event resources: Open Source Community Official Website | WeChat Official Account
A programmer born in the 1990s developed a video porting software and made over 7 million in less than a year. The ending was very punishing! High school students create their own open source programming language as a coming-of-age ceremony - sharp comments from netizens: Relying on RustDesk due to rampant fraud, domestic service Taobao (taobao.com) suspended domestic services and restarted web version optimization work Java 17 is the most commonly used Java LTS version Windows 10 market share Reaching 70%, Windows 11 continues to decline Open Source Daily | Google supports Hongmeng to take over; open source Rabbit R1; Android phones supported by Docker; Microsoft's anxiety and ambition; Haier Electric shuts down the open platform Apple releases M4 chip Google deletes Android universal kernel (ACK ) Support for RISC-V architecture Yunfeng resigned from Alibaba and plans to produce independent games on the Windows platform in the future