nginx 代理4层服务(如:mysql)
环境:
OS:Centos 7
nginx:1.26.1
1.检查安装的nginx是否启用stream模块
[root@localhost stream.d]# nginx -V 2>&1 | grep stream

2.新建目录存放四层 stream 配置
mkdir -p /etc/nginx/stream.d/
3.准备配置文件
vi /etc/nginx/stream.d/mysql.cnf
# /etc/nginx/stream.d/mysql.cnf
upstream mysql_backend {
server 192.168.1.13:3306;
}
server {
listen 43306;
proxy_pass mysql_backend;
# 连接后端超时
proxy_connect_timeout 5s;
# 连接空闲超时
proxy_timeout 600s;
# 如需传递真实客户端IP,开启下面一行,后端mysql必须支持proxy protocol
# proxy_protocol on;
}
4.修改主配置 /etc/nginx/nginx.conf
[root@localhost nginx]# more nginx.conf
user hxl;
worker_processes auto;
error_log /var/log/nginx/error.log notice;
pid /var/run/nginx.pid;
events {
worker_connections 65535;
multi_accept on;
use epoll;
}
stream {
include /etc/nginx/stream.d/*.cnf;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE
ssl_prefer_server_ciphers on;
log_format main '{"@timestamp":"$time_iso8601","server":"$hostname","clientip":"$remote_addr","xff":"$http_x_forwarded_for","doma
in":"$host","url":"$uri","referer":"$http_referer","args":"$args","upstreamtime":"$upstream_response_time","resptime":"$request_time"
,"method":"$request_method","status":"$status","size":"$body_bytes_sent","req_len":"$request_length","protocol":"$server_protocol","u
pstreamhost":"$upstream_addr","useragent":"$http_user_agent","conns":"$connection","from":"nginx-dc"}';
access_log /var/log/nginx/access.log;
sendfile on;
tcp_nopush on;
types_hash_max_size 2048;
keepalive_timeout 300;
large_client_header_buffers 4 32k;
client_max_body_size 300m;
client_body_buffer_size 512k;
client_header_buffer_size 4k;
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
gzip on;
include /etc/nginx/conf.d/*.conf;
}
红色新增部分
5.启用
nginx -t
nginx -s reload
6.客户端连接

浙公网安备 33010602011771号