Running Laravel on LEMP
By the end of this lesson ShikshaPortal will run as a Laravel 13 app at shiksha.example.com, inside the shiksha PHP-FPM pool you built earlier. You will install Composer, pull the code with its own deploy key, write a production .env, decide which folders Laravel may write to, run migrations against MySQL, cache the framework, write a Laravel-ready server block, and keep a queue worker and the scheduler running.
What you should know first: Deploying a PHP App on LEMP for the Git and deploy-key workflow, and MySQL Setup, Users & Security, where shiksha_app got migration rights on the shiksha database. Laravel itself is taught in the Laravel tutorial; its own Deployment: Shared Hosting & VPS lesson gives the general checklist. Here you fit Laravel into this course's server layout. Versions checked: Laravel Framework 13.42.0 (requires PHP 8.3 or newer; Ubuntu 26.04 has 8.5) and Ubuntu's composer 2.9.5 package. The Artisan and Nginx outputs come from a real run of Laravel 13.42.0 behind Nginx 1.28.3, using SQLite in place of MySQL; Artisan's dotted lines are shown as an 80-column terminal draws them.
What Laravel needs from the server
| Need | On this server |
|---|---|
| PHP 8.3 or newer | PHP 8.5 from Ubuntu |
| Extensions: ctype, curl, dom, fileinfo, filter, hash, mbstring, openssl, pcre, pdo, session, tokenizer, xml | Built in, or from php8.5-common, -xml, -mbstring, -curl (installed in the setup lesson) |
| Database driver | php8.5-mysql (installed) |
| Composer | sudo apt install composer unzip php8.5-zip |
| Web root | public/, which Laravel already has |
| Writable folders | storage/ and bootstrap/cache/ |
Check the extensions with one command. No output means nothing is missing:
php -r 'foreach (["ctype", "curl", "dom", "fileinfo", "filter", "hash", "mbstring", "openssl", "pcre", "pdo_mysql", "session", "tokenizer", "xml", "zip"] as $e) { if (!extension_loaded($e)) echo "missing: $e\n"; }'Who writes what
Laravel's documentation says the web server must be able to write to storage and bootstrap/cache. On this server that means the shiksha pool user, not www-data. Think of a school office: the principal (deploy) owns the files and changes the timetable; the clerk (shiksha) may only write in the register and the notice tray.
| Who | Runs | May write to |
|---|---|---|
deploy | git, composer install | Everything (owner of the code) |
shiksha (PHP-FPM pool, queue worker, Artisan) | Web requests and php artisan ... | storage/ and bootstrap/cache/ only |
www-data (Nginx) | Static files | Nothing |
One rule keeps file ownership tidy: run Composer as deploy, and run Artisan as shiksha with sudo -u shiksha php artisan .... Then logs and caches are always written by the same user that the website runs as, and "Permission denied" errors on laravel.log never appear.
Step 1: get the code onto the server
GitHub allows each deploy key on only one repository, and ~/.ssh/config already sends the bakery's key to github.com. Create a second key and a host alias for ShikshaPortal:
ssh-keygen -t ed25519 -f ~/.ssh/shiksha_deploy -N "" -C "deploy@shiksha"Host github-shiksha
HostName github.com
IdentityFile ~/.ssh/shiksha_deploy
IdentitiesOnly yesAdd the public key as a read-only deploy key on the ShikshaPortal repository. The pools lesson made storage belong to shiksha only, so hand it back to deploy (keeping the group) before Git writes into it, then turn the folder into a checkout exactly as for the bakery:
cd /var/www/shiksha
sudo chown deploy:shiksha storage
git init -b main
git remote add origin git@github-shiksha:lucknow-school/shiksha-portal.git
git fetch origin
git reset --hard origin/main
git branch --set-upstream-to=origin/main
sudo chmod -R u=rwX,g=rwX,o= storage bootstrap/cache
sudo find storage bootstrap/cache -type d -exec chmod g+s {} +The last two lines make both folders writable by the shiksha group, with no access for anyone else, and make new files inherit the group.
Step 2: install dependencies
As deploy, install only production packages. --optimize-autoloader builds a class map so PHP finds classes without searching folders:
composer install --no-dev --optimize-autoloader --no-interactionThe last lines show Laravel discovering its packages, which writes bootstrap/cache/packages.php:
Generating optimized autoload files > Illuminate\Foundation\ComposerScripts::postAutoloadDump > @php artisan package:discover --ansi INFO Discovering packages. laravel/tinker ........................................................ DONE nesbot/carbon ......................................................... DONE nunomaduro/termwind ................................................... DONE 55 packages you are using are looking for funding. Use the `composer fund` command to find out more!
--no-dev leaves out testing tools such as Pest and Faker, which have no business on a live server.
Step 3: the production .env
Copy .env.example to .env and set the values that matter on a server. Configuration in general is covered in Configuration & .env:
APP_NAME=ShikshaPortal
APP_ENV=production
APP_KEY=
APP_DEBUG=false
APP_URL=http://shiksha.example.com
LOG_CHANNEL=stack
LOG_STACK=daily
LOG_LEVEL=warning
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=shiksha
DB_USERNAME=shiksha_app
DB_PASSWORD="your-second-password"
SESSION_DRIVER=database
QUEUE_CONNECTION=database
CACHE_STORE=databaseAPP_DEBUG=false is the most important line: with debug on, an error page can show your database password to any visitor. LOG_STACK=daily starts a new log file each day and keeps 14 by default. Protect the file and create the encryption key:
chmod 640 .env
php artisan key:generateINFO Application key set successfully.
key:generate is the one Artisan command you run as deploy, because it writes into .env, which shiksha may only read. Run it once. Changing APP_KEY later logs everyone out and makes encrypted data unreadable.
Step 4: migrate and cache
Now switch to the shiksha user. --force is required because Laravel asks for confirmation before migrating in production:
sudo -u shiksha php artisan migrate --force
sudo -u shiksha php artisan optimizeINFO Preparing database. Creating migration table ...................................... 30.21ms DONE INFO Running migrations. 0001_01_01_000000_create_users_table .......................... 92.85ms DONE 0001_01_01_000001_create_cache_table .......................... 54.33ms DONE 0001_01_01_000002_create_jobs_table .......................... 132.36ms DONE INFO Caching framework bootstrap, configuration, and metadata. config ....................................................... 210.99ms DONE events ........................................................ 51.49ms DONE routes ....................................................... 117.90ms DONE views ........................................................ 660.45ms DONE
The migrations created the tables for users, sessions, the cache and queued jobs, which is why shiksha_app needed CREATE and ALTER. optimize combines the config, events, routes and compiled Blade views into cache files. After config:cache, Laravel no longer reads .env on each request, so every change to .env needs optimize again.
Step 5: a server block for Laravel
Replace /etc/nginx/sites-available/shiksha.conf. It follows the Nginx example in Laravel's deployment documentation, adapted to this server's socket, logs and Ubuntu's FastCGI snippet:
server {
listen 80;
listen [::]:80;
server_name shiksha.example.com;
root /var/www/shiksha/public;
index index.php;
charset utf-8;
access_log /var/log/nginx/shiksha.access.log;
error_log /var/log/nginx/shiksha.error.log;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
location / {
try_files $uri $uri/ /index.php$is_args$args;
}
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 = /index.php {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/shiksha.sock;
fastcgi_hide_header X-Powered-By;
}
location ~ \.php$ {
return 404;
}
location ~ /\.(?!well-known/) {
deny all;
}
}The two PHP locations are the security core. location = /index.php is an exact match, so it wins first and is the only PHP file that ever runs. Any other .php URL, such as a web shell an attacker managed to upload, hits return 404. error_page 404 /index.php then lets Laravel draw its own 404 page for it. The two add_header lines stop other sites from framing your pages and stop browsers from guessing file types.
Test, reload and probe:
sudo nginx -t && sudo systemctl reload nginx
for path in / /up /students/42 /.env /info.php; do
printf '%-14s ' "$path"
curl -s -o /dev/null -w "%{http_code}\n" -H "Host: shiksha.example.com" "http://203.0.113.10$path"
donenginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful / 200 /up 200 /students/42 404 /.env 403 /info.php 404
/up is Laravel's built-in health route: 200 means the app booted, a good URL for an uptime monitor. /students/42 is a 404 from Laravel's router, because no such route exists yet, and /info.php is refused before PHP-FPM sees it.
Step 6: queue worker and scheduler
ShikshaPortal will email report cards through Laravel's queue, a waiting list of jobs handled in the background so the teacher's page does not wait. A worker process must always be running. Laravel's docs use Supervisor; Ubuntu's systemd does the same job without another package (see Services with systemd & systemctl). Create /etc/systemd/system/shiksha-queue.service:
[Unit]
Description=ShikshaPortal queue worker
After=network.target mysql.service
[Service]
User=shiksha
Group=shiksha
WorkingDirectory=/var/www/shiksha
ExecStart=/usr/bin/php artisan queue:work --sleep=3 --tries=3 --max-time=3600
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.targetsudo systemctl daemon-reload
sudo systemctl enable --now shiksha-queue--max-time=3600 makes the worker exit every hour to free memory, and Restart=always starts a fresh one. The worker runs as shiksha with the CLI php.ini, not inside the PHP-FPM pool.
The scheduler runs tasks such as a nightly attendance summary. It needs one cron entry, in the shiksha user's crontab (sudo crontab -u shiksha -e):
* * * * * cd /var/www/shiksha && php artisan schedule:run >> /dev/null 2>&1Writing jobs and schedules is covered in Queues, Jobs & Task Scheduling.
Step 7: the update script
Every later release repeats the same steps in a fixed order. Save this as bin/deploy.sh in the repository:
#!/usr/bin/env bash
set -euo pipefail
cd /var/www/shiksha
git pull --ff-only
composer install --no-dev --optimize-autoloader --no-interaction
sudo -u shiksha php artisan migrate --force
sudo -u shiksha php artisan optimize
sudo -u shiksha php artisan reload
sudo systemctl reload php8.5-fpmphp artisan reload tells long-running processes to restart with the new code:
INFO Reloading services. queue ........................................................ 138.14ms DONE schedule ...................................................... 41.34ms DONE
The queue worker finishes its current job, exits, and systemd starts it again. To run the script without password prompts, add rules with sudo visudo -f /etc/sudoers.d/deploy-shiksha, in the same style as the bakery's rule from the last lesson: deploy ALL=(shiksha) NOPASSWD: /usr/bin/php artisan * and deploy ALL=(root) NOPASSWD: /usr/bin/systemctl reload php8.5-fpm. Be aware that the first rule lets deploy run any Artisan command as shiksha; that is acceptable here because deploy already owns the code.
Common mistakes
APP_DEBUG=truein production. Error pages then show environment values, including database passwords.- Pointing
rootat/var/www/shikshainstead ofpublic. Nginx would serve.env,composer.jsonand your code. - Running Artisan as
deployor root. Log and cache files get the wrong owner and the website starts failing with "Permission denied". chmod -R 777 storage. It "fixes" permissions by letting every user on the server write there. Give the pool's group write access instead.- Editing
.envand forgettingoptimize. The cached config still holds the old values. - Forgetting to restart workers after a deploy. They keep running old code until restarted;
artisan reloadhandles it.
Interview questions
1. Which folders must Laravel be able to write, and who should own them on a multi-site server?
storage (logs, sessions, compiled views, cache files) and bootstrap/cache (package, config and route caches). Give the code owner (a deploy user) ownership and the site's own PHP-FPM pool user's group write access, with nothing for others, rather than making them writable by www-data or everyone.
2. Why does the Nginx config allow only index.php to execute?
Laravel's only entry point is public/index.php. Refusing every other .php URL means an uploaded or injected PHP file in public can never run, which closes a whole class of attacks. Static files are still served directly.
3. What does php artisan optimize do, and what is the catch with .env?
It caches configuration, events, routes and compiled views, so requests do less work. Once config is cached, .env is not read at runtime and env() calls outside config files return null, so you must re-run optimize after changing .env.
4. How do you keep a Laravel queue worker running in production?
Run php artisan queue:work under a process manager such as systemd or Supervisor, as the site's user, with automatic restart. Limit its life with --max-time or --max-jobs, and signal a restart on every deploy with artisan queue:restart or artisan reload.
5. Why use migrate --force?
In the production environment Laravel asks for confirmation before running migrations, to avoid accidents. A deploy script has no one to answer, so --force confirms in advance; it should only appear in scripts that run on purpose.
Key points
- Laravel 13 needs PHP 8.3+, the standard extensions and Composer; Ubuntu 26.04's PHP 8.5 packages provide them.
- Web root is
public/; only/index.phpexecutes, every other.phpURL returns 404. deployowns the code and runs Composer; theshikshapool user runs Artisan and writes only tostorageandbootstrap/cache.- Production
.env:APP_ENV=production,APP_DEBUG=false, MySQL settings, mode640; generateAPP_KEYonce. - Deploy order: pull,
composer install --no-dev,migrate --force,optimize,reload, reload PHP-FPM. - Keep
queue:workalive with a systemd service, and runschedule:runevery minute from theshikshacrontab.
Exercise
ShikshaPortal now stores uploaded student photos with Laravel's public disk, which saves files in storage/app/public and serves them through a public/storage link created by php artisan storage:link. Decide who should run storage:link, explain whether the link lets visitors run PHP files that someone uploads there, and write the extra Nginx location you would add so that only image files can be fetched from /storage/.
Show solution
Run it once as deploy, because it creates a symlink inside public/, which shiksha cannot write: php artisan storage:link. The pool can still write the photos themselves into storage/app/public.
PHP cannot run from there: any URL ending in .php, including /storage/x.php, matches location ~ \.php$ and gets 404, because only the exact /index.php location passes requests to PHP-FPM. To serve only images, add:
location ^~ /storage/ {
location ~* \.(jpe?g|png|webp|gif)$ {
expires 30d;
try_files $uri =404;
}
return 404;
}^~ stops Nginx from checking the other regex locations for /storage/ URLs, the nested regex allows the four image types, and everything else under /storage/ returns 404. Run sudo nginx -t && sudo systemctl reload nginx afterwards. Because ^~ skips the other regex locations for /storage/ URLs, the outer return 404 also covers hidden files there.
Quick Quiz
1. Which PHP file may execute through the Laravel server block in this lesson?
The exact location = /index.php passes to PHP-FPM; location ~ \.php$ returns 404 for everything else.
2. Why run Artisan commands with sudo -u shiksha?
Files created by a different user would make later writes from the website fail.
3. You changed MAIL_FROM_ADDRESS in .env but emails still use the old address. What is the most likely reason?
After config:cache, Laravel no longer reads .env on each request.
4. What does php artisan reload do in the deploy script?
Its output lists queue and schedule; systemd starts the worker again after it exits.
Learn LEMP Stack with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
