user796446
user796446

Reputation:

How to handle browser reload in Docker containerized Angular application?

If I run ng serve on my local machine the application functions as expected when browser is reloaded.

I am now trying to create a docker container for this app.

My docker file is as follows:

FROM node:16.13.0-alpine as builder
COPY . /app
WORKDIR /app
RUN npm install
RUN npm run build

FROM nginx:1.17.10-alpine
EXPOSE 80
COPY --from=builder /app/dist/web-client /usr/share/nginx/html

After running docker build -t web-client-docker . I get a success message.

I then run docker run -p 80:80 web-client-docker

Navigating to http://localhost redirects to http://localhost/home as expected.

However, if I then reload the page I get error that the page is not found. But this works as expected locally.

[error] 9#9: *1 open() "/usr/share/nginx/html/home" failed (2: No such file or directory), client: 172.17.0.1, server: localhost, request: "GET /home HTTP/1.1", host: "localhost"

Here is the Angular Routes object.

const routes: Routes = [
  {
    path: '',
    redirectTo: 'home',
    pathMatch: 'full',
  },
  {
    path: '',
    component: LayoutComponent,
    children: [
      {
        path: 'home',
        loadChildren: () => import('./home/home.module').then(m => m.HomeModule)
      },
      {
         path: 'training',
         loadChildren: () => import('./training/training.module').then(m => m.TrainingModule)
      },
      { path: '**', redirectTo: 'home'}
    ]
  },
];

Upvotes: 0

Views: 244

Answers (1)

akop
akop

Reputation: 7865

You need a special config for nginx. Angular expecting that all missing files will be redirected to index.html.

See Angular Deployment - Server config. There is also an example-config.

Offtopic

You can reduce your buildtime with docker-layer-caching. It should looks like this:

FROM node:16.13.0-alpine as builder
WORKDIR /app

# own layer for package.json and npm-install
# so if nothing changed in there, docker will pickup a cached layer
# it will works better with package-lock.json and "npm ci"
COPY package.json ./
RUN npm install

# and now copy your app
COPY . /app
RUN npm run build

FROM nginx:1.17.10-alpine
EXPOSE 80
COPY --from=builder /app/dist/web-client /usr/share/nginx/html

Upvotes: 1

Related Questions