Install Laravel On Ubuntu Server: A Step-by-Step Guide

by Jhon Lennon 55 views

Hey guys! So, you're looking to get Laravel up and running on your Ubuntu server? Awesome choice! Laravel is a super popular PHP framework that makes building web applications a breeze. Whether you're a seasoned pro or just dipping your toes into the world of web development, this guide is for you. We're going to walk through the entire process, from setting up your server to deploying your first Laravel app. Stick around, because by the end of this, you'll have a fully functional Laravel environment ready for action. Let's dive in!

Prerequisites: What You'll Need Before We Start

Alright, before we get our hands dirty with the installation, let's make sure you've got all your ducks in a row. Having these essentials sorted beforehand will make the entire process smoother, trust me. First off, you'll need access to an Ubuntu server. This could be a VPS, a dedicated server, or even a local machine running Ubuntu. You'll need SSH access to your server, which is pretty standard for server management. Make sure you can log in without any issues. Second, you'll need sudo privileges. This means you can execute commands as the superuser, which is necessary for installing software and configuring services. If you're not sure how to get sudo access, you might need to check with your server administrator or hosting provider.

The core software you'll need installed on your server includes:

  • A web server: The most common choices are Apache or Nginx. We'll cover setting up a LEMP stack (Linux, Nginx, MySQL, PHP) or a LAMP stack (Linux, Apache, MySQL, PHP) as part of this guide, but if you already have one running, that's great!
  • PHP: Laravel, being a PHP framework, obviously requires PHP. We'll need a specific version, usually the latest stable release or one recommended by the Laravel documentation. You'll also need several PHP extensions that Laravel relies on. We'll list these out shortly.
  • A database: Most web applications need a database to store data. MySQL or PostgreSQL are excellent choices. We'll assume you're going with MySQL for this guide as it's very common, but the principles apply to others too.
  • Composer: This is the dependency manager for PHP. It's absolutely crucial for installing Laravel and its packages. If you don't have it yet, no worries, we'll show you how to install it.

Don't panic if you don't have all of these yet! We're going to install and configure everything step-by-step. The key is to have a clean Ubuntu server and the ability to run commands. If you're starting from scratch, it's often best to begin with a fresh Ubuntu installation. This ensures there are no conflicting configurations. So, get your server ready, make sure you can log in via SSH, and let's move on to the fun part: installing all the necessary software!

Step 1: Update Your Ubuntu Server

Alright guys, the very first thing we always do before installing anything on a Linux server is to update the package lists and upgrade the existing packages. This is super important for security and ensures you're working with the latest versions of software available in the repositories. Think of it as giving your server a good spring clean before we add new stuff.

Open up your SSH client, connect to your Ubuntu server, and let's get these commands rolling. You'll need to use sudo for these, so make sure you're logged in with an account that has sudo privileges.

First, let's update the package index:

sudo apt update

This command fetches the latest information about available packages from all the configured repositories. It doesn't actually install or upgrade any software; it just refreshes the list so your system knows what's available and what updates are pending. You'll see a bunch of lines scrolling by as it contacts the repositories and downloads the package information. It should be pretty quick.

Once that's done, we'll run the upgrade command:

sudo apt upgrade -y

The -y flag is a nice little shortcut that automatically answers 'yes' to any prompts during the upgrade process. Without it, you'd have to manually confirm each package upgrade, which can be tedious, especially if there are many updates. This command will download and install the newest versions of all packages currently installed on your system. This can take a little longer, depending on how many updates are available and your server's internet speed. It's a good idea to run this regularly on your servers, not just when you're installing new software.

Sometimes, there are also newer kernel versions or other core system components that require a reboot to take effect. While not strictly necessary for every update, it's good practice to perform a reboot after a significant upgrade. You can do this with:

sudo reboot

Just be aware that this will disconnect your SSH session, and you'll need to reconnect after the server restarts. If you're on a production server, you might want to schedule this during a low-traffic period.

Why is this step so crucial?

  • Security: Updates often patch security vulnerabilities. Keeping your system updated is your first line of defense against many cyber threats.
  • Stability: Newer versions might fix bugs that could cause instability or unexpected behavior in your applications.
  • Compatibility: When installing new software like Laravel, having an up-to-date system, especially PHP and related libraries, can prevent compatibility issues down the line.

So, yeah, don't skip this step, guys! It's the foundation for a healthy server environment. Once your server is updated and (optionally) rebooted, we're ready to move on to installing the core components needed for Laravel.

Step 2: Install PHP and Required Extensions

Alright, time to get PHP installed! Laravel is a PHP framework, so this is a pretty big step. We'll also need to install some specific PHP extensions that Laravel relies on to function correctly. The version of PHP you need might vary slightly depending on the specific Laravel version you plan to use, but generally, the latest stable version supported by your Ubuntu version is a safe bet. We'll aim for a recent version that's readily available in the Ubuntu repositories.

First, let's install PHP along with some essential extensions. Open your SSH terminal and run the following command:

sudo apt install php php-cli php-fpm php-json php-common php-mysql php-zip php-gd php-mbstring php-curl php-xml php-pear php-bcmath

Let's break down what we're installing here:

  • php: This is the core PHP package.
  • php-cli: The command-line interface for PHP, essential for running Artisan commands.
  • php-fpm: FastCGI Process Manager. This is crucial for integrating PHP with web servers like Nginx or Apache, especially for performance.
  • php-json: For handling JSON data, which is used extensively in modern web applications.
  • php-common: Common files needed by other PHP modules.
  • php-mysql: Allows PHP to communicate with MySQL databases. Super important if you're using MySQL!
  • php-zip: For handling zip archives.
  • php-gd: For image manipulation.
  • php-mbstring: For handling multi-byte strings, essential for international characters.
  • php-curl: For making HTTP requests from PHP.
  • php-xml: For working with XML data.
  • php-pear: A package repository for PHP, sometimes needed for certain functionalities.
  • php-bcmath: For arbitrary precision mathematics, useful for financial calculations or when you need high precision.

This command installs PHP and a good set of common extensions. If Laravel's documentation later specifies other extensions you need, you can always install them using sudo apt install php-<extension_name>.

After the installation is complete, it's a good idea to check your PHP version to make sure everything installed correctly. You can do this with:

php -v

This should output the installed PHP version. You can also check if the extensions are enabled:

php -m

This command lists all the loaded PHP modules. Scroll through the list to ensure the extensions we installed are present. You should see json, mysql, zip, gd, mbstring, curl, xml, pear, and bcmath in the output.

What if you need a specific PHP version?

Sometimes, the default PHP version in your Ubuntu repositories might not be the latest or the one required by a specific Laravel version. In such cases, you might need to add a third-party PPA (Personal Package Archive) like Ondřej Surý's PPA. For example, to install PHP 8.2, you'd typically do:

sudo add-apt-repository ppa:ondrej/php
sudo apt update
sudo apt install php8.2 php8.2-cli php8.2-fpm php8.2-json php8.2-common php8.2-mysql php8.2-zip php8.2-gd php8.2-mbstring php8.2-curl php8.2-xml php8.2-pear php8.2-bcmath

Remember to replace 8.2 with your desired PHP version. Always check the official Laravel documentation for the recommended PHP version for the Laravel release you're using.

With PHP and its essential extensions installed, we're getting closer! Next up, we need a database system.

Step 3: Install a Database Server (MySQL)

Alright, your web applications need a place to store all that juicy data, right? That's where a database comes in. We're going to install MySQL Server, which is a very popular and robust relational database management system. It integrates perfectly with Laravel and is widely used in the web development world. If you prefer PostgreSQL, the installation process is similar, but we'll stick with MySQL for this guide.

Let's get MySQL Server installed on your Ubuntu server. Run this command:

sudo apt install mysql-server

This will download and install the MySQL server package and its dependencies. Once the installation is complete, it's highly recommended to run the security script that comes with MySQL. This script helps you secure your installation by removing insecure default settings, disabling remote root login, and removing anonymous users.

Run the security script with:

sudo mysql_secure_installation

When you run this script, you'll be prompted with several questions:

  1. VALIDATE PASSWORD COMPONENT: You can choose to enable this to enforce strong password policies. It's a good idea to enable it for better security. If you enable it, you'll select a password strength level.
  2. New password for root user: Set a strong password for the MySQL root user. Remember this password! You'll need it to manage your MySQL databases.
  3. Remove anonymous users? Press Y and Enter. Anonymous users are a security risk.
  4. Disallow root login remotely? Press Y and Enter. It's best practice to only allow root login from localhost.
  5. Remove test database and access to it? Press Y and Enter. The test database is not needed for production environments.
  6. Reload privilege tables now? Press Y and Enter. This applies the changes you've made.

After running mysql_secure_installation, your MySQL server is much more secure. Now, let's test if you can log in to MySQL. You can log in as the root user using:

sudo mysql

If you set a password for the root user during the security script and it prompts for it, enter it. If not, sudo mysql should log you in directly using the operating system's authentication method. You should see the MySQL prompt (mysql>). Type exit; to leave.

Creating a Database and User for Laravel:

In a real-world scenario, you wouldn't use the root MySQL user for your Laravel application. It's best practice to create a dedicated database and a specific user for your Laravel project with limited privileges. Here's how you can do that:

First, log into MySQL:

sudo mysql

Then, execute the following SQL commands, replacing laravel_db, laravel_user, and your_strong_password with your desired names and a secure password:

CREATE DATABASE laravel_db;
CREATE USER 'laravel_user'@'localhost' IDENTIFIED BY 'your_strong_password';
GRANT ALL PRIVILEGES ON laravel_db.* TO 'laravel_user'@'localhost';
FLUSH PRIVILEGES;
EXIT;
  • CREATE DATABASE laravel_db;: Creates a new database named laravel_db.
  • CREATE USER 'laravel_user'@'localhost' IDENTIFIED BY 'your_strong_password';: Creates a new user named laravel_user that can only connect from localhost, and sets their password.
  • GRANT ALL PRIVILEGES ON laravel_db.* TO 'laravel_user'@'localhost';: Gives this new user full control over the laravel_db database.
  • FLUSH PRIVILEGES;: Reloads the grant tables, making the new privileges effective immediately.

Now you have a secure MySQL server ready with a dedicated database and user for your Laravel application. We're making great progress, guys! The next crucial step is installing Composer.

Step 4: Install Composer

Composer is the de facto standard package manager for PHP. You absolutely need it to install Laravel and any other PHP libraries your project might use. It handles dependencies, meaning it downloads and installs all the required code for your project to work. If you try to install Laravel without Composer, you're going to have a very bad time!

Let's get Composer installed globally on your Ubuntu server so you can use it from anywhere. First, we need to navigate to a directory where we can download the installer script. The /tmp directory is a good temporary place for this.

cd /tmp

Now, download the Composer installer script using curl. If you don't have curl installed, you can install it with sudo apt install curl first.

curl -s https://getcomposer.org/installer -o composer-setup.php

This command downloads the installer and saves it as composer-setup.php in your current directory (/tmp). The -s flag makes curl silent, and -o specifies the output file name.

Next, we need to verify the installer's signature to ensure it hasn't been tampered with. You can find the latest installer hash on the Composer Public Keys / Signatures page. Always check this page for the most current hash! As of my last update, the hash might look something like this (but please check the official site for the current one!):

EXPECTED_CHECKSUM='...' # Replace with the actual checksum from composer.org
php -r "if (hash_file('sha384', 'composer-setup.php') === '$EXPECTED_CHECKSUM') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"

Make sure you replace EXPECTED_CHECKSUM='...' with the actual SHA384 hash you find on the Composer website. If the output says "Installer verified", you're good to go. If it says "Installer corrupt", re-download the installer script.

Once verified, you can run the installer to install Composer globally. We'll install it into /usr/local/bin/composer so it's available system-wide.

sudo php composer-setup.php --install-dir=/usr/local/bin --filename=composer

This command executes the installer script. The --install-dir flag tells it where to put the composer executable, and --filename sets the name of the executable file.

Finally, clean up the installer script:

rm composer-setup.php

Now, let's verify that Composer was installed correctly. You can check its version:

composer --version

This should output the installed Composer version. If you see a version number, congratulations, Composer is installed and ready to use! This is a huge milestone, guys. With PHP, MySQL, and Composer all set up, we are so close to installing Laravel itself.

Step 5: Install a Web Server (Nginx or Apache)

We need a web server to handle incoming requests from users and serve your Laravel application. The two most popular choices on Linux are Nginx and Apache. Both are excellent, but Nginx is often preferred for its performance and efficiency, especially for serving static content and handling many concurrent connections. We'll show you how to set up Nginx, but the steps for Apache are similar.

Installing and Configuring Nginx

If you don't already have Nginx installed, let's get it:

sudo apt install nginx

Once Nginx is installed, it should start automatically. You can check its status:

sudo systemctl status nginx

You should see output indicating that Nginx is active (running). To test if Nginx is working, open your web browser and navigate to your server's IP address (e.g., http://your_server_ip). You should see the default Nginx welcome page. If you don't see it, ensure your server's firewall isn't blocking port 80 (HTTP). If you're using ufw (Uncomplicated Firewall), you can allow Nginx traffic like this:

sudo ufw allow 'Nginx Full'
sudo ufw enable

Now, we need to configure Nginx to serve your Laravel application. When you create a new Laravel project, you'll typically place its files in a directory like /var/www/html/your-project-name. For each Laravel project, you'll create a separate Nginx server block (similar to Apache's Virtual Hosts).

Let's create a directory for our first Laravel project (we'll install Laravel in the next step). We'll call it my-laravel-app for now:

sudo mkdir -p /var/www/my-laravel-app/public

Now, create an Nginx server block configuration file for this project. It's standard practice to name the file after your domain name, or just a descriptive name if you're not using a domain yet.

sudo nano /etc/nginx/sites-available/my-laravel-app

Paste the following configuration into the file. Remember to replace your_server_ip_or_domain with your server's IP address or domain name:

server {
    listen 80;
    listen [::]:80;

    root /var/www/my-laravel-app/public;
    index index.php index.html index.htm;

    server_name your_server_ip_or_domain;

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

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php8.1-fpm.sock; # Adjust PHP version if necessary
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.ht {
        deny all;
    }
}

Important Notes on the Nginx Configuration:

  • listen 80; and listen [::]:80;: Tells Nginx to listen on port 80 for IPv4 and IPv6 connections.
  • root /var/www/my-laravel-app/public;: This is the document root for your application. Crucially, for Laravel, this should point to the public directory inside your Laravel project folder, as that's where the index.php file resides and where all public assets are served from.
  • index index.php index.html index.htm;: Defines the default index file.
  • server_name your_server_ip_or_domain;: Specifies the domain name or IP address this server block should respond to.
  • location / { ... }: This block handles all requests. try_files tells Nginx to look for the requested file or directory, and if not found, to pass the request to index.php.
  • location ~ \.php$ { ... }: This block handles requests for PHP files. fastcgi_pass tells Nginx where to send PHP requests. You might need to adjust php8.1-fpm.sock to match the actual PHP version you installed (e.g., php8.2-fpm.sock). Check /var/run/php/ to see the correct filename.
  • location ~ /\.ht { deny all; }: This prevents access to .htaccess files, which Laravel uses but shouldn't be publicly accessible.

Save the file (Ctrl+X, then Y, then Enter in nano).

Now, enable this server block by creating a symbolic link to the sites-enabled directory:

sudo ln -s /etc/nginx/sites-available/my-laravel-app /etc/nginx/sites-enabled/

It's also a good idea to remove the default Nginx configuration to avoid conflicts:

sudo rm /etc/nginx/sites-enabled/default

Test your Nginx configuration for syntax errors:

sudo nginx -t

If it reports syntax is ok and test is successful, reload Nginx to apply the changes:

sudo systemctl reload nginx

If you encounter issues, double-check the configuration file and the fastcgi_pass path for your PHP-FPM version.

Step 6: Install Laravel

Finally, the moment we've all been waiting for – installing Laravel! We'll use Composer for this. Make sure you're logged in as the user who will own the project files, and navigate to the directory where you want to install your application. We previously created /var/www/my-laravel-app, so let's go there.

cd /var/www

Now, use Composer to create a new Laravel project. Replace my-laravel-app with your desired project name:

composer create-project --prefer-dist laravel/laravel my-laravel-app

This command tells Composer to download the laravel/laravel package and create a new project from it. --prefer-dist tells Composer to prefer installation from zipped packages rather than from source control, which is usually faster. This process might take a few minutes as Composer downloads Laravel and all its dependencies.

Once Composer finishes, your Laravel application files will be in the my-laravel-app directory. However, we need to make sure the web server (Nginx) can access these files and, more importantly, that Laravel can write to certain directories (like storage and bootstrap/cache).

We need to adjust ownership and permissions. It's common practice to have the web server (often running as the www-data user on Ubuntu) own the project files or at least have write permissions to specific directories. Let's set the ownership to www-data for the entire project directory:

sudo chown -R www-data:www-data /var/www/my-laravel-app

And ensure the storage and bootstrap/cache directories have the correct write permissions for the web server:

sudo chmod -R 775 storage
sudo chmod -R 775 bootstrap/cache

Note: Some security recommendations suggest not giving www-data ownership of the entire project, but rather managing permissions more granularly. For simplicity in this guide, chown -R www-data:www-data is often used. However, be mindful of security implications in production environments.

Crucially, your Nginx configuration needs to point to the public directory within your Laravel project. We already set this up in Step 5, but let's revisit it. Ensure your Nginx server block file (/etc/nginx/sites-available/my-laravel-app) has the root directive set correctly:

root /var/www/my-laravel-app/public;

If you created the Nginx config before installing Laravel, you'll need to edit it now:

sudo nano /etc/nginx/sites-available/my-laravel-app

Make sure the root directive is pointing to /var/www/my-laravel-app/public and that the fastcgi_pass directive matches your PHP-FPM version.

After updating the Nginx config, test and reload:

sudo nginx -t
sudo systemctl reload nginx

Now, if you visit http://your_server_ip_or_domain in your browser, you should see the default Laravel welcome page! If you see a