简体   繁体   中英

Unable to get socket.io to work in production using Laravel Echo Server and Nginx with HTTPS

I am having trouble getting my Laravel Echo Server to work in a staging/production environment. It works great in my local but not sure why I can't get things going on my Debian 10 VPS. Here is my configuration.

I have no firewall configured yet so there should be no issue with ports being blocked

What I see in the browser console

GET https://dev.domain.com:6001/socket.io/?EIO=3&transport=polling&t=NGLF-O_ net::ERR_CONNECTION_TIMED_OUT

Services are running via Supervisor

root@vultr:/var/www/html/website/storage/logs# supervisorctl status
echo-sever:echo-sever_00           RUNNING   pid 28148, uptime 0:22:44
laravel-worker:laravel-worker_00   RUNNING   pid 28140, uptime 0:22:44
laravel-worker:laravel-worker_01   RUNNING   pid 28141, uptime 0:22:44
laravel-worker:laravel-worker_02   RUNNING   pid 28142, uptime 0:22:44
laravel-worker:laravel-worker_03   RUNNING   pid 28143, uptime 0:22:44
laravel-worker:laravel-worker_04   RUNNING   pid 28144, uptime 0:22:44
laravel-worker:laravel-worker_05   RUNNING   pid 28145, uptime 0:22:44
laravel-worker:laravel-worker_06   RUNNING   pid 28146, uptime 0:22:44
laravel-worker:laravel-worker_07   RUNNING   pid 28147, uptime 0:22:44
peerjs-sever:peerjs-sever_00       RUNNING   pid 28149, uptime 0:22:44

Output of Laravel Echo Log

L A R A V E L  E C H O  S E R V E R

version 1.6.2

⚠ Starting server in DEV mode...

✔  Running at localhost on port 6001
✔  Channels are ready.
✔  Listening for http events...
✔  Listening for redis events...

Server ready!

NGINX CONFIG

server { 

    #only use default_server if only its the only site running
    listen 80 default_server; 
    listen [::]:80 default_server; 
    
    root /var/www/html/website/public; 
    index index.php index.html index.htm index.nginx-debian.html; 
    server_name dev.domain.com; 
    
    location / { 
        try_files $uri $uri/ /index.php?$query_string;
    } 
    
    location ~ \.php$ { 
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php7.4-fpm.sock; 
    }

    location ~* \.io {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forward-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy false;

        proxy_pass http://localhost:6001;
        proxy_redirect off;

        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
    location ~ /\.ht { 
        deny all; 
    }

    listen [::]:443 ssl ipv6only=on; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/dev.domain.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/dev.domain.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}

laravel-echo-server.json

{
        "authHost": "https://dev.domain.com",
        "authEndpoint": "/broadcasting/auth",
        "clients": [
            {
                "appId": "my-app-id",
                "key": "my-app-key"
            }
        ],
        "database": "redis",
        "databaseConfig": {
            "redis": {
                "host": "my-redis-ip",
                "port": "6379",
                "password": "my-redis-pass"
            },
            "sqlite": {
                "databasePath": "/database/laravel-echo-server.sqlite"
            }
        },
        "devMode": true,
        "host": null,
        "port": "6001",
        "protocol": "https",
        "socketio": {},
        "secureOptions": 67108864,
        "sslCertPath": "/etc/letsencrypt/live/dev.domain.com/fullchain.pem",
        "sslKeyPath": "/etc/letsencrypt/live/dev.domain.com/privkey.pem",
        "sslCertChainPath": "",
        "sslPassphrase": "",
        "subscribers": {
            "http": true,
            "redis": true
        },
        "apiOriginAllow": {
            "allowCors": true,
            "allowOrigin": "https://dev.domain.com",
            "allowMethods": "GET, POST",
            "allowHeaders": "Origin, Content-Type, X-Auth-Token, X-Requested-With, Accept, Authorization, X-CSRF-TOKEN, X-Socket-Id"
        }
    }

SNIPPET of relevant APP.JS

import Echo from "laravel-echo";
    window.io = require("socket.io-client");
    window.Echo = new Echo({
        broadcaster: "socket.io",
        host: "https://dev.domain.com:6001"
    });

EDIT:

Forgot to mention, not sure if this is relevant, but I am using Cloudflare with SSL encryption set to FULL and I'm using LetsEncrypt to generate the certificate on the server which can be seen in my Nginx configuration

Not sure what the problem is, but I found a solution. I've updated a lot: Nginx to 1.19.1, possibly installed additional modules. Installed npm not globally, but locally. And at some point, it started working as it should. I still don't understand what's the matter)

Note: this only works if you write location /socket.io.

YES,,!!!, i made this working, i am using aws lightsail and in the networking section all you need to do is to allow that port to work, 在此处输入图像描述

Here is some of the configuration which I've used to make it work,

resources/js/bootstrap.js

window._ = require('lodash');

window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
window.axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
window.axios.defaults.headers.common.crossDomain = true;
window.axios.defaults.baseURL = '/';
let token = document.head.querySelector('meta[name="csrf-token"]');


if (token) {
    window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
    console.error('CSRF token not found: https://adonisjs.com/docs/4.1/csrf');
}

/**
 * We'll load the axios HTTP library which allows us to easily issue requests
 * to our Laravel back-end. This library automatically handles sending the
 * CSRF token as a header based on the value of the "XSRF" token cookie.
 */

import Echo from "laravel-echo";

if (typeof window.io !== "undefined") {
    window.Echo = new Echo({
        broadcaster: "socket.io",
        host: window.location.hostname + ":6001",
        auth: {
            headers: {
                Accept: 'application/json',
                Authorization: 'Bearer ' + token
            }
        },
        wsPort: 80,
        wssPort: 443,
        disableStats: true,
        encrypted: true,
        forceTLS: true,
        transports: ['websocket', 'polling', 'flashsocket'],
        enabledTransports: ['ws', 'wss']
    });
}

blade file

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.1.2/socket.io.js"></script>
<script src="//{{ Request::getHost() }}:{{env('LARAVEL_ECHO_PORT')}}/socket.io/socket.io.js"></script>
<script src="{{ mix('/js/laravel-echo-setup.js') }}" type="text/javascript"></script>

laravel-echo-server.json

{
    "authHost": "http://ip-address-or-domain-name",
    "authEndpoint": "/broadcasting/auth",
    "clients": [],
    "database": "redis",
    "databaseConfig": {
        "redis": {},
        "sqlite": {
            "databasePath": "/database/laravel-echo-server.sqlite"
        }
    },
    "devMode": true,
    "host": null,
    "port": "6001",
    "protocol": "http",
    "socketio": {},
    "secureOptions": 67108864,
    "sslCertPath": "",
    "sslKeyPath": "",
    "sslCertChainPath": "",
    "sslPassphrase": "",
    "subscribers": {
        "http": true,
        "redis": true
    },
    "apiOriginAllow": {
        "allowCors": true,
        "allowOrigin": "http://ip-address-or-domain-name",
        "allowMethods": "GET, POST",
        "allowHeaders": "Origin, Content-Type, X-Auth-Token, X-Requested-With, Accept, Authorization, X-CSRF-TOKEN, X-Socket-Id"
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM