
How to Configure Laravel for Production is the question every developer hits the moment their local app is ready to face real users. In 2026 the answer is no longer a single Apache virtual host. It is a deliberate stack: PHP 8.3, a tuned web server, a hardened .env, and either Octane or a classic LEMP setup, plus monitoring that catches problems before customers do. This guide walks through every layer with the tradeoffs you actually need to know, so you can ship a Laravel app that stays fast, secure, and recoverable under real traffic.
Overview & Quick Wins
What Is Laravel Production? A production Laravel environment is a live, public-facing server (or cluster) where the framework serves real requests, sensitive data, and paying users. It differs from local in three concrete ways: APP_ENV=production disables verbose error pages, APP_DEBUG=false hides stack traces, and every config file is read from a single cached bootstrap/cache/config.php instead of being re-parsed on each request. Caching alone can shave 30-50% off response time on a typical request.
Definition: Laravel is a PHP web application framework that provides tools for routing, ORM, queueing, caching, and authentication. "Production" in Laravel terms means the environment where APP_ENV=production and the app is exposed to end users.
Immediate Deployment Checklist
- Set
APP_ENV=productionandAPP_DEBUG=false. - Generate a fresh
APP_KEYwithphp artisan key:generate. - Run
php artisan config:cache,route:cache, andview:cache. - Set storage and bootstrap/cache ownership to the web user (e.g.
www-data). - Point your web server's document root to
public/, not the project root. - Run
php artisan doctorto surface misconfigurations.
Why Production Setup Matters in 2026
PHP 8.3 Features Impacting Laravel PHP 8.3 brings typed class constants, readonly amendments, and the json_validate function that Laravel 11+ uses internally. Benchmarks across community hardware show frame boot times dropping by 12-18% compared to 8.2, which matters once you start running Swoole or RoadRunner. Skipping 8.3 in 2026 means leaving performance on the table for no reason.
Cloud Trends: Serverless vs Dedicated AWS Lambda Cold Starts for PHP have dropped to roughly 250 ms with custom runtimes, but they still cannot match the steady-state latency of a warm Octane worker. Dedicated VMs on Hetzner or DigitalOcean remain the cost-per-request king for any app serving more than 50,000 requests per day. Serverless makes sense for spiky, low-traffic APIs; dedicated wins for steady, predictable workloads.
Security in 2026 Automated scanners now probe every public IPv4 address within hours of deployment. Leaving APP_DEBUG=true is a 24-hour path to a full server compromise. HSTS preloading, strict CORS, and rate limiting are not optional extras anymore. They are the baseline that keeps your app out of botnet databases.
Prerequisites & Environment Checklist
Supported PHP Versions Laravel 11 requires PHP 8.2 minimum; Laravel 12 (released late 2025) requires PHP 8.3. Production deployments should run exactly the minimum required version, not the latest one with breaking changes, because every minor version bump you skip reduces the surface for known CVEs. Ubuntu 24.04 LTS ships PHP 8.3 in its default repos as of 2026.
Database Requirements MySQL 8.0+ or MariaDB 10.11+ is the safe default. PostgreSQL 15+ is the better choice if you need JSONB, advanced indexing, or strong concurrency. SQLite with WAL mode is production-viable for read-heavy apps, but it cannot scale across multiple servers and it still blocks writers against each other, which is documented in Laravel's official SQLite guidance.
Composer & Artisan Prerequisites Install Composer 2.7+ globally, then run composer install --no-dev --optimize-autoloader on the server. The --no-dev flag strips testing tools like PEST and Dusk; the --optimize-autoloader flag builds a classmap that speeds up autoloading by 20-40%.
File Permissions & Storage The web user (www-data on Ubuntu, apache on RHEL) must own storage/ and bootstrap/cache/. Recommended permissions: directories at 755, files at 644, and the .env file itself at 640. Never make the project world-writable; you are handing the keys to every PHP process that runs on the box.
Configuring the .env for Production
Setting APP_ENV and APP_DEBUG This is the single most important change. APP_ENV=production switches the framework into strict mode, where missing config keys become errors rather than silent nulls. APP_DEBUG=false hides the full stack traces that would otherwise leak database credentials, file paths, and environment names to anyone who triggers a 500 error. Keep .env outside the web root and add it to .gitignore before your first commit, then verify with git ls-files | grep .env that nothing slipped in.
Database Connection Strings For MySQL, use a dedicated application user with privileges limited to the specific database, never 'root' or the '%' wildcard host. Set DB_CONNECTION=mysql, DB_HOST=127.0.0.1 (not localhost, which forces a Unix socket), DB_PORT=3306, and rotate passwords quarterly. For managed databases like PlanetScale or AWS RDS, enable SSL by setting MYSQL_ATTR_SSL_CA in the options array of config/database.php.
Cache & Queue Drivers Set CACHE_STORE=redis and QUEUE_CONNECTION=redis for any app with more than trivial traffic. The file driver works but does not scale beyond a single server. Redis 7+ on the same box adds roughly 80 MB of RAM and returns cache reads in under 1 ms, which is why almost every Laravel deployment uses it.
Mail & Third-Party Services Use environment variables for every API key, never commit them. For mail, set MAIL_MAILER=ses (or Postmark, Resend, Mailgun) and verify the sending domain's SPF, DKIM, and DMARC records. A misconfigured mail driver is the number-one reason transactional emails land in spam in 2026, even with reputable providers.
Optimizing the Server Stack: LEMP vs Docker vs Octane
LEMP Stack Basics LEMP (Linux, Nginx, MySQL, PHP-FPM) is the simplest production stack for a single-server deployment. Nginx handles static assets and reverse-proxies PHP requests to PHP-FPM, which executes Laravel. A minimal Nginx server block looks like this:
server {
listen 80;
server_name example.com;
root /var/www/laravel/public;
index index.php;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
include fastcgi_params;
fastcgi_pass unix:/run/php/php8.3-fpm.sock;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
fastcgi_read_timeout 60;
}
}
Docker Compose for Laravel Docker shines when you have more than two services or need reproducible environments across staging and production. A production-grade docker-compose.yml separates the web container, queue worker (Horizon), scheduler, Redis, and database into distinct containers, as detailed in this production-ready Laravel stack walkthrough. Use Traefik labels to expose services on ports 80 and 443 with automatic Let's Encrypt certificates, and keep images minimal (php:8.3-cli-alpine as a base, not the full latest tag).
Octane on Shared Hosting Octane is not strictly tied to dedicated boxes. A contrarian view worth testing: a single Octane worker on a $6/month shared plan can outperform a 4-worker FPM setup on the same hardware, because the framework stays in memory. The catch is that Octane requires the Swoole or RoadRunner PHP extension, which most shared hosts block. If yours allows it, you get a 3-5x throughput bump for free.
Choosing Between Swoole & RoadRunner Swoole is a PHP extension written in C; it is the fastest option but requires recompiling PHP to add the extension. RoadRunner is a Go-based process manager that communicates with PHP over a Unix socket. For most teams, RoadRunner is the safer pick because it does not require a custom PHP build. Swoole wins for raw throughput when you have the operational maturity to maintain it.
| Stack | Best For | Complexity | Typical Throughput |
|---|---|---|---|
| LEMP (Nginx + PHP-FPM) | Single server, traditional apps | Low | 500-1,500 req/s |
| Docker + PHP-FPM + Traefik | Multi-service, reproducible | Medium | 500-1,500 req/s |
| Octane (RoadRunner) | APIs, high concurrency | Medium | 3,000-8,000 req/s |
| Octane (Swoole) | Maximum throughput | High | 8,000-20,000 req/s |
Securing the Application
Enforcing HTTPS & HSTS Never serve Laravel over plain HTTP in production. Use Let's Encrypt via Certbot or Traefik's automatic issuance, and redirect all port 80 traffic to 443. Add the following header to force HSTS: Strict-Transport-Security: max-age=31536000; includeSubDomains; preload. Once HSTS is active, browsers refuse to load your site over HTTP for the next year, killing a whole class of downgrade attacks.
Configuring CORS Middleware Laravel 11 ships with a HandleCors middleware. Set allowed_origins to a specific list, never * for authenticated requests. The supports_credentials flag must be set to true if you send cookies cross-origin, and allowed_methods should be restricted to only what the API actually exposes.
Rate Limiting & Throttling Laravel's RateLimiter facade, configured in App\Providers\AppServiceProvider, defaults to 60 requests per minute per IP. For a public API, 30-60 req/min is reasonable. For login endpoints, drop it to 5 attempts per minute and add exponential backoff via the throttle middleware. In 2026, brute-force login attempts exceed 1,000 per day on every public Laravel app; rate limiting is the only thing keeping your user table intact.
File Upload Validation Validate MIME type using mimes:jpg,png,pdf plus an explicit max size (max:5120 for 5 MB). Store uploads outside public/ and serve them through a signed URL route. PHP's finfo extension checks the actual file magic, not the extension, which defeats the most common upload bypass.
Performance Tuning
PHP OPcache Settings OPcache cuts PHP execution time roughly in half. In /etc/php/8.3/fpm/php.ini, set opcache.enable=1, opcache.memory_consumption=256, opcache.max_accelerated_files=20000, and opcache.validate_timestamps=0 in production. The last line tells OPcache to never re-check file mtimes, so you must restart PHP-FPM after every deploy.
Supervisord vs Laravel Horizon Supervisor is a Linux process manager; it keeps php artisan octane:start and queue workers alive after crashes. Horizon is a Laravel-specific dashboard for Redis queues. Use both: Supervisor manages the processes, Horizon gives you visibility into jobs, failed attempts, and throughput. The Horizon UI runs at /horizon and should be gated behind authentication in app/Providers/HorizonServiceProvider.php.
Octane Swoole Performance Metrics Swoole typically cuts framework boot time to 4-6 ms per request, compared to 30-50 ms for FPM. Real-world benchmarks on an 8-core Hetzner CCX show 15,000 req/s for a JSON API and 6,000 req/s for a typical HTML-rendering route. The first request after a worker starts is the slowest; subsequent requests stay in memory until the worker is recycled (default 500 requests).
RoadRunner Benchmarking RoadRunner sits between Swoole and FPM in throughput but wins on compatibility. Use the ./rr serve command with the bundled .rr.yaml file. Tune pool.allocate_timeout and pool.destroy_timeout if you see connection timeouts under load. RoadRunner's jobs plugin can replace a separate Horizon worker for simple queue setups.
Monitoring & Health Checks with Laravel Doctor
Installing Laravel Doctor Laravel Doctor is a first-party diagnostic tool that catches misconfigurations before they hit production. Install it as a dev dependency with composer require laravel/doctor --dev as documented in the Laravel News announcement. Then run php artisan doctor to scan for issues. Output uses status indicators: pass, notice, warn, fail, skip, or error.
Custom Health Checks Doctor is extensible. Create a check class implementing Doctor\Checks\Check and return one of the status constants. A typical health check verifies that the database is reachable, Redis responds to PING, and the storage/ directory is writable. Run these on a cron every minute and POST the result to your alerting system.
Integrating with CloudWatch / Grafana Push Doctor output to CloudWatch metrics or Grafana via a custom middleware that runs checks on a sample of requests. The Inspector package and Laravel Pulse are solid third-party alternatives, but Doctor covers the basics for free and adds no runtime overhead when not invoked.
Alerting & Auto-Recovery Wire Doctor into a systemd timer that runs every 5 minutes. On fail, trigger a PagerDuty or Slack alert and, if the issue is a downed Octane worker, run php artisan doctor --fix automatically. The --fix flag can repair many issues, including creating a missing .env, generating an APP_KEY, turning off debug mode, adding .env to .gitignore, creating the storage symlink, and fixing storage permissions.
Common Pitfalls & Troubleshooting
Permission Errors on Shared Hosting The most common error is file_put_contents(...): failed to open stream: Permission denied on storage/logs/laravel.log. Fix it with sudo chown -R $USER:www-data storage bootstrap/cache and chmod -R 775 storage bootstrap/cache. On shared hosts without sudo, add the FTP user to the www-data group via your hosting panel.
Environment Variable Caching Issues After editing .env in production, run php artisan config:clear then php artisan config:cache. If you forget this step, the framework keeps using the old values and you will chase a ghost bug for an hour. The same rule applies to route:clear and route:cache after route changes.
Queue Worker Crashes Horizon workers crash silently if Redis becomes unreachable or if a job throws an unhandled exception. Configure Supervisor to restart workers automatically (autorestart=true) and check Horizon's "Failed Jobs" tab daily. The php artisan queue:flush command removes all failed jobs older than 48 hours.
Cache Invalidation Problems After deploying a config change, the cached config in bootstrap/cache/config.php may serve stale values to long-running Octane workers. Use php artisan optimize:clear in your deploy script and add a Horizon/Octane reload step. Redis keys with the wrong prefix also cause weird cache misses; verify REDIS_PREFIX matches across environments.
Who Should Use Which Setup? Personas & Recommendations
Choosing a production stack depends on team size, traffic volume, and budget. The following table maps common personas to their best fit, based on real-world deployment experience in 2026.
| Target Persona | Recommended Option | Key Reason & Real-World Benefit |
|---|---|---|
| Solo developer on shared hosting | LEMP (Apache + PHP-FPM) | Lowest complexity, no SSH needed, $5-$10/month; sufficient for under 50k requests/day |
| Small team with Docker | Docker Compose + Traefik + Octane (RoadRunner) | Reproducible environments, one-command deploys, automatic HTTPS via Let's Encrypt |
| Enterprise with high traffic | Octane (Swoole) + Kubernetes + Redis Cluster + RDS | Horizontal scaling, 10k+ req/s, blue-green deploys via Git |
| Budget-conscious startup | LEMP on Hetzner + Horizon + SQLite (read-heavy apps) | Under $30/month total, covers up to 200k requests/day, no managed-service lock-in |
Verdict: For 80% of Laravel apps in 2026, a single dedicated box running LEMP with Octane on RoadRunner plus Redis and a managed MySQL is the sweet spot. It costs less than $50/month, supports millions of requests per day, and requires zero Kubernetes expertise.