TCP 代理到 postgres 数据库作为 nginx 中的上游服务器

TCP proxy to postgres database as an upstream server in nginx

问:是否可以将Nginx设置为数据库的反向代理? 这些是我目前拥有的标志,我相信拥有 --with-stream 模块足以将 TCP 流用于数据库。这是附加功能吗?

Nginx 配置选项:

--prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=%{_libdir}/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-http_ssl_module --with-http_realip_module --with-http_addition_module --with-http_sub_module --with-http_dav_module --with-http_flv_module --with-http_mp4_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_random_index_module --with-http_secure_link_module --with-http_stub_status_module --with-http_auth_request_module --with-threads --with-stream --with-stream_ssl_module --with-http_slice_module --with-mail --with-mail_ssl_module --with-file-aio --with-http_v2_module --with-cc-opt='-g -O2 -fstack-protector-strong -Wformat -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2' --with-ld-opt='-Wl,-z,relro -Wl,--as-needed' --with-ipv6

Nginx 配置

stream {

    include conf.d/streams/*.conf;
}

conf.d/streams/upstream.conf

的内容
upstream database_server {
    least_conn;
    keepalive 512;
    server 192.168.99.103:32778 max_fails=5 fail_timeout=30s weight=1;

}

来自 Nginx 的错误消息

2016/02/22 03:54:13 [emerg] 242#242: invalid host in upstream "http://database_server" in /etc/nginx/conf.d/streams/database_server.conf:9

问题是“http://database_server” 这是一个 tcp 流,所以你只需要 proxy_pass database_server

另外,keep alive 不是进入 tcp 上游服务器的指令

这是一个适合我的 nginx 配置(我是 运行 inside Docker,所以其中一些选项可以帮助解决这个问题):

worker_processes auto;

daemon off;

error_log stderr info;

events {
    worker_connections 1024;
}

stream {
    upstream postgres {
        server my_postgres:5432;
    }

    server {
        listen 5432 so_keepalive=on;
        proxy_pass postgres;
    }
}

对我来说关键是行 listen 5432 so_keepalive=on;,它打开 TCP keepalive。没有它,我可以连接,但我的连接会在几秒钟后重置。