In this Dockerfile
below, I’ve added comments to explain each step clearly. This makes it easier for readers to understand the purpose of each stage and the reasoning behind the image choices.
# Stage 1: Build Adonisjs application
FROM node:20-alpine as builder
WORKDIR /app
# Copy package.json and package-lock.json
COPY ./package.json ./
COPY ./package-lock.json ./
# Install dependencies
RUN npm ci
# Copy the entire application
COPY ./ ./
# Build Adonisjs app
RUN node ./ace build --production
# Stage 2: Run Adonisjs application
FROM gcr.io/distroless/nodejs20-debian11:nonroot
ENV NODE_ENV production
WORKDIR /app
# Copy the built app from the builder stage
COPY --from=builder /app/build /app/build
# Expose the app on port 3333
EXPOSE 3333
# Command to run the Adonisjs app
CMD [ "node", "/app/build/server.js" ]
In the provided Dockerfile, two distinct stages are employed to facilitate the building and running of the Adonisjs application.
Builder Stage (node:20-alpine
):
- The choice of
node:20-alpine
as the builder stage is driven by the necessity to build the Adonisjs application initially. - Adonisjs applications typically require a two-stage setup, the first being the build stage.
- In this context, the builder stage is designated to handle the build process.
Runner Stage (gcr.io/distroless/nodejs20-debian11:nonroot
):
- The runner stage utilizes
distroless debian
withnodejs20 nonroot
. - This choice is guided by the specific needs of the application:
- Unnecessary default features from Debian (e.g., ssh, bash, curl) are excluded for a more streamlined and secure image.
- The application uses port
3333
, avoiding the need for root access as ports below1024
require elevated permissions.
Build Process in the Builder Stage:
- The
package.json
andpackage-lock.json
are initially copied to the working directory (workdir
), and the dependencies are installed to eliminate any potential caching issues, even with the use ofnpm ci
. - The entire application content is then copied.
- The Adonisjs app is built with the command
RUN node ./ace build --production
.
Transition to the Runner Stage:
- Upon a successful build, the transition to the second stage occurs.
- All files from the builder stage are copied to the runner stage.
Final Configuration and Execution:
- The application is configured to run on port
3333
, which is exposed for external access. - The Adonisjs app is launched using the command
CMD ["node", "/app/build/server.js"]
.
This multi-stage Dockerfile is thoughtfully crafted for security, efficiency, and clarity, ensuring a robust containerized environment for the Adonisjs application.