Skip to content

Commit 8c1a4a8

Browse files
committed
Refactor notes.Dockerfile for multi-stage build and improved security:
- Separate stages for building dependencies and runtime. - Add non-root `node` user and `NODE_ENV=production` for enhanced container security. - Optimize installation of production-only dependencies.
1 parent 16bf5de commit 8c1a4a8

1 file changed

Lines changed: 21 additions & 13 deletions

File tree

notes.Dockerfile

Lines changed: 21 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,31 @@
1-
FROM node:22.20-alpine3.22
1+
# syntax=docker/dockerfile:1
22

3+
# Build stage: install only production dependencies
4+
FROM node:22.20-alpine3.22 AS builder
5+
WORKDIR /app
6+
COPY package*.json ./
7+
# Install reproducible, production-only deps and clean cache
8+
RUN npm ci --only=production && npm cache clean --force
9+
10+
# Runtime stage: minimal image, non-root user
11+
FROM node:22.20-alpine3.22 AS runner
312
# Install wget for health checks
413
RUN apk add --no-cache wget
5-
6-
# Set the working directory inside the container
14+
ENV NODE_ENV=production
715
WORKDIR /app
816

9-
# Copy package.json and package-lock.json if they exist
10-
COPY package*.json ./
17+
# Copy only production dependencies from builder
18+
COPY --from=builder --chown=node:node /app/node_modules ./node_modules
1119

12-
# Install the dependencies
13-
RUN npm install
20+
# Copy the application code to the container (only what's needed to run)
21+
COPY --chown=node:node src/notes-api-server.js .
22+
COPY --chown=node:node src/public ./public
23+
COPY --chown=node:node src/db ./db
24+
COPY --chown=node:node src/models ./models
25+
COPY --chown=node:node src/routes ./routes
1426

15-
# Copy the application code to the container
16-
COPY src/notes-api-server.js .
17-
COPY src/public ./public
18-
COPY src/db ./db
19-
COPY src/models ./models
20-
COPY src/routes ./routes
27+
# Drop privileges to non-root user provided by the Node image
28+
USER node
2129

2230
# Expose the port the Express server will run on
2331
EXPOSE 3000

0 commit comments

Comments
 (0)