Webpack Dev Server with NGINX proxy_pass

23,724

Proxy pass should be ip and port of your webpack-dev-server container and you need proxy_redirect off;

location /sockjs-node {
    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_set_header Host $host;

    proxy_pass http://node:8080; 

    proxy_redirect off;

    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
}

Also don't forget to add poll to your webpack-dev middleware

  watchOptions: {
    aggregateTimeout: 300,
    poll: 1000
  }
Share:
23,724
jshbrntt
Author by

jshbrntt

Updated on July 09, 2022

Comments

  • jshbrntt
    jshbrntt almost 2 years

    I'm trying to get webpack-dev-server running inside a Docker container then accessing it through a NGINX host. The initial index.html loads but the Web Sockets connection to the dev server cannot connect.

    VM47:35 WebSocket connection to 'ws://example.com/sockjs-node/834/izehemiu/websocket' failed: Error during WebSocket handshake: Unexpected response code: 400

    I'm using the following config.

    map $http_upgrade $connection_upgrade {
      default upgrade;
      ''      close;
    }
    
    upstream webpack_dev_server {
      server node;
    }
    
    server {
      server_name _;
      listen 80;
      root /webpack_dev_server;
    
      location / {
        proxy_pass http://webpack_dev_server;
      }
    
      location /sockjs-node/ {
        proxy_pass http://webpack_dev_server/sockjs-node/;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;  # pass the host header - http://wiki.nginx.org/HttpProxyModule#proxy_pass
    
        proxy_http_version 1.1;  # recommended with keepalive connections - http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_http_version
    
        # WebSocket proxying - from http://nginx.org/en/docs/http/websocket.html
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
      }
    }
    
  • JoelParke
    JoelParke about 7 years
    I worked on this some more in the case of a HTTPS server and had some issues, and solved them and posted the answer here: stackoverflow.com/questions/43081342/… which will be helpful for others that pass though this post.
  • Paweł Szczur
    Paweł Szczur over 3 years
    I've run a similar problem (nx.dev + React + nginx) and proxy_redirect is not necessary. What's even more it may be wrong and cause invalid redirects.