Deploying a Laravel application to production is a critical step that requires careful planning and execution. A successful deployment ensures your application is secure, performant, and reliable for your users.
This comprehensive guide covers Laravel deployment strategies from development to production, including server setup, deployment methods, environment configuration, and best practices to ensure a smooth launch.
The Deployment Challenge
Deploying Laravel applications involves several critical steps:
- Server configuration and setup
- Environment configuration
- Database migrations
- Asset compilation and optimization
- Queue workers and scheduled tasks
- Monitoring and error tracking
Pre-Deployment Checklist
Environment Configuration
- Set
APP_ENV=production - Set
APP_DEBUG=false - Generate
APP_KEYif not set - Configure database credentials
- Set up cache and session drivers
- Configure mail settings
Security Considerations
- Use HTTPS (SSL/TLS certificates)
- Set secure session and cookie settings
- Configure CORS properly
- Review and secure file permissions
- Enable rate limiting
- Set up firewall rules
Performance Optimization
- Enable OPcache
- Configure caching (Redis/Memcached)
- Optimize autoloader
- Compile and minify assets
- Enable gzip compression
Server Requirements
PHP Version and Extensions
// Required PHP version: 8.1 or higher
// Required extensions:
- BCMath
- Ctype
- Fileinfo
- JSON
- Mbstring
- OpenSSL
- PDO
- Tokenizer
- XML
// Recommended extensions:
- Redis (for caching/queues)
- Imagick (for image processing)
- OPcache (for performance)
Web Server Configuration
Nginx Configuration
server {
listen 80;
server_name example.com;
root /var/www/laravel/public;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
index index.php;
charset utf-8;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt { access_log off; log_not_found off; }
error_page 404 /index.php;
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /\.(?!well-known).* {
deny all;
}
}
Database Setup
- MySQL 5.7+ or MariaDB 10.3+
- PostgreSQL 10+
- SQLite 3.8.8+
- Configure database user with appropriate permissions
- Set up database backups
Deployment Methods
Manual Deployment
# 1. Clone repository
git clone https://github.com/user/repo.git /var/www/laravel
# 2. Install dependencies
cd /var/www/laravel
composer install --optimize-autoloader --no-dev
# 3. Copy environment file
cp .env.example .env
# 4. Generate application key
php artisan key:generate
# 5. Run migrations
php artisan migrate --force
# 6. Build assets
npm install
npm run build
# 7. Optimize
php artisan config:cache
php artisan route:cache
php artisan view:cache
Git-Based Deployment
#!/bin/bash
# deploy.sh
cd /var/www/laravel
git pull origin production
composer install --optimize-autoloader --no-dev
npm install
npm run build
php artisan migrate --force
php artisan config:cache
php artisan route:cache
php artisan view:cache
# Restart queue workers
php artisan queue:restart
CI/CD Pipelines
# .github/workflows/deploy.yml
name: Deploy
on:
push:
branches: [ production ]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: '8.2'
- name: Install Dependencies
run: composer install --optimize-autoloader --no-dev
- name: Run Tests
run: php artisan test
- name: Deploy to Server
uses: appleboy/ssh-action@master
with:
host: ${{ secrets.HOST }}
username: ${{ secrets.USERNAME }}
key: ${{ secrets.SSH_KEY }}
script: |
cd /var/www/laravel
git pull origin production
composer install --optimize-autoloader --no-dev
php artisan migrate --force
php artisan config:cache
php artisan route:cache
php artisan view:cache
Laravel Forge
Laravel Forge provides automated server management and deployment:
- One-click server provisioning
- Automatic SSL certificates
- Git-based deployments
- Queue worker management
- Database backups
Environment Configuration
.env File Management
# Production .env example
APP_NAME="My Application"
APP_ENV=production
APP_KEY=base64:...
APP_DEBUG=false
APP_URL=https://example.com
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=production_db
DB_USERNAME=production_user
DB_PASSWORD=secure_password
CACHE_DRIVER=redis
SESSION_DRIVER=redis
QUEUE_CONNECTION=redis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
Configuration Caching
# Cache configuration for performance
php artisan config:cache
# Clear config cache (when needed)
php artisan config:clear
# Cache routes
php artisan route:cache
# Cache views
php artisan view:cache
Database Migrations
Running Migrations Safely
# Run migrations
php artisan migrate --force
# Rollback last migration (if needed)
php artisan migrate:rollback
# Check migration status
php artisan migrate:status
Backup Strategies
# Backup database before migration
mysqldump -u user -p database > backup.sql
# Or use Laravel backup package
composer require spatie/laravel-backup
# Schedule automatic backups
php artisan schedule:run
Asset Compilation
Frontend Asset Building
# Install dependencies
npm install
# Build for production
npm run build
# Or use Vite
npm run build -- --mode production
CDN Integration
// config/filesystems.php
'disks' => [
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
'url' => env('AWS_URL'),
],
],
Queue Workers and Scheduling
Setting Up Queue Workers
# Start queue worker
php artisan queue:work --daemon
# Or use Supervisor for process management
# /etc/supervisor/conf.d/laravel-worker.conf
[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/laravel/artisan queue:work --sleep=3 --tries=3
autostart=true
autorestart=true
user=www-data
numprocs=2
redirect_stderr=true
stdout_logfile=/var/www/laravel/storage/logs/worker.log
Cron Job Configuration
# Add to crontab
* * * * * cd /var/www/laravel && php artisan schedule:run >> /dev/null 2>&1
Monitoring and Logging
Application Monitoring
- Laravel Telescope (development/staging)
- Laravel Pulse (production monitoring)
- Application Performance Monitoring (APM) tools
- Server monitoring (New Relic, Datadog)
Error Tracking
# Install Sentry
composer require sentry/sentry-laravel
# Configure in config/logging.php
'channels' => [
'sentry' => [
'driver' => 'sentry',
],
],
Post-Deployment
Health Checks
// routes/web.php
Route::get('/health', function () {
return response()->json([
'status' => 'ok',
'database' => DB::connection()->getPdo() ? 'connected' : 'disconnected',
'cache' => Cache::get('health_check') !== null ? 'working' : 'not working',
]);
});
Rollback Procedures
# Rollback to previous deployment
cd /var/www/laravel
git reset --hard HEAD~1
composer install --optimize-autoloader --no-dev
php artisan migrate:rollback
php artisan config:cache
php artisan route:cache
Common Deployment Issues
Permission Problems
# Fix storage and cache permissions
sudo chown -R www-data:www-data storage bootstrap/cache
sudo chmod -R 775 storage bootstrap/cache
Cache Problems
# Clear all caches
php artisan cache:clear
php artisan config:clear
php artisan route:clear
php artisan view:clear
# Then rebuild
php artisan config:cache
php artisan route:cache
php artisan view:cache
Best Practices
- Always test deployments in staging first
- Use version control for all code
- Automate deployment processes
- Monitor application after deployment
- Have rollback procedures ready
- Document deployment process
- Backup database before migrations
- Use environment-specific configurations
Conclusion
Laravel deployment strategies are crucial for successfully launching your application to production. By following best practices, properly configuring your server, and implementing automated deployment processes, you can ensure a smooth and reliable deployment.
Whether you choose manual deployment, Git-based workflows, or automated CI/CD pipelines, the key is to have a consistent, tested process that ensures your application is secure, performant, and ready for your users.
Working with experienced Laravel developers who understand deployment best practices can help you launch your application successfully and maintain it reliably in production.