nginx:socker转发
程序员文章站
2022-06-15 22:57:43
...
1.安装nginx,stream模块默认不安装的,需要手动添加参数:–with-stream,官方下载地址:download,根据自己系统版本选择nginx1.9或以上版本。
2.nginx.conf 配置,参考说明:ngx_stream_core_module(http://nginx.org/en/docs/stream/ngx_stream_core_module.html)
======================================
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
.................
}
# tcp层转发的配置文件夹
include /etc/nginx/tcp.d/*.conf;
======================================
请注意,stream配置不能放到http内,即不能放到/etc/nginx/conf.d/,因为stream是通过tcp层转发,而不是http转发。
如配置在http内,启动nginx会报如下错误:
nginx: [emerg] "server" directive is not allowed here
3.在tcp.d下新建个bss_num_30001.conf文件
======================================
stream {
# 添加socket转发的代理
upstream bss_num_socket {
hash $remote_addr consistent;
# 转发的目的地址和端口
server 130.51.11.33:19001 weight=5 max_fails=3 fail_timeout=30s;
}
# 提供转发的服务,即访问localhost:30001,会跳转至代理bss_num_socket指定的转发地址
server {
listen 30001;
proxy_connect_timeout 1s;
proxy_timeout 3s;
proxy_pass bss_num_socket;
}
}
======================================
4.重启nginx,访问localhost:30001,会跳转到bss_num_socket指定的转发地址130.51.11.33:19001
2.nginx.conf 配置,参考说明:ngx_stream_core_module(http://nginx.org/en/docs/stream/ngx_stream_core_module.html)
======================================
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
.................
}
# tcp层转发的配置文件夹
include /etc/nginx/tcp.d/*.conf;
======================================
请注意,stream配置不能放到http内,即不能放到/etc/nginx/conf.d/,因为stream是通过tcp层转发,而不是http转发。
如配置在http内,启动nginx会报如下错误:
nginx: [emerg] "server" directive is not allowed here
3.在tcp.d下新建个bss_num_30001.conf文件
======================================
stream {
# 添加socket转发的代理
upstream bss_num_socket {
hash $remote_addr consistent;
# 转发的目的地址和端口
server 130.51.11.33:19001 weight=5 max_fails=3 fail_timeout=30s;
}
# 提供转发的服务,即访问localhost:30001,会跳转至代理bss_num_socket指定的转发地址
server {
listen 30001;
proxy_connect_timeout 1s;
proxy_timeout 3s;
proxy_pass bss_num_socket;
}
}
======================================
4.重启nginx,访问localhost:30001,会跳转到bss_num_socket指定的转发地址130.51.11.33:19001