Issue
I'm facing a trouble while deploying a fullstack app into AWS EC2 instance.
I have my backend node.js app running on port 5000 I have my frontend Angular app handled by nginx on port 80 Both on the same instance.
I have managed to allow basics http calls but I didn't find the way to allow ws connection between my front and my backend.
Following code is the part I added in my nginx.conf file, in a server block, to allow communication between the 2 apps :
listen 80;
listen [::]:80;
server_name _;
#FRONTEND angular files
location / {
root /my_frontend_folder_path;
}
#BACKEND node/express proxy redirects
location /api/ {
proxy_pass http://localhost:5000/;
}
location /ws/ {
proxy_pass http://localhost:5000/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
}
Angular side, here is how I connect to my websocket :
this.socket = new WebSocket(ws://localhost:5000/ws);
this.socket.onopen = () => {
console.log('WebSocket connection established.');
};
It works perfectly in my local machine but I got a "Connection refused" when I try to access it in my deployed app.
Apparently, the closest question I found here wasn't answered
I've tried different nginx conf that I found on web but none allows me to have a working service.
My expectation is to be able to connect to my websocket from my frontend hosted in the same instance.
EDIT : Finally I'm able to connect to my WS by changing his url client-side. I use the public IP address of my instance, I don't like this way but for now I just want to progress. But just after the connection is established successfully, it immediately closes with following error :
CloseEvent
bubbles: false
cancelBubble: false
cancelable: false
code: 1005
composed: false
currentTarget: null
defaultPrevented: false
eventPhase: 0
isTrusted: true
reason: ""
returnValue: true
srcElement: WebSocket {}
target: WebSocket {}
timeStamp: 482
type: "close"
wasClean: true
Any help would be very appreciated <3
Solution
Finally, I've found where was MY mistake...
nginx was "eating" a part of my url, so I've just added a '/ws' in my url...
this.socket = new WebSocket(ws://<INSTANCE_PUBLIC_IP>/ws/<NORMAL_WS_SERVER_ENDPOINT>);
Hope my brainless issue will help someone in the future xD
Answered By - Estema Answer Checked By - David Goodson (WPSolving Volunteer)