The Essential Laravel Production Deployment Checklist
Essential steps for launch: Config caching, route optimization, .env security, and ensuring debug mode is strictly OFF.
Deploying a Laravel project to production requires careful preparation to ensure security, performance, and reliability. Below is a comprehensive checklist to confirm before deploying a Laravel project to production, along with common mistakes to avoid. This guide assumes familiarity with Laravel and basic server management.
Checklist for Deploying a Laravel Project to Production
1. Environment Configuration
- Set Environment to Production:
- Ensure the
.envfile or server environment variables setAPP_ENV=productionandAPP_DEBUG=false. - Debugging should be disabled in production to prevent sensitive information leaks.
- Ensure the
- Optimize Configuration:
- Run
php artisan config:cacheto cache configuration files for faster performance. - Avoid caching during development or if configs change frequently.
- Run
- Secure Environment File:
- Ensure the
.envfile is not publicly accessible (e.g., exclude it from version control and restrict access via server configuration). - Store sensitive data (e.g.,
APP_KEY, database credentials) securely in the.envfile or a secrets management system.
- Ensure the
- Generate Application Key:
- Run
php artisan key:generateif theAPP_KEYis missing or invalid. This key is critical for encryption.
- Run
2. Database Setup
- Configure Database:
- Set up a production database (e.g., MySQL, PostgreSQL) with proper credentials in
.env. - Use a dedicated database user with limited permissions (avoid
root).
- Set up a production database (e.g., MySQL, PostgreSQL) with proper credentials in
- Run Migrations:
- Execute
php artisan migrate --forceto apply database migrations in production. - Test migrations in a staging environment first to avoid data loss.
- Execute
- Seed Data (if needed):
- If seeding initial data, use
php artisan db:seed --forcecarefully to avoid overwriting production data.
- If seeding initial data, use
- Backup Database:
- Set up automated backups for the database to prevent data loss.
3. Performance Optimization
- Cache Routes:
- Run
php artisan route:cacheto cache routes for faster routing. - Clear cache (
php artisan route:clear) if routes are updated.
- Run
- Cache Views:
- Run
php artisan view:cacheto compile Blade templates for better performance.
- Run
- Optimize Autoloader:
- Run
composer install --optimize-autoloader --no-devto optimize the autoloader and exclude development dependencies.
- Run
- Enable Opcache:
- Configure PHP’s Opcache on the server to cache compiled PHP code for faster execution.
- Use a Queue System:
- Configure a queue driver (e.g., Redis, database) for tasks like sending emails or processing jobs.
- Run the queue worker (
php artisan queue:work) using a process manager like Supervisor.
- Set Up CDN (Optional):
- Use a Content Delivery Network (CDN) for static assets (CSS, JS, images) to reduce server load.
4. Security
- Secure File Permissions:
- Set appropriate permissions:
storage/andbootstrap/cache/should be writable by the web server user (e.g.,www-data).- Other directories should be read-only for the web server user.
- Example:
chmod -R 755 storage bootstrap/cache.
- Set appropriate permissions:
- Use HTTPS:
- Enforce HTTPS by configuring SSL/TLS certificates (e.g., Let’s Encrypt).
- Update
.envwithAPP_URL=https://yourdomain.comand enforce HTTPS inAppServiceProvideror middleware.
- Sanitize Inputs:
- Use Laravel’s validation and request classes to sanitize and validate user inputs.
- Avoid directly using
$_POSTor$_GET.
- Protect Against CSRF and XSS:
- Ensure CSRF tokens are enabled (default in Laravel forms).
- Use Laravel’s Blade
{{ }}ore()helper to escape output and prevent XSS.
- Secure APIs:
- Use Laravel Sanctum or Passport for API authentication.
- Implement rate limiting to prevent abuse (
php artisan throttle:requests).
- Update Dependencies:
- Ensure all Composer dependencies are up to date (
composer update) and free of known vulnerabilities (use tools like Dependabot orcomposer audit).
- Ensure all Composer dependencies are up to date (
- Hide Sensitive Information:
- Configure the web server (e.g., Nginx, Apache) to block access to sensitive files like
.env,.git, andcomposer.json.
- Configure the web server (e.g., Nginx, Apache) to block access to sensitive files like
5. Server Configuration
- Choose a Reliable Server:
- Use a production-grade server (e.g., AWS, DigitalOcean, Laravel Forge, or Heroku).
- Ensure the server meets Laravel’s requirements (PHP ≥ 8.1, required extensions like
mbstring,pdo, etc.).
- Configure Web Server:
- For Nginx or Apache, set up a virtual host pointing to the
public/directory as the document root. - Example Nginx configuration:
server { listen 80; server_name yourdomain.com; root /path/to/laravel/public; index index.php index.html; location / { try_files $uri $uri/ /index.php?$query_string; } location ~ \.php$ { include fastcgi_params; fastcgi_pass unix:/var/run/php/php8.1-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; } }
- For Nginx or Apache, set up a virtual host pointing to the
- Set Up PHP-FPM:
- Configure PHP-FPM for optimal performance (e.g., adjust
pm.max_children,pm.start_servers).
- Configure PHP-FPM for optimal performance (e.g., adjust
- Enable Error Logging:
- Configure Laravel’s logging (
config/logging.php) to write to a file or service like Sentry. - Ensure PHP and web server logs are enabled and monitored.
- Configure Laravel’s logging (
- Set Up Caching:
- Use a caching driver like Redis or Memcached for sessions and cache (
CACHE_DRIVER=redisin.env).
- Use a caching driver like Redis or Memcached for sessions and cache (
- Monitor Server Resources:
- Set up monitoring tools (e.g., New Relic, Datadog) to track CPU, memory, and disk usage.
6. Testing and Staging
- Test in Staging:
- Deploy to a staging environment that mirrors production to catch issues early.
- Run Tests:
- Execute unit and feature tests (
php artisan test) to ensure functionality.
- Execute unit and feature tests (
- Check for Errors:
- Test all critical user flows (e.g., login, registration, payments) in staging.
- Load Testing:
- Perform load testing (e.g., using JMeter or Locust) to ensure the app handles expected traffic.
7. Deployment Process
- Use a Deployment Tool:
- Consider tools like Laravel Forge, Envoyer, or Git-based deployment for zero-downtime deployments.
- Automate Deployment:
- Set up a CI/CD pipeline (e.g., GitHub Actions, GitLab CI) to automate testing and deployment.
- Clear Caches After Deployment:
- Run
php artisan cache:clear,php artisan config:cache,php artisan route:cache, andphp artisan view:cachepost-deployment.
- Run
- Minimize Downtime:
- Use
php artisan downto put the app in maintenance mode during deployment, andphp artisan upto bring it back online.
- Use
8. Monitoring and Maintenance
- Set Up Monitoring:
- Use tools like Laravel Telescope (for debugging, not recommended in production) or external services like Sentry for error tracking.
- Schedule Tasks:
- Configure Laravel’s task scheduler (
php artisan schedule:run) using a cron job:* * * * * cd /path/to/laravel && php artisan schedule:run >> /dev/null 2>&1
- Configure Laravel’s task scheduler (
- Monitor Performance:
- Use tools like Laravel Horizon for queue monitoring or external services for performance tracking.
- Regular Updates:
- Keep Laravel, PHP, and dependencies updated to patch security vulnerabilities.
- Backup Strategy:
- Schedule regular backups for the database and
storage/directory.
- Schedule regular backups for the database and
9. Email and Notifications
- Configure Mail Driver:
- Use a reliable mail driver (e.g., SMTP, Mailgun, SES) in
.envfor sending emails. - Example:
MAIL_DRIVER=smtp,MAIL_HOST=smtp.mailgun.org.
- Use a reliable mail driver (e.g., SMTP, Mailgun, SES) in
- Test Notifications:
- Verify that emails, SMS, or other notifications are sent correctly in production.
10. Scalability
- Horizontal Scaling:
- Use a load balancer (e.g., AWS ELB, Nginx) to distribute traffic across multiple servers.
- Session Management:
- Store sessions in a centralized store (e.g., Redis, database) for multi-server setups.
- Database Optimization:
- Index frequently queried columns and optimize queries for performance.
Common Mistakes to Avoid
- Leaving Debug Mode Enabled:
- Mistake: Setting
APP_DEBUG=truein production exposes sensitive error details. - Fix: Always set
APP_DEBUG=falsein.env.
- Mistake: Setting
- Exposing Sensitive Files:
- Mistake: Allowing public access to
.env,storage/, or.git/directories. - Fix: Configure the web server to deny access to these directories.
- Mistake: Allowing public access to
- Not Caching Configurations:
- Mistake: Forgetting to cache configurations, routes, or views, leading to slower performance.
- Fix: Run
php artisan config:cache,php artisan route:cache, andphp artisan view:cache.
- Using Development Dependencies:
- Mistake: Deploying with development dependencies, increasing server load.
- Fix: Run
composer install --no-devin production.
- Ignoring Security Headers:
- Mistake: Not setting HTTP security headers like Content Security Policy (CSP) or X-Frame-Options.
- Fix: Use middleware or server configuration to add headers (e.g.,
X-Content-Type-Options: nosniff).
- Not Backing Up Data:
- Mistake: Failing to set up automated backups for the database or files.
- Fix: Implement a backup strategy using tools like AWS S3 or database-specific solutions.
- Running Migrations Blindly:
- Mistake: Running migrations in production without testing, risking data loss.
- Fix: Test migrations in a staging environment first.
- Not Monitoring Queues:
- Mistake: Failing to monitor queue workers, leading to delayed or failed jobs.
- Fix: Use Supervisor or Horizon to manage and monitor queues.
- Hardcoding Paths or URLs:
- Mistake: Hardcoding domain names or file paths in the code.
- Fix: Use environment variables or Laravel’s helpers (e.g.,
asset(),url()).
- Ignoring Scalability:
- Mistake: Not planning for traffic spikes or multi-server setups.
- Fix: Design for scalability with load balancers, centralized sessions, and caching.
Additional Notes
- Use Version Control: Ensure the codebase is versioned (e.g., Git) and exclude sensitive files like
.envusing.gitignore. - Document Deployment: Maintain a deployment checklist or script to ensure consistency.
- Test Rollbacks: Have a rollback plan in case the deployment fails (e.g., revert to previous Git commit).
- Check Laravel Version: Ensure the Laravel version is compatible with your PHP version and dependencies.
By following this checklist and avoiding these mistakes, you can deploy a secure, performant, and reliable Laravel application in production. If you need help with specific configurations or tools, let me know!
Ketan Patel
PHP & MySQL Performance Optimization Specialist
I specialize in diagnosing and fixing slow PHP applications, optimizing MySQL queries, and resolving backend bottlenecks in live production systems. My approach is metric-driven — identifying root causes through profiling, execution analysis, and structured optimization instead of guesswork.