Angular/sockjs through docker+nginx doesn't work

Viewed 125

I run angular on Linux using the following command: ng serve --host 0.0.0.0 app

[WDS] Live Reloading works well.

But when I try to place angular in docker with proxying nginx, Live Reloading stops working because of the websocket-connection failure: "GET /sockjs-node/034/gdu0ifc0/websocket HTTP/1.1" 499 (WebSocket is closed before the connection is established)

Here is my nginx configuration:

map $http_upgrade $connection_upgrade {
    default upgrade;
    '' close;
}

server {
    listen 80;
    server_name app.local;

    location ~* ^/sockjs-node/[0-9]+/[A-Za-z0-9]+/websocket {
        resolver 127.0.0.1 valid=30s;
        set $front_host http://app_1.localnet;
        proxy_pass $front_host:4200;


        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_set_header Host $host;
    }

    location / {
        try_files $uri @proxyapp;
    }

    location @proxyapp {
        resolver 127.0.0.11 ipv6=off;
        set $dev_container http://app_1.localnet;
        proxy_pass $dev_container:4200;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header Forwarded "";
    }
}

I used a lot of config instructions to fix it, but nothing works...

What am I doing wrong?)

1 Answers

Your websocket-connection failure happens because web sockets use two HTTP headers (Connection and Upgrade).

Add 'proxy_set_header Upgrade $http_upgrade;' and 'proxy_set_header Connection $http_connection;' to your nginx config:

location @proxyapp {
        resolver 127.0.0.11 ipv6=off;
        set $dev_container http://app_1.localnet;
        proxy_pass $dev_container:4200;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $http_connection;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header Forwarded "";
    }

Edit:

Try remove everything and use:

location / {
        proxy_pass       http://localhost:4200;
        proxy_set_header Upgrade    $http_upgrade;
        proxy_set_header Connection $http_connection;
        proxy_set_header Host       $host;
    }

Furthermore, run your app with:

ng serve --public-host 0.0.0.0 app

Related