Before multi-stage build, developers used to maintain two dockerfiles (i.e. Dockerfile.dev and Dockerfile.prod) to build and deploy an application. But it is hard to maintain and it may increase image size also.
In the last two previous articles, we created two Dockerfiles and docker-compose yml files to generate dist folder and service application using Nginx respectively.
With help of multi-stage builds, we can create a single Dockerfile to build and serve an angular application
- Create new scaffolding angular application using ng new command
- Validate folder structure as per below image in the host machine
- Set default host for ng serve in package.json file
- Configure Dockerfile with below instructions
- set base image as "node:12.7-alpine" and stage name as "build"
- set working directory as "/usr/app"
- write command to copy package.json
- write command to run npm install
- write command to copy all files from host machine into an image
- expose Port 4200
- set CMD command to execute npm run build
- set second From base image as "nginx:1.17.1-alpine"
- copy dist folder from previous stage to nginx/html folder
- Configure "dockerangular-multistage-service" service by specifying build context as Dockerfile
- specify bindmount to /usr/app container path
- specify volume mount to /usr/app/node_modules
- Expose port 8081
8. check http://localhost:8081
Step 1:
> ng new docker-angular-multi-stage
Step 4:
"scripts": {
"start": "ng serve --host 0.0.0.0"
}
Step 5:
FROM node:12.7-alpine AS build
WORKDIR /usr/app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 4200
CMD ["npm", "run", "build"]
FROM nginx:1.17.1-alpine
COPY --from=build /usr/app/dist/docker-angular-multi-stage /usr/share/nginx/html
Step 6:
version: '3'
services:
dockerangular-multistage-service:
build: .
volumes:
- .:/usr/app
- /usr/app/node_modules
environment:
NODE_ENV: production
ports:
- 8081:80
Step 7:
> docker-compose up
we can even spin up docker containers by right click on docker-compose.yml in vscode and select "Compose up" option
Source code available under https://github.com/ramasubbareddy1224/docker-angular-multi-stage
Happy Coding :)