本文介绍如何通过 Nginx 实现对 Redis 服务的反向代理。此配置适用于需要通过 Nginx 来代理 Redis 服务的场景。
第一步:Redis 配置及启动
编辑
redis.conf
文件,配置 Redis 服务:vim redis.conf
配置内容示例:
port 6379 # 取消绑定本地地址 # bind 127.0.0.1 daemonize yes requirepass test1234
启动 Redis 服务:
redis-server /software/redis-5.0.5/redis.conf
验证 Redis 服务是否启动成功:
ps -ef | grep redis
示例输出:
root 2081 1 0 09:23 ? 00:00:07 redis-server *:6379
第二步:安装 Nginx 并配置反向代理
配置并安装 Nginx:
./configure --with-stream # 添加 stream 模块 make && make install
备份并清理 Nginx 配置文件:
mv /usr/local/nginx/conf/nginx.conf /usr/local/nginx/conf/nginx.conf.bak grep -vE '^#|^$|^ #|^ #' /usr/local/nginx/conf/nginx.conf.bak > /usr/local/nginx/conf/nginx.conf
编辑 Nginx 配置文件
nginx.conf
:vim /usr/local/nginx/conf/nginx.conf
配置内容示例:
worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; server { listen 80; server_name localhost; location / { root html; index index.html index.htm; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } } stream { # stream 模块配置与 http 模块在相同级别 upstream redis { server 127.0.0.1:6379 max_fails=3 fail_timeout=30s; } server { listen 16379; proxy_connect_timeout 1s; proxy_timeout 3s; proxy_pass redis; } }
第三步:验证配置
端口验证:
netstat -ntlp | grep -E 'nginx|redis'
示例输出:
tcp 0 0 0.0.0.0:16379 0.0.0.0:* LISTEN 13041/nginx: master tcp 0 0 0.0.0.0:6379 0.0.0.0:* LISTEN 13253/redis-server tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 13041/nginx: master tcp6 0 0 :::6379 :::* LISTEN 13253/redis-server
连接验证:
redis-cli -h 127.0.0.1 -p 16379
在 Redis CLI 中验证身份:
127.0.0.1:16379> auth "test1234" OK
以上步骤完成后,Nginx 已成功配置为 Redis 的反向代理服务,并通过验证测试。