Nginx is commonly used as a high-performance HTTP and reverse proxy server for handling HTTP and HTTPS traffic. However, Nginx can also be configured as a UDP proxy, which is useful in application scenarios such as handling DNS, real-time communication, and video streaming. This article details how to build a UDP proxy using Nginx.
pre-conditions
Before you begin, make sure you have completed the following preparations:
- A server running a Linux operating system (e.g. Ubuntu or CentOS)
- Installed and configured Nginx
- With sudo or root privileges
Step 1: Install Nginx
If you haven't installed Nginx yet, you can do so with the following command:
Ubuntu
sudo apt update
sudo apt install nginx
CentOS
sudo yum install epel-release
sudo yum install nginx
Step 2: Configure Nginx to Support UDP
By default, Nginx does not support UDP proxying. Therefore, we need to make sure that Nginx is compiled with the stream
module. Most modern versions of Nginx already include this module.
First, open the Nginx configuration file for editing:
sudo nano /etc/nginx/nginx.conf
In the configuration file, find the http
block, make sure to add the stream
Configuration of the module:
upstream backend {
upstream backend {
server 127.0.0.1:12345; # replace with your UDP server address and port
}
server {
listen 12345 udp; # The port Nginx is listening on
proxy_pass backend;
}
}
Save and close the configuration file.
Step 3: Verify Configuration and Restart Nginx
Before reloading the Nginx configuration, it is a good idea to verify that the configuration file is correct:
sudo nginx -t
If there is no problem with the configuration file, you will see a message similar to the following:
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: the configuration file /etc/nginx/nginx.conf test is successful
Then, restart Nginx to apply the new configuration:
sudo systemctl restart nginx
Step 4: Test the UDP Proxy
Now you can test that Nginx's UDP proxy is working properly. You can use the nc
(netcat) command to send UDP packets for testing:
Send test packet
echo "Test UDP packet" | nc -u -w1 127.0.0.1 12345
If your back-end UDP server receives and processes packets normally, the UDP proxy configuration for Nginx is successful.
summarize
With the above steps, you have successfully configured Nginx as a UDP proxy.The power of Nginx lies in its flexibility and high performance, not only in handling HTTP traffic, but also in UDP proxying tasks. Hopefully, this tutorial will help you better utilize Nginx's capabilities to provide reliable UDP proxy services for your applications.