Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Nginx Docker 404

Been driving myself nuts trying to figure this out.

I have a very simple Angular project with routing, below is the app.module.ts, nginx.conf and docker file.

I start up by container

docker run --rm -d -p 80:80/tcp demo:latest

browse to http://localhost and site works all routes render

If I am on http://localhost/contact and refresh page or type Url in directly I get 404 from Nginx.

The nginx.conf has try_files $uri /index.html; this is what all the posts with similar issues have said needs to be set.

Any idea what I am doing wrong.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { ContactComponent } from './contact/contact.component';
import { AboutComponent } from './about/about.component';

const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'contact', component: ContactComponent },
  { path: 'about', component: AboutComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}

nginx.conf

server {
    listen   80;

    root /usr/share/nginx/html;
    index index.html;

    server_name _;

    location / {
        try_files $uri /index.html;
    }
}

dockerfile

FROM nginx

COPY nginx.conf /etc/nginx/conf.d/

RUN rm -rf /usr/share/nginx/html/*

COPY ./dist /usr/share/nginx/html
like image 881
Mike U Avatar asked May 26 '19 23:05

Mike U


2 Answers

Use { "useHash" : true } in AppRoutingModule.

imports: [RouterModule.forRoot(routes , {useHash : true } )]

When you put 34.**.**.**:8080/anyroute, Nginx will search is that route available in his server, not in angular app. That's why the 404 error occurs.. using useHash true , it will automatically format your url with a hash.

34.**.**.**:8080/#/anyroute

Nginx will not read after # It will redirected to your app

like image 192
Yasiru Sandeeptha Avatar answered Sep 28 '22 03:09

Yasiru Sandeeptha


Silly me, I was not overwriting the default docker conf in the docker file

COPY nginx.conf /etc/nginx/conf.d/default.conf
like image 45
Mike U Avatar answered Sep 28 '22 04:09

Mike U