Keamanan Docker untuk Web Developer
Docker memberikan isolasi antara aplikasi dan host, tapi container bukan sandbox yang sempurna. Konfigurasi yang salah bisa membuka celah keamanan serius.
Risiko Keamanan Docker
- Running as root — Container yang berjalan sebagai root bisa escape ke host
- Base image vulnerable — Image yang sudah lama bisa mengandung vulnerability
- Secrets di image — Credentials yang di-copy ke image bisa diekstrak
- Exposed ports — Port yang tidak perlu terbuka memperluas attack surface
- Privileged mode — Container dengan akses penuh ke host
Dockerfile yang Aman
# BAIK: Dockerfile dengan best practices keamanan
# 1. Gunakan specific version, bukan latest
FROM node:20-alpine AS builder
# 2. Set working directory
WORKDIR /app
# 3. Copy dependency files dulu (layer caching)
COPY package*.json ./
RUN npm ci --only=production
# 4. Copy source code
COPY . .
# 5. Multi-stage build — image final lebih kecil
FROM node:20-alpine
WORKDIR /app
COPY --from=builder /app .
# 6. Buat user non-root
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
# 7. Jalankan sebagai non-root
USER appuser
# 8. Expose hanya port yang diperlukan
EXPOSE 3000
CMD ["node", "server.js"]
Secrets Management di Docker
# BURUK: secrets di Dockerfile
ENV DB_PASSWORD=secret123
# BURUK: secrets di docker-compose
environment:
- DB_PASSWORD=secret123
# BAIK: gunakan Docker secrets
docker secret create db_password ./secret.txt
# BAIK: gunakan .env file yang tidak di-commit
# docker-compose.yml
env_file:
- .env # Pastikan .env ada di .gitignore
Docker Compose Security
# docker-compose.yml
services:
app:
image: myapp:latest
# Jangan gunakan privileged mode
# privileged: true # JANGAN!
# Batasi capabilities
cap_drop:
- ALL
cap_add:
- NET_BIND_SERVICE
# Read-only filesystem
read_only: true
tmpfs:
- /tmp
# Limit resources
deploy:
resources:
limits:
cpus: "0.5"
memory: 512M
Image Scanning
# Scan image untuk vulnerability
docker scout cves myapp:latest
# Trivy — open source scanner
trivy image myapp:latest
# Snyk container
snyk container test myapp:latest
Best Practices
- Selalu run as non-root user
- Gunakan specific version tags, bukan latest
- Gunakan multi-stage builds untuk image lebih kecil
- Scan images untuk vulnerability secara berkala
- Jangan simpan secrets di image
- Gunakan minimal base image (Alpine)