angular – nginx does not recognize service worker implementation

  angular, docker, nginx, service-worker

Angular application has an implemented service worker: when Internet connection is lost, webpage shows almost instantly a message that indicates lost connection. Similarly, when Internet connection is restored, this message disappears.

For a quick configuration, this command is executed:

ng add @angular/pwa

For testing it, this command is executed:

http-server -c-1 -p 8080 ./dist/[nombre_proyecto]

For testing a supposed Internet connection loss, I shutdown the service.

This is the code that verifies Internet connection.

app.component.ts

export class AppComponent implements OnInit, OnDestroy {
  public connectionChecker: Subscription;

  public constructor(
    private http: HttpService,
    private methods: MethodsService,
  ) { }

  // More variables
  public ngOnInit() {
    var connectionCheckerTimer = timer(1000, 1000);
    this.connectionChecker = connectionCheckerTimer.subscribe(val => {
      this.http.checkForConnection().then(data => {
        if (this.disconnected) {
          // Shows a message on webpage
          this.methods.showMessage("Se restableció la conexión a Internet", ToastType.INFO);
        }
        this.disconnected = false;
        // Global variable for being used in other componentes.
        InternetConnection.connected = true;
      }).catch(error => {
        this.disconnected = true;
        InternetConnection.connected = false;
      });
    });
  // More init
  }
}

http.service.ts

import { HttpClient } from "@angular/common/http";
export class HttpService {
  constructor(
    private http: HttpClient,
  ) { }
  public checkForConnection(): Promise<any> {
    // When Internet connection is lost, this file is removed
    return this.http.get("./ngsw.json").toPromise();
  }
  // More methods
}

When the application is dockerized whit Nginx, it does not show "Internet connection lost" message.

Dockerfile

### STAGE 1 ###
FROM node:12.7-alpine AS build
WORKDIR /usr/src/app
COPY package.json package-lock.json ./
RUN npm install
COPY . .
RUN npm run build

### STAGE 2: Run ###
FROM nginx:1.17.1-alpine
COPY nginx.conf /etc/nginx/nginx.conf
COPY --from=build /usr/src/app/dist/[nombre_proyecto] /usr/share/nginx/html

nginx.conf

events{}
http {
    include /etc/nginx/mime.types;
    server {
        listen 80;
        server_name localhost;
        root /usr/share/nginx/html;
        index index.html;
        location / {
            try_files $uri $uri/ /index.html;
        }
    }
}

Why Internet connection checker method is not working on Nginx? In any case, which Docker image must be used rather than Nginx for deploying Angular project and working with service worker for executing verification method correctly?

Source: Docker Questions

LEAVE A COMMENT