Laravel Application Implementement on Linux

Laravel is a modern PHP framework enabling rapid development of robust web applications with expressive syntax, powerful ORM, and comprehensive tooling. Implementeing Laravel applications on Linux VPS requires understanding PHP-FPM configuration, Nginx setup, Composer dependency management, environment configuration, database migrations, background job processing, and application security. This guide covers production-ready Laravel deployment including LEMP stack setup, application installation, queue workers, caching configuration, and optimization for Linux servers.

Tabla de contenidos

Laravel Architecture Overview

Laravel applications consist of routing, controllers, models, views, and services. Understanding the architecture helps with deployment configuration.

Typical request flow:

  1. Nginx receives HTTP request
  2. Nginx forwards to PHP-FPM via FastCGI
  3. Laravel bootstrap initializes application
  4. Request routed to appropriate controller
  5. Controller interacts with models/database
  6. Response rendered and returned
  7. Response cached for future requests

Key deployment considerations:

  • Laravel runs as www-data user (web server user)
  • Storage directories require write permissions
  • Environment variables configure application
  • Database migrations set up schema
  • Queue workers process background jobs
  • Cache stores improve performance
  • Artisan console for administrative tasks

Server Environment Setup

Prepare Linux server for Laravel deployment.

Update system:

sudo apt update
sudo apt upgrade -y
sudo apt install curl wget git zip unzip vim htop build-essential -y

Instale PHP 8.2:

# Add PHP repository
sudo apt install software-properties-common -y
sudo add-apt-repository ppa:ondrej/php -y
sudo apt update

# Install PHP and extensions required by Laravel
sudo apt install php8.2 php8.2-fpm php8.2-mysql php8.2-curl php8.2-gd \
    php8.2-intl php8.2-json php8.2-xml php8.2-zip php8.2-mbstring \
    php8.2-opcache php8.2-redis php8.2-cli php8.2-common php8.2-sqlite3 -y

# Start PHP-FPM
sudo systemctl start php8.2-fpm
sudo systemctl enable php8.2-fpm

Instale Nginx:

sudo apt install nginx -y
sudo systemctl start nginx
sudo systemctl enable nginx

Instale MariaDB:

sudo apt install mariadb-server mariadb-client -y
sudo systemctl start mariadb
sudo systemctl enable mariadb
sudo mysql_secure_installation

Cree application database:

sudo mysql -u root -p << EOF
CREATE DATABASE laravel_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'laravel_user'@'localhost' IDENTIFIED BY 'SecurePassword123!';
GRANT ALL PRIVILEGES ON laravel_db.* TO 'laravel_user'@'localhost';
FLUSH PRIVILEGES;
EXIT;
EOF

Cree application user:

sudo useradd -m -s /bin/bash laravel
sudo usermod -aG www-data laravel

Cree application directory:

sudo mkdir -p /var/www/laravel-app
sudo chown -R laravel:www-data /var/www/laravel-app
sudo chmod -R 755 /var/www/laravel-app

Instale Composer:

curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer
sudo chmod +x /usr/local/bin/composer

# Verify
composer --version

PHP-FPM Configuration

Optimize PHP-FPM for Laravel applications.

Edit PHP-FPM pool configuration:

sudo nano /etc/php/8.2/fpm/pool.d/www.conf

Apply optimized settings:

[www]
user = www-data
group = www-data
listen = /run/php/php8.2-fpm.sock
listen.owner = www-data
listen.group = www-data
listen.mode = 0660

; Process management
pm = dynamic
pm.max_children = 64
pm.start_servers = 16
pm.min_spare_servers = 8
pm.max_spare_servers = 32
pm.max_requests = 5000

; Timeouts
request_terminate_timeout = 300
request_slowlog_timeout = 10s
slowlog = /var/log/php8.2-fpm-slow.log

; Resource limits
rlimit_files = 65535
rlimit_core = unlimited

Configure php.ini for Laravel:

sudo nano /etc/php/8.2/fpm/php.ini

Apply settings:

memory_limit = 256M
max_execution_time = 300
max_input_time = 300
upload_max_filesize = 128M
post_max_size = 128M

; OPcache
opcache.enable = 1
opcache.memory_consumption = 256
opcache.max_accelerated_files = 20000
opcache.validate_timestamps = 0
opcache.revalidate_freq = 0

; Session
session.save_path = /var/lib/php/sessions
session.gc_maxlifetime = 28800

; Error logging
error_log = /var/log/php8.2-fpm.log

Reinicie PHP-FPM:

sudo systemctl restart php8.2-fpm

Configuración de Nginx

Configure Nginx for Laravel application routing.

Cree Nginx server block:

sudo nano /etc/nginx/sites-available/laravel.conf

Apply configuration:

upstream php_backend {
    server unix:/run/php/php8.2-fpm.sock;
}

server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name example.com www.example.com;
    root /var/www/laravel-app/public;
    index index.php;

    access_log /var/log/nginx/laravel_access.log;
    error_log /var/log/nginx/laravel_error.log;

    # SSL configuration
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    # Security headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

    # Cache static files
    location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2|ttf)$ {
        expires 365d;
        add_header Cache-Control "public, immutable";
    }

    # Block access to sensitive files
    location ~ /\.env {
        deny all;
    }

    location ~ /\. {
        deny all;
    }

    # Laravel routing
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    # PHP handler
    location ~ \.php$ {
        fastcgi_pass php_backend;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

Enable configuration:

sudo ln -s /etc/nginx/sites-available/laravel.conf /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx

Laravel Application Instaleation

Instale Laravel and configure for production.

Clone or download Laravel project:

cd /var/www/laravel-app

# Clone from Git repository
git clone https://github.com/yourname/laravel-app.git .

# Or create new Laravel project
composer create-project laravel/laravel .

Instale dependencies:

cd /var/www/laravel-app

# Install PHP dependencies
composer install --optimize-autoloader --no-dev

# This installs packages from composer.json
# Progress shows: downloading, extracting, installing

Cree .env file:

# Copy environment template
cp .env.example .env

# Edit configuration
nano .env

Configure .env for production:

APP_NAME=Laravel
APP_ENV=production
APP_KEY=
APP_DEBUG=false
APP_LOG=single
APP_URL=https://example.com

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_db
DB_USERNAME=laravel_user
DB_PASSWORD=SecurePassword123!

CACHE_DRIVER=redis
SESSION_DRIVER=redis
QUEUE_CONNECTION=redis

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=465
MAIL_USERNAME=your-username
MAIL_PASSWORD=your-password

AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=

Generate application key:

cd /var/www/laravel-app
php artisan key:generate

# Verify key added to .env
grep APP_KEY .env

Set permissions:

sudo chown -R www-data:www-data /var/www/laravel-app
sudo find /var/www/laravel-app -type d -exec chmod 755 {} \;
sudo find /var/www/laravel-app -type f -exec chmod 644 {} \;

# Storage and bootstrap cache require write permissions
sudo chmod -R 777 /var/www/laravel-app/storage
sudo chmod -R 777 /var/www/laravel-app/bootstrap/cache

Configuración de la base de datos

Configure database and run migrations.

Run database migrations:

cd /var/www/laravel-app
php artisan migrate

# Output shows: migrating, migrated
# Creates all database tables defined in migrations

Seed database (if seeders exist):

# Run seeders to populate test data
php artisan db:seed

# Or run specific seeder
php artisan db:seed --class=UsersSeeder

Verifique database:

# Connect to database and verify tables
mysql -u laravel_user -p laravel_db -e "SHOW TABLES;"

# Check table structure
mysql -u laravel_user -p laravel_db -e "DESCRIBE users;"

Queue Processing with Supervisor

Configure background job processing with Supervisor.

Instale Supervisor:

sudo apt install supervisor -y
sudo systemctl start supervisor
sudo systemctl enable supervisor

Cree Supervisor configuration:

sudo nano /etc/supervisor/conf.d/laravel-worker.conf

Configure Laravel queue worker:

[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/laravel-app/artisan queue:work redis --sleep=3 --tries=3
autostart=true
autorestart=true
numprocs=4
redirect_stderr=true
stdout_logfile=/var/log/laravel-worker.log
user=www-data

Load configuration:

sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start laravel-worker:*

Verifique workers:

# Check supervisor status
sudo supervisorctl status

# Should show:
# laravel-worker:laravel-worker_00 RUNNING
# laravel-worker:laravel-worker_01 RUNNING
# etc.

# Monitor output
tail -f /var/log/laravel-worker.log

Application Caching

Configure caching for improved performance.

Instale and configure Redis:

sudo apt install redis-server -y
sudo systemctl start redis-server
sudo systemctl enable redis-server

# Verify
redis-cli ping

Configure Redis in Laravel:

# Already configured in .env
# CACHE_DRIVER=redis
# SESSION_DRIVER=redis
# QUEUE_CONNECTION=redis

# Test connection
cd /var/www/laravel-app
php artisan tinker
# Type: cache()->put('test', 'value')
# Type: cache()->get('test')

Configure config cache:

cd /var/www/laravel-app

# Cache configuration files (production optimization)
php artisan config:cache

# Cache routes
php artisan route:cache

# Cache views
php artisan view:cache

# Verify caches created
ls -la bootstrap/cache/

Clear caches when deploying:

cd /var/www/laravel-app

# Clear all caches
php artisan cache:clear

# Clear specific caches
php artisan config:clear
php artisan route:clear
php artisan view:clear

# Re-cache for production
php artisan config:cache
php artisan route:cache

Security Configuration

Implement security best practices.

Set secure file permissions:

# .env file should not be readable by others
sudo chmod 600 /var/www/laravel-app/.env

# Restrict storage directory
sudo chmod 750 /var/www/laravel-app/storage

Enable HTTPS only:

# In AppServiceProvider or middleware
# Force HTTPS in production

# app/Providers/AppServiceProvider.php
if ($this->app->environment('production')) {
    \Illuminate\Support\Facades\URL::forceScheme('https');
}

Set security headers via Nginx:

# Add to Nginx server block
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
add_header X-Frame-Options "DENY" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;

Configure Laravel security:

// config/session.php
'secure' => true,  // Only send over HTTPS
'http_only' => true,  // Prevent JavaScript access

// config/hashing.php
'driver' => 'bcrypt',  // Use bcrypt for passwords

// Disable debug in production
APP_DEBUG=false

Optimización del rendimiento

Optimize Laravel applications for production.

Enable OPcache monitoring:

# Monitor OPcache usage
php -r "phpinfo()" | grep -A 20 "opcache"

# Check OPcache hits/misses
redis-cli --stat

Optimize autoloader:

cd /var/www/laravel-app

# Generate optimized autoloader
composer dump-autoload --optimize

# Use classmap optimization
composer install --optimize-autoloader --no-dev

Monitor application:

# Check Laravel logs
tail -f /var/www/laravel-app/storage/logs/laravel.log

# Monitor PHP-FPM
ps aux | grep php-fpm

# Check database performance
# Enable slow query log in MySQL

Configure monitoring:

# Install Laravel Telescope (development) or Nova (admin panel)
# Or use external monitoring: New Relic, Datadog

# Basic log monitoring
watch -n 5 'tail /var/www/laravel-app/storage/logs/laravel.log'

Conclusión

Implementeing Laravel applications on Linux requires coordinated configuration of PHP-FPM, Nginx, database, and application-level settings. This guide provides a production-ready deployment covering LEMP stack setup, Laravel installation, database configuration, queue processing, and optimization. Key focus areas are proper permissions ensuring web server can write to storage and cache directories, Redis configuration for caching and queues, Supervisor for background job processing, and security hardening for production environments. Regular monitoring of logs and cache hit rates ensures smooth operation. Following these practices creates a robust Laravel deployment ready for production traffic.