Search code examples
node.jsangulardockernginxdeployment

My dockerfile for deploying my angular app doesnt start the app using a web server either nodeJs or nginx


i have finished my work on an angular project and i need to deploy it using docker , i followed the instructions and made sure that the dockerfile is correct using multiple sources . i tried to use either nginx or nodejs but it doesnt work(for nginx it shows me the default page of nginx server).

for the builder its ' "builder": "@angular-devkit/build-angular:application", ' and for the version of the project version i am using: Angular CLI: 17.3.8 Node: 20.15.1 .

here is the dockerfile i use righ now to create the image:

# Stage 1: Build Angular application
FROM node:latest as build

WORKDIR /app

COPY package*.json ./

RUN npm install

RUN npm install -g @angular/cli

COPY . .

RUN ng build --configuration=production

# Stage 2: Serve Angular application with Nginx
FROM nginx:latest

COPY --from=build /app/dist/projet-daret /usr/share/nginx/html

EXPOSE 80

this is my docker-compose:

     version: '3.8'
    services:
      angular-app:
        build: .
        ports:
          - "4300:80"
      nginx:
        image: nginx:latest
        ports:
          - "4300:80"
        volumes:
          - ./nginx.conf:/etc/nginx/nginx.conf
        depends_on:
          - angular-app

Note: i have a Dockerfile for a version that uses nodejs as web server.

when i use the docker with just the angular app and run it with ng serve it works fine, but when i use nginx or nodejs it doesn't run the angular app, i tried multiple modifications i could find for the docker file but no result, i tried event to use compose but it yielded no result also. i am stuck right now.


Solution

  • You are using the new application builder. The folder structure is now like the following:

    dist/
      <your-app-name>/
        browser/
          index.html
          main.js
          ...
    

    However it seems like your Dockerfile is still expecting the old structure from the browser builder:

    dist/
      <your-app-name>/
        index.html
        main.js
        ...
    

    Note that there is no browser folder. You need to adjust your dockerfile to copy the browser folder:

    COPY --from=build /app/dist/projet-daret/browser /usr/share/nginx/html
    

    Additional context: For client side rendered applications, this seems unnecessary. But for server side rendered applications, there will be two folders: The browser folder with the prerendered pages, and the server folder with the NodeJS server code.

    Also make sure to configure your nginx server properly for hosting an Angular app. Apparently you don't have any config, which might be problematic. See this question: How to config nginx to run angular4 application