Nginx之tcp转发
环境网络因素无法直连一些服务,通过nginx的stream模块来转发4层.
# 1. 安装nginx
[root@demo ~]# yum -y install nginx
[root@demo ~]# nginx -v
nginx version: nginx/1.20.1
1
2
3
2
3
# 2. 配置stream
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;
events {
worker_connections 1024;
}
stream {
upstream mysql {
server 172.200.0.41:3306; #后端数据库的ip和端口,如果进行了域名解析,直接写域名就好
}
server {
listen 3306; #如果监听3306,远程登录的时候不用加-p参数
proxy_connect_timeout 10s;
proxy_timeout 30s;
proxy_pass mysql;
}
}
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 4096;
include /etc/nginx/mime.types;
default_type application/octet-stream;
include /etc/nginx/conf.d/*.conf;
server {
listen 80;
listen [::]:80;
server_name _;
root /usr/share/nginx/html;
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
error_page 404 /404.html;
location = /404.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# 3. 检查配置文件
[root@demo ~]# nginx -t
nginx: [emerg] unknown directive "stream" in /etc/nginx/nginx.conf:38
nginx: configuration file /etc/nginx/nginx.conf test failed
1
2
3
2
3
# 4. 安装stream_module
[root@demo ~]# yum -y install epel-release
[root@demo ~]# yum -y install nginx-all-modules.noarch
[root@demo ~]# ls /usr/lib64/nginx/modules/ -l
总用量 360
-rwxr-xr-x 1 root root 24600 11月 11 2022 ngx_http_image_filter_module.so
-rwxr-xr-x 1 root root 24528 11月 11 2022 ngx_http_perl_module.so
-rwxr-xr-x 1 root root 24576 11月 11 2022 ngx_http_xslt_filter_module.so
-rwxr-xr-x 1 root root 110280 11月 11 2022 ngx_mail_module.so
-rwxr-xr-x 1 root root 179856 11月 11 2022 ngx_stream_module.so
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 5. 验证
# 查看nginx.conf是否有此项:
include /usr/share/nginx/modules/*.conf;
# 如果没有,可手动增加至nginx.conf:
load_module /usr/lib64/nginx/modules/ngx_stream_module.so;
# 检查
[root@demo nginx]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 6. 配置socket转发
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_cache off;
proxy_buffering off;
chunked_transfer_encoding on;
1
2
3
4
5
2
3
4
5
上次更新: 2025/04/25, 03:40:17