This blog post shows multi stage Dockerfile that builds and deploys Angular app in Nginx container
The above Dockerfile has 2 stages
Stage 1 - Install NPM dependencies and builds Angular project
Stage 2 - Builds docker image from dist directory generated by previous stage
- We use Node 16 alpine image to build the project and it accepts CONFIGURATION build argument. You can override this during build based on your environment
docker build --build-arg CONFIGURATION=dev .
and you can also define as many arguments as you like
- Then make
/appas working directory. All of the source code and files will be copies to /app directory inside Node container
- Copy the package.json file to /app directory. This will enable Docker to cache the node_modules rather than building from scratch and sub sequent builds use these when package.json file is unchanged.
COPY package.json .
- Install dependencies using npm install command and specify flag
—-legacy-peer-depsto prevent build errors in NPM 7+
RUN npm install --legacy-peer-deps
- Then copy the source code and build the project using npm run build
COPY . . RUN npm run build -- --output-path=dist --configuration=$CONFIGURATION --output-hashing=all
- The built code will be present in
/app/distdirectory in Node container
We use NgInx alpine stable image to serve Angular application in production
Remove existing HTML content using the command
RUN rm -rf /usr/share/nginx/html/*
- Copy the Nginx config file from source to
/etc/nginx/nginx.confdirectory. If you don’t have one, you can use the below one
- Then Copy dist folder from build stage to nginx public folder
COPY — from=builder /app/dist /usr/share/nginx/html
- At the end specify the NgInx start command. That’s it.
You can also split Stage 1 into two separate stages. One to install dependencies and the second one to build the Angular app :)