Dockerfile Multi-Stage Paling Masuk Akal Buat Nyelametin Storage VPS

175 words • 1,130 chars Markdown
Raw

Dockerfile Multi-Stage Anti-Bengkak

Ngapain lu deploy image Docker ukurannya sampe 2GB cuma buat nge-run app Node.js atau Go doang? Mau numpukin disk VPS kantor lu yang pas-pasan itu? Nih pake multi-stage build. Biar artifact sampah sisa nge-build nggak ikut nongkrong di production.

Snippet Dockerfile Node.js Praktis

# Stage 1: Build
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

# Stage 2: Production
FROM node:20-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production

COPY package*.json ./
RUN npm ci --only=production

-- Bawa hasil compile aja bray, jangan bawa node_modules development --
COPY --from=builder /app/dist ./dist

USER node
EXPOSE 3000
CMD ["node", "dist/index.js"]

Kenapa Harus Begini?

  • Image Ramping: Ukuran image akhir jauh lebih kecil karena nggak bawa compiler, devDependencies, dan cache npm yang nggak penting.
  • Security Aman: Pake non-root user (USER node) biar kalau app lu kena inject, hacker nggak langsung jadi root di dalem container.
  • Tidur Nyenyak: Pull/push image ke registry pas CI/CD jadi sat-set, nggak ngabisin kuota internet server.