Here's a review of your Docker ENTRYPOINT script with suggestions for improvement:
Key Strengths
- Graceful Shutdown Handling: Properly traps SIGTERM/SIGINT and forwards to Gunicorn
- Database Migration Retry Logic: Robust retry mechanism for database readiness
- Configurable Gunicorn Settings: Good use of environment variables with sensible defaults
- Optimized Worker Calculation: Uses CPU core count for worker sizing
- Docker Logging: Correctly logs to stdout/stderr for container compatibility
Areas for Improvement
1. Migration Command Safety
# Current
flask db upgrade
# Improved
set +e # Temporarily disable exit-on-error
flask db upgrade
MIGRATION_STATUS=$?
set -e # Re-enable exit-on-error
Why: set -e would terminate the script immediately on migration failure, preventing retries. This change allows proper error handling.
2. Gunicorn Execution
# Current
exec gunicorn ... &
# Improved
gunicorn ... &
Why: exec is ineffective here since the command is backgrounded. Removing it avoids confusion while maintaining functionality.
3. Worker Class Default
# Current
WORKER_CLASS=${WORKER_CLASS:-sync}
# Improved
WORKER_CLASS=${WORKER_CLASS:-gevent}
Why: gevent is generally more efficient for I/O-bound web apps than sync. Keep sync only for CPU-bound workloads.
4. Database Connection Handling
Add before migration loop:
# Wait for database to be ready
until flask db upgrade; do
echo "Database unavailable - sleeping"
sleep 2
done
Why: Explicitly checks database connectivity before attempting migrations, reducing unnecessary retries.
5. Signal Propagation
Add to shutdown function:
shutdown() {
echo "Shutting down gracefully..."
if kill -0 "$child" 2>/dev/null; then
kill -TERM "$child"
fi
wait "$child"
}
Why: Checks if child process exists before signaling and ensures proper cleanup.
6. Resource Limits
Add before Gunicorn start:
# Adjust for container resource limits
if [ -n "$GUNICORN_WORKERS" ]; then
WORKERS=$GUNICORN_WORKERS
elif [ -f /sys/fs/cgroup/cpu/cpu.cfs_quota_us ]; then
CPU_QUOTA=$(cat /sys/fs/cgroup/cpu/cpu.cfs_quota_us)
CPU_PERIOD=$(cat /sys/fs/cgroup/cpu/cpu.cfs_period_us)
if [ "$CPU_QUOTA" -ne -1 ]; then
WORKERS=$(( (CPU_QUOTA / CPU_PERIOD) + 1 ))
fi
fi
Why: Respects Docker CPU limits when calculating workers, preventing over-provisioning.
7. Health Check Integration
Add after Gunicorn start:
# Health check endpoint
curl --fail http://localhost:5000/health || exit 1
Why: Validates application readiness after startup (requires a /health endpoint in your app).
Final Improved Script
#!/bin/bash
set -e
# Graceful shutdown handler
shutdown() {
echo "Shutting down gracefully..."
if kill -0 "$child" 2>/dev/null; then
kill -TERM "$child"
fi
wait "$child"
}
trap shutdown SIGTERM SIGINT
# Wait for database readiness
echo "Waiting for database..."
until flask db upgrade; do
echo "Database unavailable - sleeping"
sleep 2
done
# Database migration with retry logic
MAX_RETRIES=10
RETRY_COUNT=0
while [ $RETRY_COUNT -lt $MAX_RETRIES ]; do
set +e
flask db upgrade
MIGRATION_STATUS=$?
set -e
if [ $MIGRATION_STATUS -eq 0 ]; then
echo "Database migration successful"
break
fi
RETRY_COUNT=$((RETRY_COUNT + 1))
echo "Migration failed (attempt $RETRY_COUNT/$MAX_RETRIES), retrying..."
sleep 5
done
if [ $RETRY_COUNT -eq $MAX_RETRIES ]; then
echo "Migration failed after $MAX_RETRIES attempts. Exiting."
exit 1
fi
# Calculate workers respecting container limits
WORKERS=${WORKERS:-$((2 * $(nproc) + 1))}
if [ -n "$GUNICORN_WORKERS" ]; then
WORKERS=$GUNICORN_WORKERS
elif [ -f /sys/fs/cgroup/cpu/cpu.cfs_quota_us ]; then
CPU_QUOTA=$(cat /sys/fs/cgroup/cpu/cpu.cfs_quota_us)
CPU_PERIOD=$(cat /sys/fs/cgroup/cpu/cpu.cfs_period_us)
if [ "$CPU_QUOTA" -ne -1 ]; then
WORKERS=$(( (CPU_QUOTA / CPU_PERIOD) + 1 ))
fi
fi
# Gunicorn configuration
THREADS=${THREADS:-2}
WORKER_CLASS=${WORKER_CLASS:-gevent} # More efficient than sync
WORKER_CONNECTIONS=${WORKER_CONNECTIONS:-1000}
TIMEOUT=${TIMEOUT:-120}
KEEPALIVE=${KEEPALIVE:-5}
MAX_REQUESTS=${MAX_REQUESTS:-1000}
MAX_REQUESTS_JITTER=${MAX_REQUESTS_JITTER:-50}
# Start Gunicorn
gunicorn microblog:app \
--bind :5000 \
--workers $WORKERS \
--threads $THREADS \
--worker-class $WORKER_CLASS \
--worker-connections $WORKER_CONNECTIONS \
--timeout $TIMEOUT \
--keep-alive $KEEPALIVE \
--max-requests $MAX_REQUESTS \
--max-requests-jitter $MAX_REQUESTS_JITTER \
--access-logfile - \
--error-logfile - \
--log-level ${LOG_LEVEL:-info} \
--preload \
--enable-stdio-inheritance &
child=$!
wait "$child"
Key Recommendations
- Use
gevent Workers: Better for most web applications than sync
- Respect Container Limits: Critical for proper resource utilization
- Database Readiness Check: Prevents unnecessary migration retries
- Health Check Endpoint: Essential for container orchestration
- Signal Handling Improvements: More robust process cleanup
- Migration Safety: Proper error handling with
set +e
Additional Best Practices
- Add Health Check in Dockerfile:
HEALTHCHECK --interval=30s --timeout=3s \
CMD curl -f http://localhost:5000/health || exit 1
- Use Non-Root User:
USER appuser
- Multi-Stage Builds: Reduce image size
- Environment Validation: Add checks for required env vars
- Log Format: Consider structured logging (JSON) for production
These changes will make your container more resilient, efficient, and production-ready while maintaining all the original functionality.