How to Fix WebSocket Connection Error in Nginx and React on Docker

How to Fix WebSocket Connection Error in Nginx and React on Docker


2 min read

If you're running an application on Docker that uses Nginx as a reverse proxy server and React as a front-end framework, you might have encountered the following error message when trying to access the React app from the browser:

WebSocketClient.js:16 WebSocket connection to 'ws://localhost:3000/ws' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

This error occurs because the web app is trying to access ws://localhost:3000/ws, which does not exist, and Nginx is running on a different port.

To fix this error, you need to change the Nginx port to 3000, which is the same port as the React app running inside the Docker container.

You also need to add the location /ws into the Nginx configuration file and route it to the React client running in the Docker container.

Here are the steps to fix the error:

  1. Open the docker compose file and change the port mapping of the nginx to 3000 or change the script for running the nginx image to docker run -p 3000:80 <IMAGE ID / IMAGE NAME>

  2. Open the Nginx configuration file nginx.conf and add the following lines inside it. location /ws { proxy_pass http://localhost:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; } The location block defines the URL path that should be routed to the React app running on port 3000. The proxy_pass directive sets the URL to which the request should be forwarded, and the proxy_http_version and proxy_set_header directives configure the connection between Nginx and the React app.

  3. Save the configuration file, build the docker image and run the image again

  4. Now, when you try to access the React app from the browser, the error should be fixed, and the WebSocket connection should work correctly.

Note that this solution applies when the container is running locally, and it might not be necessary when running in production, such as when deploying to AWS Elastic Beanstalk.

In conclusion, the WebSocket connection error in Nginx and React on Docker can be solved by changing the Nginx port to 3000, adding the location /ws to the Nginx configuration file, and routing it to the React client running in the Docker container.

If you have any questions or concerns about this solution, please don't hesitate to leave a comment below. We'd be happy to help clarify any issues you may have. Also, if you found this post helpful, please consider giving it a like or sharing it with others who may be facing a similar issue. Thanks for reading!