Dockerfile Templates for Angular Framework
This guide helps you create appropriate Dockerfiles for Angular-based projects.
Key Points for All Dockerfiles
- Using official Node.js images
- Creating a non-root user for enhanced security
- Using environment variables for greater flexibility
- Optimization for Angular CLI and related tools
FROM node:$node_version as build
ARG UID=1000
ARG GID=1000
RUN groupadd -g $GID -o app && \
useradd -g $GID -u $UID -mr -d /home/app -o -s /bin/bash app
USER app
WORKDIR /home/app
COPY --chown=app:app package*.json /home/app/
RUN npm install
COPY --chown=app:app . /home/app/
RUN npm run build --prod
FROM nginx:$nginx_version as production
COPY --from=build /home/app/dist/*app-name*/ /usr/share/nginx/html/
RUN echo 'server {\n\
listen 80;\n\
server_name _;\n\
location / {\n\
root /usr/share/nginx/html;\n\
try_files $uri $uri/ /index.html;\n\
}\n\
location /index.html {\n\
root /usr/share/nginx/html;\n\
expires 0d;\n\
add_header Cache-Control "no-store, no-cache, must-revalidate";\n\
}\n\
}' > /etc/nginx/conf.d/default.conf
info
- This Dockerfile uses a multi-stage structure: build stage and production stage.
- In the build stage, the Angular project is compiled using
ng build --prod
. - In the production stage, built files are transferred to an Nginx server.
- Nginx configuration is set up to support Angular routing and Single Page Application (SPA).
caution
- Replace
$node_version
with your desired Node.js version. - Replace
$nginx_version
with your desired Nginx version. - Replace
*app-name*
with your Angular project name. - Ensure that Angular CLI is installed either globally or in project dependencies.
Building and Running the Dockerfile
To build the Dockerfile and create an image, use the command:
docker build -t [ProjectName] .
- -t: Giving a specific tag and name for the project
And then to run it:
docker run -p outport:80 --name=container-name -d [ProjectName]
- -p: Setting port for running the project
- outport: External port
- --name: Setting container name
- -d: Running container in detached mode
caution
- Security: Always use the latest stable versions of Node.js and Nginx.
- Optimization: Use Angular optimization techniques like ahead-of-time compilation.
- Testing: Always test your Docker image in a production-like environment before deployment.
- Caching: Use appropriate caching strategies in Nginx for improved performance.