🐳

Docker 배포 가이드

Docker 컨테이너 배포 및 운영 가이드

📄 DOCKER_DEPLOYMENT_GUIDE.md 📏 -줄 💾 - 🌐 ad.uschool.kr

TokTak Clone - Docker & Cloud Deployment Guide

Complete guide for containerizing and deploying the TokTak Clone application using Docker and cloud platforms.

Table of Contents

  1. Prerequisites
  2. Local Development Setup
  3. Docker Architecture
  4. Development Workflow
  5. Production Deployment
  6. Cloud Deployment Options
  7. Troubleshooting
  8. Performance Optimization

Prerequisites

System Requirements

  • Docker: Version 20.10 or higher
  • Docker Compose: Version 1.29 or higher
  • Git: For version control
  • Bash/Shell: For running scripts
  • 4GB+ RAM: Minimum for comfortable development
  • 20GB+ Disk Space: For images, containers, and data

Installation

Ubuntu/Debian:

bash
# Install Docker
curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh

# Install Docker Compose
sudo curl -L "https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose

macOS (with Homebrew):

bash
brew install docker
brew install docker-compose

Verify Installation:

bash
docker --version
docker-compose --version

Local Development Setup

Initial Setup

  1. Clone Repository:
bash
git clone https://github.com/your-org/toktak-clone.git
cd toktak-clone
  1. Configure Environment:
bash
# Copy environment template
cp .env.docker .env

# Edit .env with your local settings
# Important: Update all API keys and secrets
nano .env
  1. Start Containers:
bash
# Using docker-compose
docker-compose up -d

# Or using Makefile (recommended)
make up
  1. Verify Services:
bash
make health-check

# Expected output:
# PHP Container: OK
# MySQL: OK
# Redis: OK

First Run Setup

bash
# Install dependencies
make install

# Run database migrations
make migrate

# Seed database with test data
make seed

Access Services

  • Application: http://localhost:80
  • phpMyAdmin: http://localhost:8080
  • Redis CLI: make redis
  • MySQL CLI: make mysql

Docker Architecture

Container Architecture

code
┌─────────────────────────────────────────────────────────┐
│                   Docker Network                        │
│              (toktak-network bridge)                    │
├─────────────────────────────────────────────────────────┤
│                                                         │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐ │
│  │    Nginx     │  │   PHP-FPM    │  │   MySQL      │ │
│  │  (Port 80)   │──│  (Port 9000) │  │ (Port 3306)  │ │
│  │              │  │              │  │              │ │
│  │  - Reverse   │  │ - Application│  │ - Database   │ │
│  │    Proxy     │  │   Logic      │  │   Storage    │ │
│  │  - Static    │  │ - Session    │  │              │ │
│  │    Files     │  │   Manager    │  │              │ │
│  │  - SSL/TLS   │  │              │  │              │ │
│  └──────────────┘  └──────────────┘  └──────────────┘ │
│                                                         │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐ │
│  │    Redis     │  │  phpMyAdmin  │  │   Storage    │ │
│  │  (Port 6379) │  │  (Port 8080) │  │   Volumes    │ │
│  │              │  │              │  │              │ │
│  │ - Cache      │  │ - DB Admin   │  │ - Uploads    │ │
│  │ - Sessions   │  │   Tool       │  │ - Logs       │ │
│  │              │  │              │  │ - Cache      │ │
│  └──────────────┘  └──────────────┘  └──────────────┘ │
│                                                         │
└─────────────────────────────────────────────────────────┘

Service Descriptions

ServiceImageRoleVolumes
appphp:8.2-fpm-alpinePHP applicationapp code, uploads, logs
webnginx:alpineWeb server, reverse proxypublic folder, configs
dbmysql:8.0Database servermysql-data volume
redisredis:7-alpineCache & sessionsredis-data volume
phpmyadminphpmyadminDB managementnone (dev only)

Development Workflow

Common Commands

bash
# Start/Stop Containers
make up              # Start all containers
make down            # Stop all containers
make restart         # Restart containers
make ps              # Show running containers

# View Logs
make logs            # Show all logs
make log-app         # Show PHP logs
make log-web         # Show Nginx logs
make log-db          # Show MySQL logs

# Container Access
make shell           # Enter PHP container
make mysql           # Access MySQL CLI
make redis           # Access Redis CLI

# Database Operations
make migrate         # Run migrations
make seed            # Seed database
make db-backup       # Backup database
make db-restore FILE=backups/dump.sql.gz

# Code Quality
make lint            # Check code style
make analyze         # Static analysis
make format          # Format code
make test            # Run tests
make quality         # All checks

# Caching
make cache-clear     # Clear all caches
make cache-info      # Show cache stats

File Changes During Development

The following directories are mounted as volumes for live development:

code
toktak-clone/
├── app/              → /var/www/html/app (live reload)
├── public/           → /var/www/html/public (live reload)
├── routes/           → /var/www/html/routes (live reload)
├── config/           → /var/www/html/config (live reload)
├── database/         → /var/www/html/database (live reload)
├── storage/          → /var/www/html/storage (persistent)
└── docker/           → /docker configs (read-only)

Note: You can edit files locally and changes appear immediately in the container.

Running Tests

bash
# Run all tests
make test

# Run specific test file
make php CMD="vendor/bin/phpunit tests/Unit/ExampleTest.php"

# Generate coverage report
make test-coverage

Production Deployment

Pre-Deployment Checklist

bash
# 1. Verify all tests pass
make test

# 2. Check code quality
make quality

# 3. Run security analysis
make analyze

# 4. Build production images
docker-compose -f docker-compose.yml -f docker-compose.prod.yml build

# 5. Review environment configuration
cat .env.production

Deployment Script

The deploy.sh script automates the deployment process:

bash
# Deploy to production (with confirmation)
./deploy.sh production

# Force deployment without confirmation
./deploy.sh production -f

# Deploy to staging
./deploy.sh staging

# Deployment options
./deploy.sh production --no-backup      # Skip database backup
./deploy.sh production --no-migrations  # Skip migrations
./deploy.sh production --no-health-check # Skip health checks

What the Deploy Script Does

  1. Code Update: Pulls latest changes from git
  2. Image Build: Builds new Docker images
  3. Database Backup: Creates database backup (unless --no-backup)
  4. Migrations: Runs database migrations (unless --no-migrations)
  5. Container Restart: Stops old containers and starts new ones
  6. Cache Clear: Clears application and Redis caches
  7. Health Checks: Verifies all services are healthy
  8. Rollback on Failure: Automatically restores from backup if anything fails

Manual Production Deployment

bash
# Pull latest code
git pull origin main

# Build new images
docker-compose -f docker-compose.yml -f docker-compose.prod.yml build

# Stop old containers
docker-compose down

# Start new containers
docker-compose -f docker-compose.yml -f docker-compose.prod.yml up -d

# Run migrations
docker-compose exec app php /var/www/html/database/migrations/migrate.php

# Clear caches
docker-compose exec app rm -rf storage/cache/*
docker-compose exec redis redis-cli FLUSHDB

# Health check
curl http://localhost/health-check

Cloud Deployment Options

AWS (Amazon Web Services)

Option 1: AWS ECS (Elastic Container Service)

Create ECR Repository:

bash
aws ecr create-repository --repository-name toktak-clone --region ap-northeast-2

Build and Push Image:

bash
# Build image
docker build -t toktak-clone:latest .

# Tag for ECR
docker tag toktak-clone:latest 123456789.dkr.ecr.ap-northeast-2.amazonaws.com/toktak-clone:latest

# Push to ECR
docker push 123456789.dkr.ecr.ap-northeast-2.amazonaws.com/toktak-clone:latest

Deploy with ECS:

bash
# Create ECS task definition
aws ecs register-task-definition --cli-input-json file://ecs-task-definition.json

# Create ECS service
aws ecs create-service \
  --cluster toktak-cluster \
  --service-name toktak-service \
  --task-definition toktak-clone:1 \
  --desired-count 2 \
  --region ap-northeast-2

Option 2: AWS Lightsail

Simplest option for small to medium deployments:

bash
# Create Lightsail container service
aws lightsail create-container-service \
  --service-name toktak-clone \
  --power small \
  --region ap-northeast-2

# Deploy container
aws lightsail create-container-service-deployment \
  --service-name toktak-clone \
  --region ap-northeast-2 \
  --containers file://containers.json

DigitalOcean App Platform

Create app.yaml:

yaml
name: toktak-clone
services:
  - name: app
    github:
      repo: your-org/toktak-clone
      branch: main
    build_command: make build
    http_port: 80
    health_check:
      http_path: /health-check
    envs:
      - key: APP_ENV
        value: production
      - key: DB_HOST
        scope: RUN_TIME
        value: ${db.hostname}

  - name: db
    engine: MYSQL
    version: "8.0"
    production: true
    envs:
      - key: MYSQL_ROOT_PASSWORD
        value: ${MYSQL_ROOT_PASSWORD}

  - name: cache
    engine: REDIS
    version: "7"

Deploy:

bash
doctl apps create --spec app.yaml

Google Cloud Run

Build and Push:

bash
# Build image
gcloud builds submit --tag gcr.io/PROJECT-ID/toktak-clone

# Deploy to Cloud Run
gcloud run deploy toktak-clone \
  --image gcr.io/PROJECT-ID/toktak-clone \
  --platform managed \
  --region asia-northeast1 \
  --memory 2Gi \
  --cpu 2 \
  --allow-unauthenticated

Docker Swarm (Simple Cluster)

For production clusters on your own infrastructure:

bash
# Initialize Swarm
docker swarm init

# Create stack from compose file
docker stack deploy -c docker-compose.prod.yml toktak

# Monitor services
docker service ls
docker service logs toktak_app

GitHub Actions CI/CD

The .github/workflows/deploy.yml file provides automated CI/CD pipeline:

Pipeline Stages

  1. Code Quality - Tests, linting, static analysis
  2. Build - Docker image build and push
  3. Security - Vulnerability scanning
  4. Deploy - Automated deployment to production
  5. Smoke Tests - Basic health and functionality checks

Configure Secrets

Required GitHub secrets for deployment:

code
PRODUCTION_HOST          - Server IP or hostname
PRODUCTION_USER          - SSH username
PRODUCTION_SSH_KEY       - Private SSH key
PRODUCTION_SSH_PORT      - SSH port (default 22)
PRODUCTION_APP_PATH      - App directory path
PRODUCTION_URL           - Application URL
SLACK_WEBHOOK_URL        - Slack notifications

Add secrets in GitHub:

code
Settings → Secrets and variables → Actions → New repository secret

Trigger Deployment

bash
# Automatic trigger (push to main)
git push origin main

# Manual trigger
# Go to GitHub Actions → Deploy to Production → Run workflow

Troubleshooting

Common Issues

Container Won't Start

bash
# Check logs
make logs app

# Verify configuration
docker-compose config

# Inspect container
docker inspect toktak-app

Database Connection Failed

bash
# Check MySQL is running
make log-db

# Verify credentials
make mysql

# Restart database
docker-compose restart db

# Wait for MySQL to be ready
docker-compose exec db mysqladmin ping -h localhost

Redis Connection Issues

bash
# Check Redis status
make redis

# Verify Redis is accepting connections
docker-compose exec redis redis-cli ping

# Check Redis logs
make log-redis

# Clear Redis data
docker-compose exec redis redis-cli FLUSHDB

Nginx 502 Bad Gateway

bash
# PHP-FPM not responding
# Check PHP logs
make log-app

# Restart PHP container
docker-compose restart app

# Check PHP health
curl http://localhost:9000/health-check

File Permission Issues

bash
# Fix volume permissions
docker-compose exec -u root app chown -R www:www /var/www/html/storage

# Fix storage directory permissions
docker-compose exec -u root app chmod -R 775 /var/www/html/storage

Useful Debugging Commands

bash
# View all containers
docker ps -a

# Show container stats
docker stats

# Inspect network
docker network inspect toktak-network

# View volume details
docker volume ls
docker volume inspect toktak-uploads-data

# Clean up unused resources
docker system prune -a

# Get container IP
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' toktak-app

Performance Optimization

PHP Configuration

Key settings in docker/php/php.ini:

ini
# Increase limits for video processing
upload_max_filesize = 500M
post_max_size = 512M
max_execution_time = 300

# Enable OPcache for faster execution
opcache.enable = 1
opcache.memory_consumption = 128M

# Session storage in Redis (not file-based)
session.save_handler = redis
session.save_path = "tcp://redis:6379"

Nginx Performance

Key settings in docker/nginx/default.conf:

nginx
# Enable Gzip compression
gzip on;
gzip_types text/plain text/css text/javascript application/json;

# Cache static assets
location ~* \.(jpg|jpeg|png|gif|css|js|svg)$ {
    expires 1y;
    add_header Cache-Control "public, immutable";
}

# PHP-FPM buffering
fastcgi_buffering on;
fastcgi_buffer_size 64k;
fastcgi_buffers 8 64k;

Docker Resource Limits

Set resource constraints in docker-compose.yml:

yaml
services:
  app:
    deploy:
      resources:
        limits:
          cpus: '2'
          memory: 1G
        reservations:
          cpus: '1'
          memory: 512M

Database Optimization

bash
# Add indexes
docker-compose exec db mysql -u toktak -p -e "CREATE INDEX idx_user_id ON posts(user_id);"

# Optimize tables
docker-compose exec db mysql -u toktak -p -e "OPTIMIZE TABLE posts, users, content;"

# Monitor queries
docker-compose exec db mysql -u toktak -p -e "SET GLOBAL slow_query_log = 'ON';"

Monitoring and Metrics

Container Resource Usage

bash
docker stats toktak-app toktak-db toktak-redis

Database Monitoring

bash
# Monitor active connections
make mysql << 'EOF'
SHOW PROCESSLIST;
EOF

Redis Monitoring

bash
# Check memory usage
make redis
> INFO memory

Additional Resources

Support and Issues

For issues or questions:

  1. Check container logs: make logs
  2. Review this guide's troubleshooting section
  3. Check GitHub Issues
  4. Contact the development team

License

TokTak Clone - MIT License