nginx配置tcp转发
遇到的问题:
平时配置nginx转发时,是直接在/etc/nginx/conf.d文件夹下配置的,然后配置tcp转发的时候,我也把配置文件写在了/etc/nginx/conf.d下,但配置好之后运行nginx -t总是不通过。当我把转发的ip地址前加上http:// 的时候却没有问题。但加了http:// 之后tcp请求就会出现一些问题。很明显http:// 并不是tcp服务。 起初我以为是我的nginx版本太老,但我看了下我的nginx版本,我的已经是最新版本的nginx了。后来我从网上搜寻答案,发现是nginx需要安装第三方模块,需要在编译的时候添加 –with-stream之类的参数,但我觉得这个不应该啊,既然这个功能那么重要,为什么nginx不把这个功能放进nginx官方安装包里呢?
解决方案:
后来我发现/etc/nginx/conf.d/文件夹下的所有配置文件都是包含在/etc/nginx/nginx.conf配置文件里的http{}服务里的,因为我的目的是做tcp转发,但nginx 的tcp转发并不能放在http{}服务里。 当我把配置的转发代码放在/etc/nginx/nginx.conf的http{}外面的时候,nginx -t通过了,而且功能也正常了。以下是我的nginx.conf配置文件,其中stream是我配置的端口转发。
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
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;
keepalive_timeout 65;
#gzip on;
include /etc/nginx/conf.d/*.conf;
}
stream {
upstream cloudsocket {
hash $remote_addr consistent;
# $binary_remote_addr;
server 172.17.0.1:6391 max_fails=3 fail_timeout=30s;
}
server {
listen 8080;
proxy_connect_timeout 10s;
proxy_timeout 300s;
proxy_pass cloudsocket;
}
}