Docker CLI Tutorial
Docker is a powerful tool for containerizing applications, making it easier to develop, deploy, and scale applications. This tutorial will guide you through installing Docker CLI, running it with Angular applications, and creating a multi-stage Dockerfile.
Installing Docker CLI Using Homebrew
To install Docker CLI on macOS, you can use Homebrew:
Update Homebrew to ensure you have the latest formulae:
brew update
Install Docker:
brew install --cask docker
After installation, launch Docker Desktop from your Applications folder or via Spotlight Search.
Verify the installation by checking the Docker version:
docker --version
Running Docker with an Angular Application
Follow these steps to containerize and run an Angular application using Docker:
Step 1: Create an Angular Application
If you don’t already have an Angular application, create one using Angular CLI:
npm install -g @angular/cli
ng new my-angular-app
cd my-angular-app
Step 2: Build the Angular Application
Build the application for production:
ng build --prod
This generates a dist
folder containing the production-ready files.
Step 3: Write a Dockerfile
Create a Dockerfile
in the root of your Angular project with the following content:
# Stage 1: Build the Angular app
FROM node:18 AS build
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . ./
RUN npm run build --prod
# Stage 2: Serve the app with Nginx
FROM nginx:alpine
COPY --from=build /app/dist/my-angular-app /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
Step 4: Build and Run the Docker Container
Build the Docker image:
docker build -t my-angular-app .
Run the container:
docker run -d -p 8080:80 my-angular-app
Access your Angular application in the browser at http://localhost:8080
.
Multi-Stage Dockerfile Example
The above Dockerfile is an example of a multi-stage build. Let’s break it down:
Stage 1: Build
- Base Image: Uses
node:18
as the base image for building the Angular app. - Working Directory: Sets
/app
as the working directory. - Dependencies: Installs dependencies using
npm install
. - Build Command: Runs
npm run build --prod
to generate the production files in thedist
directory.
Stage 2: Serve
- Base Image: Uses
nginx:alpine
, a lightweight web server image. - Copy Files: Copies the built files from the
build
stage to Nginx's default directory for static files. - Expose Port: Opens port
80
to allow access to the container. - Run Command: Starts the Nginx server.
With this setup, you’ve containerized an Angular application using Docker, making it easy to deploy and run in any environment. Happy coding!