Dockerfile Yazımı

Kendi Docker image'larınızı oluşturma

Dockerfile Nedir?

Dockerfile, Docker image oluşturmak için kullanılan talimat dosyasıdır. Her satır bir katman (layer) oluşturur.

Temel Talimatlar

TalimatAçıklamaÖrnek
FROMBase imageFROM node:18-alpine
WORKDIRÇalışma diziniWORKDIR /app
COPYDosya kopyalaCOPY . .
ADDDosya ekle (URL, tar)ADD app.tar.gz /app
RUNKomut çalıştırRUN npm install
CMDVarsayılan komutCMD ["npm", "start"]
ENTRYPOINTGiriş noktasıENTRYPOINT ["python"]
EXPOSEPort belirtEXPOSE 3000
ENVEnvironment variableENV NODE_ENV=production
ARGBuild-time variableARG VERSION=1.0
VOLUMEVolume noktasıVOLUME /data
USERKullanıcı değiştirUSER node
HEALTHCHECKSağlık kontrolüHEALTHCHECK CMD curl -f http://localhost/

Node.js Uygulaması

# Dockerfile
FROM node:18-alpine

# Çalışma dizini
WORKDIR /app

# Bağımlılıkları önce kopyala (cache optimizasyonu)
COPY package*.json ./

# Bağımlılıkları yükle
RUN npm ci --only=production

# Uygulama kodunu kopyala
COPY . .

# Port
EXPOSE 3000

# Ortam değişkeni
ENV NODE_ENV=production

# Başlatma komutu
CMD ["node", "server.js"]

Python Uygulaması

FROM python:3.11-slim

WORKDIR /app

# System dependencies
RUN apt-get update && apt-get install -y \
    gcc \
    && rm -rf /var/lib/apt/lists/*

# Python dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Application code
COPY . .

EXPOSE 8000

CMD ["gunicorn", "--bind", "0.0.0.0:8000", "app:app"]

PHP/Laravel Uygulaması

FROM php:8.2-fpm

# Extensions
RUN apt-get update && apt-get install -y \
    git zip unzip libpng-dev libonig-dev libxml2-dev \
    && docker-php-ext-install pdo_mysql mbstring exif pcntl bcmath gd

# Composer
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer

WORKDIR /var/www

COPY . .

RUN composer install --optimize-autoloader --no-dev

RUN chown -R www-data:www-data /var/www/storage /var/www/bootstrap/cache

EXPOSE 9000

CMD ["php-fpm"]

Multi-Stage Build

# Build aşaması
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

# Production aşaması
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
Multi-stage build, final image boyutunu dramatik şekilde küçültür. Build araçları son image'da bulunmaz.

Image Oluşturma

# Basit build
docker build -t myapp .

# Tag ile
docker build -t myapp:1.0 .

# Farklı Dockerfile
docker build -f Dockerfile.prod -t myapp:prod .

# Build arg ile
docker build --build-arg VERSION=2.0 -t myapp .

# Cache kullanmadan
docker build --no-cache -t myapp .

Best Practices

  • Alpine veya slim base image kullanın
  • Layer'ları birleştirin (RUN komutlarını && ile)
  • .dockerignore kullanın
  • Root olmayan kullanıcı kullanın
  • HEALTHCHECK ekleyin
  • Multi-stage build kullanın