Back to blog
Mei 12, 202534 min read
DevOps

How to Deploy Laravel Apps to Ubuntu Server

How to Deploy Laravel Apps to Ubuntu Server

From Localhost to Live: The Ultimate Guide to Deploying Laravel + React on Ubuntu Server

Keywords: Laravel deployment, React deployment, Ubuntu server, Nginx, Apache, production server, web server configuration, full-stack deployment, Linux, server setup, PHP, Node.js, Composer, npm, Git, SSL, performance optimization.

Ready to take your Laravel and React application from your local machine to a live server? This ultimate guide provides a step-by-step walkthrough on deploying your full-stack project on an Ubuntu Linux server. Learn how to configure Nginx (or Apache), set up PHP, Node.js, and MySQL, and optimize your application for high performance and user engagement. Stop wrestling with deployment and get your masterpiece online today!

In today's fast-paced web development landscape, combining the power of Laravel for robust backends and React for dynamic frontends is a winning formula. But bringing your beautifully crafted application from the cozy confines of your local machine to a live, production-ready environment can feel like a daunting journey. Fear not, fellow developers! This comprehensive guide will walk you through every essential step of deploying your Laravel + React application on a Linux Ubuntu server, optimized for performance and high user engagement.

Why Ubuntu for Your Laravel + React Stack?

Ubuntu, a popular and powerful Linux distribution, is a go-to choice for web servers due to its:

  • Stability and Security: A strong foundation for critical applications.
  • Vast Community Support: Easy access to solutions and assistance.
  • Rich Package Repositories: Simple installation of necessary software like PHP, Node.js, databases, and web servers.
  • Cost-Effectiveness: Free and open-source, ideal for budget-conscious projects.

Pre-Deployment Checklist: Setting the Stage

Before we dive into the nitty-gritty, ensure you have the following:

  • A Fresh Ubuntu Server: A clean install is recommended for a smooth deployment.
  • SSH Access: To connect securely to your server.
  • Domain Name: Pointed to your server's IP address.
  • Git Repository: Your Laravel and React projects should be in separate (or monorepo-structured) Git repositories for easy deployment.
  • Basic Linux Command Line Knowledge: Familiarity with sudo, cd, ls, nano, etc.

Step 1: Prepare Your Ubuntu Server Environment

First things first, let's update your server and install essential tools.

sudo apt update && sudo apt upgrade -y
sudo apt install curl git unzip apache2 (or nginx) -y

Note on Web Servers: You can choose between Apache or Nginx. Nginx is generally preferred for its performance with static content and acting as a reverse proxy, while Apache is known for its .htaccess flexibility. We'll provide configurations for both.

Install PHP and Required Extensions

Laravel relies heavily on PHP. We'll use the ondrej/php PPA for the latest PHP versions.

sudo add-apt-repository ppa:ondrej/php -y
sudo apt update
sudo apt install php8.2 php8.2-fpm php8.2-mysql php8.2-xml php8.2-mbstring php8.2-bcmath php8.2-tokenizer php8.2-curl php8.2-zip -y

(Adjust PHP version if needed, e.g., php8.3)

Install Composer

Composer is Laravel's dependency manager.

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

Install Node.js and npm

React requires Node.js and npm (Node Package Manager).

curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt-get install -y nodejs

(This installs the latest LTS version of Node.js)

Install MySQL Server (or PostgreSQL, etc.)

Your Laravel application will need a database.

sudo apt install mysql-server -y
sudo mysql_secure_installation

Follow the prompts to secure your MySQL installation. Then, create a database and user for your Laravel application:

sudo mysql -u root -p

# Inside MySQL prompt:
CREATE DATABASE your_laravel_db;
CREATE USER 'your_db_user'@'localhost' IDENTIFIED BY 'your_strong_password';
GRANT ALL PRIVILEGES ON your_laravel_db.* TO 'your_db_user'@'localhost';
FLUSH PRIVILEGES;
EXIT;

Step 2: Deploy Your Laravel Backend

Now, let's get your Laravel application onto the server.

Clone Your Laravel Project

Navigate to /var/www/ (or your preferred deployment directory) and clone your Laravel repository.

cd /var/www/
sudo git clone https://github.com/your-username/your-laravel-project.git laravel

Configure Laravel

Navigate into your Laravel project directory:

cd /var/www/laravel

Copy the example environment file and edit it with your database credentials and other production settings:

sudo cp .env.example .env
sudo nano .env

Key .env configurations:

  • APP_ENV=production
  • APP_DEBUG=false
  • APP_URL=https://your-domain.com (Use http initially if you haven't set up SSL yet)
  • DB_CONNECTION=mysql
  • DB_HOST=127.0.0.1
  • DB_PORT=3306
  • DB_DATABASE=your_laravel_db
  • DB_USERNAME=your_db_user
  • DB_PASSWORD=your_strong_password

Save and exit (Ctrl+X, then Y, then Enter).

Install Dependencies, Generate Key, and Run Migrations

sudo composer install --no-dev --optimize-autoloader
sudo php artisan key:generate
sudo php artisan migrate --force
sudo php artisan config:cache
sudo php artisan route:cache
sudo php artisan view:cache

Set Proper File Permissions

Crucial for Laravel's operation and security:

sudo chown -R www-data:www-data /var/www/laravel
sudo chmod -R 775 /var/www/laravel/storage
sudo chmod -R 775 /var/www/laravel/bootstrap/cache

Step 3: Build and Deploy Your React Frontend

Your React application will be served separately, typically as static assets.

Build Your React Application Locally

On your local development machine, navigate to your React project and build it for production:

cd /path/to/your/local/react-project
npm install
npm run build

This will create a build folder containing optimized static files.

Transfer React Build to Server

Use scp to transfer the build folder to your server. We'll place it in /var/www/react.

scp -r /path/to/your/local/react-project/build username@your-vps-ip:/var/www/react

Alternatively, you can clone your React repository on the server and build it there, especially if you plan to use CI/CD.

cd /var/www/
sudo git clone https://github.com/your-username/your-react-project.git react
cd /var/www/react
npm install
npm run build

Step 4: Configure Your Web Server (Nginx or Apache)

This is where your server directs traffic to your Laravel API and React frontend.

Option A: Nginx Configuration

We'll configure Nginx to serve the React app on your main domain and proxy API requests to your Laravel backend.

Create a new Nginx configuration file:

sudo nano /etc/nginx/sites-available/your_domain.com

Add the following configuration (replace your-domain.com and adjust paths as necessary):

server {
listen 80;
server_name your-domain.com www.your-domain.com;
root /var/www/react; # Path to your React build folder

index index.html index.htm;

location / {
try_files $uri $uri/ /index.html;
}

# Proxy API requests to Laravel
location /api {
proxy_pass http://127.0.0.1:8000; # Or your Laravel internal IP/port
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}

# Handle Laravel public folder
location ~ \.php$ {
return 404; # React handles non-API routes
}
}

server {
listen 8000; # Internal port for Laravel API
server_name your-domain.com; # Or your server's local IP
root /var/www/laravel/public;

add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
add_header Referrer-Policy "no-referrer-when-downgrade";
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload";

index index.php index.html index.htm;

charset utf-8;

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

location ~ \.php$ {
fastcgi_pass unix:/run/php/php8.2-fpm.sock; # Adjust PHP-FPM sock if needed
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
include fastcgi_params;
}

location ~ /\.(?!well-known).* {
deny all;
}
}

Enable the site and restart Nginx:

sudo ln -s /etc/nginx/sites-available/your_domain.com /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx

Option B: Apache Configuration

For Apache, you'll create two separate virtual hosts or configure a single one with proxy rules.

Virtual Host for React (Frontend)

sudo nano /etc/apache2/sites-available/react.conf
```apache

ServerAdmin webmaster@localhost
ServerName your-domain.com
ServerAlias [www.your-domain.com](https://www.your-domain.com)
DocumentRoot /var/www/react # Path to your React build folder


Options +FollowSymLinks
AllowOverride All
Require all granted


ErrorLog ${APACHE_LOG_DIR}/react_error.log
CustomLog ${APACHE_LOG_DIR}/react_access.log combined


Virtual Host for Laravel (Backend API)

sudo nano /etc/apache2/sites-available/laravel.conf
```apache
# Use an internal port or a subdomain if preferred
ServerAdmin webmaster@localhost
ServerName api.your-domain.com # Or your-domain.com if using path-based proxy
DocumentRoot /var/www/laravel/public


Options +FollowSymLinks
AllowOverride All
Require all granted


ErrorLog ${APACHE_LOG_DIR}/laravel_error.log
CustomLog ${APACHE_LOG_DIR}/laravel_access.log combined


Enable sites and modules, then restart Apache:

sudo a2ensite react.conf
sudo a2ensite laravel.conf
sudo a2enmod rewrite
sudo a2enmod proxy
sudo a2enmod proxy_http # Needed for proxying
sudo systemctl restart apache2

Important Apache Note: If you want to serve both React and Laravel on the same domain with Apache, you'll need to configure proxy rules within your main React virtual host to redirect API calls to the Laravel virtual host. This is more complex and Nginx handles this scenario more gracefully.

Step 5: Secure Your Applications with SSL (HTTPS)

HTTPS is non-negotiable for modern web applications. Let's Encrypt provides free SSL certificates.

sudo apt install certbot python3-certbot-apache (or python3-certbot-nginx) -y

For Apache:

sudo certbot --apache -d your-domain.com -d www.your-domain.com -d api.your-domain.com (if you have an API subdomain)

For Nginx:

sudo certbot --nginx -d your-domain.com -d www.your-domain.com -d api.your-domain.com (if you have an API subdomain)

Follow the prompts from Certbot. It will automatically configure your web server to use HTTPS and set up automatic renewals.

Step 6: Optimize for Production and User Engagement

Deployment isn't just about getting code live; it's about making it perform.

Process Management for Laravel Queues (Optional but Recommended)

If your Laravel app uses queues (e.g., for sending emails, processing images), Supervisor is essential to keep them running.

sudo apt install supervisor -y
sudo nano /etc/supervisor/conf.d/laravel-worker.conf
```ini
[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/laravel/artisan queue:work --tries=3 --sleep=3
autostart=true
autorestart=true
user=www-data
numprocs=2 # Adjust based on your server's capacity and queue load
redirect_stderr=true
stdout_logfile=/var/log/laravel-worker.log

Save, exit, and then:

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

Performance Monitoring

Keep an eye on your server's health and application performance.

sudo apt install htop net-tools -y

  • htop: For real-time process monitoring.
  • netstat -tulnp: To see active network connections and listening ports.
  • Laravel Logs: tail -f /var/www/laravel/storage/logs/laravel.log
  • Web Server Logs:
    • Nginx: /var/log/nginx/access.log and /var/log/nginx/error.log
    • Apache: /var/log/apache2/access.log and /var/log/apache2/error.log

Regular Updates and Maintenance

Set up a script for easy updates:

sudo nano /usr/local/bin/update-laravel-react
```bash
#!/bin/bash
cd /var/www/laravel
git pull
composer install --no-dev --optimize-autoloader
php artisan migrate --force
php artisan config:cache
php artisan route:cache
php artisan view:cache
sudo chown -R www-data:www-data /var/www/laravel

cd /var/www/react
git pull # Or use rsync if you only transfer the build folder
npm install
npm run build
sudo systemctl reload nginx # Or apache2

Make it executable: sudo chmod +x /usr/local/bin/update-laravel-react

Troubleshooting Common Issues

  • 500 Internal Server Error (Laravel):
    • Check storage/logs/laravel.log for specific errors.
    • Ensure file permissions are correct (sudo chown -R www-data:www-data /var/www/laravel).
    • Verify .env settings, especially database credentials.
  • React App Not Loading/Blank Screen:
    • Check your web server's error logs.
    • Ensure the DocumentRoot for your React site is pointing to the build folder correctly.
    • Verify the build folder contents are correctly transferred.
  • API Calls Failing from React:
    • Check your React app's axios.defaults.baseURL or similar API endpoint configuration to ensure it points to the correct Laravel API URL (https://your-domain.com/api or https://api.your-domain.com).
    • Check web server proxy settings (Nginx location /api or Apache ProxyPass).
    • Look for CORS (Cross-Origin Resource Sharing) errors in your browser's console. You might need to configure CORS in your Laravel application (e.g., using laravel-cors package).
  • Permission Denied: Almost always a chown or chmod issue. Double-check the recursive permissions.
  • Composer/NPM Commands Failing: Ensure you are in the correct directory and that Composer/Node.js are installed correctly and in your PATH.

SEO and User Engagement Considerations for Technical Articles

To ensure this article ranks high and engages its audience, we've implemented the following strategies:

  • Keyword Optimization: Strategically placed relevant keywords like "Laravel deployment," "React deployment," "Ubuntu server," and "web server configuration" throughout the title, headings, and body.
  • Clear and Concise Structure: Using headings, subheadings, bullet points, and code blocks for easy readability and scannability, catering to developers who often skim for solutions.
  • Actionable Steps: Providing clear, step-by-step instructions with direct commands for users to follow.
  • Practical Examples: Including concrete code snippets for server configurations.
  • Problem-Solving Focus: Addressing common issues with a dedicated "Troubleshooting" section.
  • High-Value Content: Offering a comprehensive guide that covers the entire deployment process, aiming to be a one-stop resource.
  • Mobile-Friendly Formatting: Ensuring the article is easily readable on various devices.
  • Internal Linking (if applicable): If this were part of a larger blog, we'd link to related articles (e.g., "Introduction to Laravel," "Getting Started with React").
  • Call to Action (Implied): Encouraging readers to apply these steps and successfully deploy their applications.

By following this guide, you're not just deploying a Laravel and React application; you're building a robust, secure, and performant web presence on a reliable Ubuntu server. Happy deploying!

© 2026 Dimas Eka Putra. All rights reserved.
Built with hope by Dimas Eka Putra
How to Deploy Laravel Apps to Ubuntu Server