Search code examples
angulardocker

How to deploy Angular 17 with SSR with Docker?


Minimal Example

Setting up a new Angular 17 project (Node 18) as follows:

$ npm install -g @angular/cli@17
$ ng update @angular/core@17 @angular/cli@17
$ npm update

$ ng new example
stylesheets? $ SCSS
SSR? $ yes
$ cd example
$ ng serve

Connects just fine on localhost:4200.

Deploying it with Docker does not work, because all the example Dockerfiles expect older Angular versions without SSR.

Seriously, guys. Before giving an answer try actually creating an Angular 17 SSR project and try if it works with your Dockerfile.

Docker Failures

I tried following these suggestions (remember to replace as necessary e.g.the node version node:12-slim by node:18-slim, the project name sample-angular-app by the project name example, doing the ports correctly etc.):


Solution

  • Dockerfile

    FROM node:18-alpine as build
    WORKDIR /app/src
    COPY package*.json ./
    RUN npm ci
    COPY . ./
    RUN npm run build
    
    FROM node:18-alpine
    WORKDIR /usr/app
    COPY --from=build /app/src/dist/PROJECT_NAME ./
    CMD node server/server.mjs
    EXPOSE 4000
    

    Docker invocation

    docker build . -t PROJECT_NAME -f Dockerfile
    docker run -d PROJECT_NAME -p 8080:4000
    

    Notes

    • Replace PROJECT_NAME by the project name.
    • Need to use node:18 to support Angular 17.
    • Need to copy from dist/PROJECT_NAME/server to get the version that can be served.
    • Need to serve server.mjs, there is no server.js.
    • Need to make sure the ports are mapped correctly.
    • 4000 is the default port set in server.ts, see the line const port = process.env['PORT'] || 4000; in there. Of course one can define another port either by editing the server.ts or setting the PORT environment variable, but I kept it simple here.
    • 8080 is the port where one can see the project in the browser at http://localhost:8080/.