一、背景
公司接了一个项目,其中一个模块使用websocket连接,但是配置过后还是不行。经过排查,最终实现了websocket的配置和验证。
配置中需要注意的是:
- 配置nginx的时候,注意是否配置了证书,以及证书是否正确。
- 使用curl 后端程序+websocket端口+websocket路径是否正确。
- 使用postman或者在线测试是否工作正常。
二、拓扑
(1)nginx
upstream ws-xxx {
server 127.0.0.1:7003 weight=2 max_fails=3 fail_timeout=20s;
}
map $http_upgrade $conn_upgrade {
default upgrade;
'' close;
}
server {
listen 80;
server_name xxx;
access_log /var/log/nginx/xxx.a.log main;
error_log /var/log/nginx/xxx.e.log;
location /ngx_status {
stub_status on;
access_log off;
}
location / {
proxy_passhttp://xxx;
proxy_redirect off;
proxy_set_headerHost $host;
proxy_set_headerX-real-ip $remote_addr;
proxy_set_headerX-Forwarded-For $proxy_add_x_forwarded_for;
}
}
server {
listen xxx ssl;
server_name xxx;
access_log /var/log/nginx/xxx main;
error_log /var/log/nginx/xxxe.log;
ssl_certificate /etc/nginx/cert.d/xxx;
ssl_certificate_key /etc/nginx/cert.d/xxx;
ssl_session_timeout 5m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4:!DH:!DHE;
ssl_prefer_server_ciphers on;
location / {
proxy_passhttp://xxx;
proxy_set_header Host $host;
proxy_http_version 1.1;
proxy_read_timeout 120s;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_set_header X-real-ip $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
add_header Set-Cookie "Path=/; HttpOnly; Secure";
if ($request_uri ~* "css$|js$|png$|jpg$") {
add_header Cache-Control max-age=86400;
}
}
location /ws {
proxy_pass http://xxx;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connetion $conn_upgrade;
}
}
(2)后端程序
使用curl本地测试后端服务程序正常。
[root@xxx-test]# curl 192.168.177.66:2301/ws
not a WebSocket handshake request: missing upgrade
(3)frpc
使用frpc打通内网websocket端口到带有公网ip地址的公网服务器。
serverAddr = "xxx"
serverPort = 7000
[[proxies]]
name = "user-comet"
type = "tcp"
localIP = "192.168.177.66"
localPort = 2301
remotePort = 7003