Nginx配置socket.io集群
最近项目中使用到了socket.io,为了保证系统的稳定性,需要进行集群。使用了nginx完成负载和反向代理。具体配置如下:
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
map $http_x_forwarded_for $clientRealIp {
"" $remote_addr;
~^(?P<firstAddr>[0-9.]+),?.*$ $firstAddr;
}
upstream nodes {
hash $clientRealIp;
server localhost:9082;
server localhost:8082;
}
server {
listen 80;
server_name localhost;
location /socket.io/ {
# 此处改为 socket.io 后端的 ip 和端口即可
proxy_pass http://nodes;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_http_version 1.1;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
}
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
此时使用ip:80,连接即可对所socket.io器进行负载。
踩坑:使用docker部署nginx时遇到了诸多问题,例如必须使用真实ip,不能使用localhost等等。