SoFunction
Updated on 2025-04-08

Steps for implementing TCP and UDP proxy in Nginx

Preface

Nginx is a high-performance HTTP and reverse proxy server, and also supports TCP/UDP proxy. After version 1.9.13, Nginx already supports port forwarding, including TCP and UDP protocols. Nginx's TCP/UDP proxy function allows it to act as a middleman, receive TCP or UDP requests from the client and forward these requests to the specified backend server, and then return the backend server's response to the client.

Nginx's TCP and UDP proxy

How it works

  • Configuration: First, you need to set the relevant parameters of the TCP/UDP proxy in the Nginx configuration file, such as the listening port, the address and port of the backend server, etc.
  • monitor: Nginx listens for connection requests from clients on the specified port according to the settings in the configuration file.
  • connect: When receiving the client's connection request, Nginx will immediately try to establish a connection with the backend server.
  • Data Forwarding: After establishing the connection, Nginx forwards the data sent by the client to the backend server and forwards the response data of the backend server back to the client.
  • Stay connected: Nginx supports long and short connections, maintain or close connections with clients and backend servers according to actual needs.
  • Security and optimization:Nginx also provides advanced functions such as SSL/TLS encryption, load balancing, and failover to enhance the security and stability of TCP/UDP proxy services.

Schematic diagram

+--------+      +--------+      +--------+
|  Client | ---> |   Nginx  | ---> | Backend|
+--------+      +--------+      +--------+

Configuration file and command parameter comments

The configuration file of Nginx is generally located in the Nginx installation directory.confIn the directory, the main configuration files are. Here are some basic configuration directives and their comments:

# Number of worker processesworker_processes  auto;

# Location and log level of error log fileerror_log /var/log/nginx/ info;

# Event module configurationevents {
    # Maximum number of connections allowed per worker process    worker_connections  1024;
}

# HTTP module configurationhttp {
    # Contains MIME type configuration file    include       ;
    # Default MIME type    default_type  application/octet-stream;
    # Log format    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    '$status $body_bytes_sent "$http_referer" '
    '"$http_user_agent" "$http_x_forwarded_for"';
    # Location of access logs    access_log  logs/  main;
    # Enable efficient file transfer mode    sendfile     on;
    # TCP_NODELAY option settings    tcp_nopush   on;
    # TCP_NODELAY option settings    tcp_nodelay  on;
    # Long connection timeout    keepalive_timeout  65;
    #Other configurations...}

# TCP/UDP module configurationstream {
    # TCP proxy configuration    upstream backend {
        server 127.0.0.1:12345  max_fails=3 fail_timeout=30s;
    }
    server {
        listen 12345;
        proxy_connect_timeout 1s;
        proxy_timeout 3s;
        proxy_pass backend;
    }
    
    # UDP proxy configuration    upstream udp_backend {
        server 192.168.31.51:514;
    }
    server {
        listen 1514 udp;
        proxy_pass udp_backend;
    }
}

Basic Commands

  • nginx -t: Check whether there are syntax errors in the configuration file.
  • nginx -s reload: Hot load, reload the configuration file.
  • nginx -s stop: Quickly close.
  • nginx -s quit: Closed after waiting for the worker process to complete.

Configuration instance description

TCP proxy instance

The following are detailed notes for Nginx TCP proxy configuration:

# Define a context named 'stream' to configure the TCP/UDP proxystream {
    # Define an upstream server group 'backend' to store information about the backend server    upstream backend {
        # Specify a server in the upstream server group, here is the 12345 port of the machine        server 127.0.0.1:12345; 
        # Set the maximum number of failed attempts to 3 times        max_fails=3; 
        # Set the timeout time to 30 seconds after failure        fail_timeout=30s;
    }
    # Define a server block that listens and proxies TCP traffic    server {
        # Listen to the local port 12345, which is used to receive the client's TCP connection        listen 12345;
        # Set the timeout time to establish a connection with the backend server to 1 second        proxy_connect_timeout 1s;
        # Set the timeout time to communicate with the backend server to 3 seconds        proxy_timeout 3s;
        # Proxy traffic to the defined 'backend' upstream server group        proxy_pass backend;
    }
}

The main function of this configuration is to let Nginx listen to the local port 12345 and forward all received TCP connections to another local service, which runs on port 12345. At the same time, the configuration also includes a health check and failover mechanism for the backend service. If the backend service cannot connect for 3 consecutive times, the service is considered to have failed and try to reconnect after a 30-second timeout. This can improve the availability and stability of proxy services.

UDP proxy instance

The following are detailed notes for Nginx UDP proxy configuration:

# Define a context named 'stream' to configure the TCP/UDP proxystream {
    # Define an upstream server group 'udp_backend' to store information about the backend UDP server    upstream udp_backend {
        # Specify a server in the upstream server group, here is the 514 port of 192.168.31.51        server 192.168.31.51:514;
    }
    
    # Define a server block that listens and proxys UDP traffic    server {
        # Listen to the local port 1514 and receive UDP packets from the client        listen 1514 udp;
        # Proxy the received UDP traffic to the defined 'udp_backend' upstream server group        proxy_pass udp_backend;
    }
}

illustrate:

  • stream: This is a context block dedicated to configuring traffic proxy for TCP and UDP. Unlike HTTP contexts, the stream context handles raw network traffic.

  • upstream udp_backend: Define a nameudp_backendThe upstream server group contains information about the backend UDP server. In this example, there is only one server.

  • server 192.168.31.51:514: Specify the IP address and port number of the upstream server. Here, Nginx will forward the received UDP packet to port 514 of 192.168.31.51.

  • server: Define a server block that handles listening and proxying of UDP traffic.

  • listen 1514 udp: Nginx will listen to the local port 1514 and receive UDP packets from the client.udpThe keyword indicates that Nginx works in UDP mode.

  • proxy_pass udp_backend: Proxy the received UDP traffic to the previously definedudp_backendUpstream server group. Nginx will forward UDP packets sent by the client to port 1514 to port 514 of 192.168.31.51.

Through this configuration, Nginx can serve as a UDP proxy server to forward traffic to the specified backend server, which is suitable for application scenarios that require UDP protocol, such as Syslog, etc.

Summarize

Through these configurations, Nginx can serve as a powerful TCP/UDP proxy server, suitable for a variety of application scenarios, such as databases, mail servers, game servers, etc.

This is the article about the methods and steps of Nginx implementing TCP and UDP proxy. For more information about Nginx TCP and UDP proxy, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!