Cara Build Image yang Benar
Learn by Doing
Dockerfile adalah file teks yang berisi instruksi untuk membangun Docker image. Seperti resep:
Hasilnya: Image yang bisa dijalankan sebagai Container
# Comment
FROM ubuntu:24.04 # Base image (wajib)
LABEL maintainer="[email protected]" # Metadata
ENV VAR_NAME=value # Environment variables
WORKDIR /app # Working directory
COPY . /app # Copy files
RUN command # Execute saat build
EXPOSE 8080 # Dokumentasi port
ENTRYPOINT ["cmd"] # Entry point
CMD ["arg"] # Default arguments
Setiap Dockerfile harus dimulai dengan FROM. Ini adalah fondasi image kamu.
FROM ubuntu:24.04 # Ubuntu LTS
FROM python:3.11-slim # Python + slim OS
FROM node:20-alpine # Node.js + Alpine (paling kecil)
FROM nginx:alpine # Nginx web server
FROM postgres:16 # PostgreSQL database
:latest
RUN menjalankan perintah saat proses build image.
# Install packages
RUN apt-get update && apt-get install -y nginx
# Install Python packages
RUN pip install flask gunicorn
# Install Node packages globally
RUN npm install -g pm2
# Create directory
RUN mkdir -p /app/logs
Menyalin file dari build context ke dalam image.
COPY source destination
COPY package*.json /app/ # Copy file matching pattern
COPY requirements.txt . # Current dir ke workdir
COPY . /app/ # Copy semua file
WORKDIR /app
WORKDIR /var/www/html
ENV NODE_ENV=production
ENV PORT=3000
EXPOSE 80
EXPOSE 3000 8080
| Instruction | Purpose | Use Case |
|---|---|---|
CMD |
Default command, bisa di-override | Main process |
ENTRYPOINT |
Fixed entry point, args di-append | Always executable |
# CMD - bisa dioverride
CMD ["python", "app.py"]
# docker run image custom.py <- runs custom.py
# ENTRYPOINT - appends args
ENTRYPOINT ["python", "app.py"]
# docker run image --debug <- runs app.py --debug
Kurangi ukuran image dengan menggunakan beberapa stage.
# 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
WORKDIR /app
COPY --from=builder /app/dist ./dist
CMD ["node", "dist/index.js"]
Exclude file yang tidak perlu dari build context.
.git
node_modules
*.log
.env
.DS_Store
__pycache__
*.md
vendor/
dist/
build/
*.tar.gz
docker build -t myapp:latest .
docker build -t myapp:1.0 .
docker build -f Dockerfile.prod -t myapp:prod .
docker run -d -p 8080:80 myapp:latest
docker run -d -p 8080:80 -e NODE_ENV=production myapp:latest
docker run -d -p 8080:80 -v $(pwd):/app myapp:latest
-d - Detached (background)-p - Port mapping-e - Environment variable-v - Volume mount--name - Container name