这篇文章上次修改于 902 天前,可能其部分内容已经发生变化,如有疑问可询问作者。

在 nginx 配置文件的末尾添加:

stream {
  log_format proxy '$remote_addr [$time_local] '
                   '$protocol $status $bytes_sent $bytes_received '
                   '$session_time "$upstream_addr" '
                   '"$upstream_bytes_sent" "$upstream_bytes_received" "$upstream_connect_time"';

  access_log /var/log/nginx/udp-access.log proxy;
  open_log_file_cache off;
  tcp_nodelay on;

  upstream tcp_server {
       server 192.168.49.2:50011;
  }
  server{
       listen 20011 so_keepalive=on;
       proxy_connect_timeout 8s;
       proxy_pass tcp_server;
  }

  upstream udp_server {
       server 192.168.49.2:21116;
  }
  server{
       listen 21116 udp reuseport;
       proxy_connect_timeout 8s;
       proxy_pass udp_server;
  }
}

本例中,udp server 用来保持心跳,接收信息比较频繁,所以需要写上 reuseport,以提高性能,原因详见:https://www.zhihu.com/question/51618274