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

by Team 48 views
Install Laravel on Ubuntu: A Step-by-Step Guide

So, you want to install Laravel on your Ubuntu server? Awesome! You've come to the right place. This guide will walk you through the entire process, step-by-step, making it super easy even if you're not a Linux guru. We'll cover everything from setting up your server environment to finally running your brand-new Laravel application. Let's dive in!

Prerequisites

Before we get started installing Laravel on Ubuntu, let's make sure you have a few things in place. Think of it as gathering your ingredients before you start cooking up a delicious Laravel application.

  • An Ubuntu Server: Obviously, you'll need an Ubuntu server. It could be a virtual private server (VPS) from providers like DigitalOcean, AWS, or Linode, or even a local virtual machine using VirtualBox or VMware. Make sure you have SSH access to it.
  • Basic Linux Knowledge: A little familiarity with the Linux command line will be helpful. You should know how to connect to your server via SSH, run basic commands, and navigate the file system. Don't worry, you don't need to be a wizard, just comfortable enough to type in some commands.
  • A User Account with sudo Privileges: You'll need a user account that has sudo privileges. This allows you to run commands as the superuser (root), which is necessary for installing software and configuring your system. It's generally a bad idea to log in directly as the root user, so using sudo is the preferred way to go.

Having these prerequisites sorted will make the installation process much smoother. If you're missing any of these, take a few minutes to get them set up before moving on. Trust me, it'll save you headaches later!

Step 1: Update and Upgrade Your System

First things first, let's make sure your Ubuntu server is up to date. Think of it like giving your server a health check and ensuring it has all the latest patches and updates. This is crucial for security and stability.

Connect to your server via SSH using your terminal. Once you're logged in, run the following commands:

sudo apt update
sudo apt upgrade

The sudo apt update command updates the package lists. It's like refreshing the list of available software. The sudo apt upgrade command then upgrades all the installed packages to their latest versions. This might take a few minutes, depending on how long it's been since the last update. Just sit back and let it do its thing.

During the upgrade process, you might be prompted to confirm certain changes or restart services. Just follow the prompts and answer yes when asked. Once the upgrade is complete, it's a good idea to reboot your server to ensure all the changes take effect. You can do this with the following command:

sudo reboot

After the reboot, reconnect to your server via SSH. Now you're ready to move on to the next step, knowing that your system is up to date and running smoothly. Keeping your system updated is a good habit to get into, as it helps prevent security vulnerabilities and ensures you have the latest features and bug fixes.

Step 2: Install PHP and Required Extensions

Laravel is a PHP framework, so you'll need to have PHP installed on your server. You'll also need to install some PHP extensions that Laravel relies on. Don't worry, it's not as complicated as it sounds!

Run the following command to install PHP and the necessary extensions:

sudo apt install php php-cli php-fpm php-json php-mysql php-zip php-gd php-mbstring php-xml

Let's break down what each of these packages does:

  • php: This is the core PHP package.
  • php-cli: This provides the PHP command-line interface, which you'll use for running Artisan commands.
  • php-fpm: This is the PHP FastCGI Process Manager, which is used for running PHP applications with web servers like Nginx or Apache.
  • php-json: This provides support for JSON encoding and decoding.
  • php-mysql: This allows PHP to connect to MySQL databases.
  • php-zip: This provides support for working with ZIP archives.
  • php-gd: This provides support for image processing.
  • php-mbstring: This provides support for multibyte strings.
  • php-xml: This provides support for XML processing.

Once the installation is complete, you can verify that PHP is installed correctly by running the following command:

php -v

This will display the PHP version that's installed on your server. Make sure it's PHP 7.4 or higher, as Laravel requires at least PHP 7.4.

Next, you'll want to configure PHP-FPM to work with your web server. The exact configuration will depend on which web server you're using (Nginx or Apache), but we'll cover that in more detail later. For now, just make sure PHP and the required extensions are installed correctly.

Step 3: Install Composer

Composer is a dependency manager for PHP. It allows you to easily install and manage the dependencies that your Laravel application needs. Think of it like npm for Node.js or pip for Python.

To install Composer, run the following commands:

sudo apt install curl
curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer

The first command installs curl, which is a command-line tool for transferring data with URLs. The second command downloads the Composer installer and runs it using PHP. This will install Composer globally on your system, so you can use it from any directory.

After the installation is complete, you can verify that Composer is installed correctly by running the following command:

composer -v

This will display the Composer version that's installed on your server. If you see the version number, then Composer is installed correctly.

Composer makes it incredibly easy to manage your project's dependencies. You can define the dependencies in a composer.json file, and then use Composer to install, update, and remove them. This helps ensure that your project has all the necessary libraries and that they're all compatible with each other.

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

To serve your Laravel application to the world, you'll need a web server. The two most popular choices are Nginx and Apache. Both are excellent choices, but Nginx is generally considered to be faster and more efficient, especially for serving static content. In this guide, we'll cover how to install and configure Nginx. If you prefer Apache, the process is similar, but the configuration files will be different.

Installing Nginx

To install Nginx, run the following command:

sudo apt install nginx

After the installation is complete, you can verify that Nginx is running by opening your server's IP address in a web browser. You should see the default Nginx welcome page.

Configuring Nginx for Laravel

Now, you need to configure Nginx to serve your Laravel application. Create a new Nginx configuration file for your application. You can name it whatever you want, but it's a good idea to use your application's domain name. For example, if your application's domain name is example.com, you can name the configuration file example.com.

Create the configuration file in the /etc/nginx/sites-available/ directory. You can use your favorite text editor to create the file. For example, to use nano, run the following command:

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

Replace example.com with your application's domain name. Then, add the following configuration to the file:

server {
    listen 80;
    server_name example.com;
    root /var/www/example.com/public;

    index index.php index.html index.htm;

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

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php7.4-fpm.sock;
    }

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

Replace example.com with your application's domain name and /var/www/example.com/public with the path to your Laravel application's public directory.

Let's break down what each of these directives does:

  • listen 80: This tells Nginx to listen on port 80, which is the default port for HTTP traffic.
  • server_name example.com: This specifies the domain name that this configuration should handle.
  • root /var/www/example.com/public: This specifies the root directory for your application.
  • index index.php index.html index.htm: This specifies the order in which Nginx should look for index files.
  • location /: This defines how Nginx should handle requests for the root directory.
  • try_files $uri $uri/ /index.php?$query_string: This tells Nginx to try serving the requested URI as a file or directory. If neither exists, it passes the request to index.php.
  • location ~ \.php$: This defines how Nginx should handle requests for PHP files.
  • include snippets/fastcgi-php.conf: This includes the standard FastCGI configuration for PHP.
  • fastcgi_pass unix:/run/php/php7.4-fpm.sock: This specifies the path to the PHP-FPM socket.
  • location ~ /\.ht: This denies access to .htaccess files.

After you've created the configuration file, you need to enable it by creating a symbolic link from the /etc/nginx/sites-available/ directory to the /etc/nginx/sites-enabled/ directory. You can do this with the following command:

sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/

Replace example.com with your application's domain name. Then, restart Nginx to apply the changes:

sudo systemctl restart nginx

Now, Nginx is configured to serve your Laravel application. You're ready to move on to the next step, which is installing Laravel itself.

Step 5: Create a Laravel Project

Now comes the exciting part: creating your Laravel project! Navigate to the directory where you want to install your Laravel application. This is usually the /var/www/ directory. You can use the cd command to change directories:

cd /var/www/

Then, run the following command to create a new Laravel project:

composer create-project --prefer-dist laravel/laravel example.com

Replace example.com with your application's domain name or the name you want to give your project. This command will download Laravel and all its dependencies and create a new directory with the specified name.

After the project is created, you need to set the correct permissions for the storage and bootstrap/cache directories. These directories need to be writable by the web server user. You can do this with the following commands:

sudo chown -R www-data:www-data /var/www/example.com/storage
sudo chown -R www-data:www-data /var/www/example.com/bootstrap/cache
sudo chmod -R 775 /var/www/example.com/storage
sudo chmod -R 775 /var/www/example.com/bootstrap/cache

Replace /var/www/example.com with the path to your Laravel application. These commands change the ownership of the directories to the www-data user and group, which is the user that Nginx runs as. They also set the permissions to allow the web server user to write to the directories.

Step 6: Configure Environment Variables

Laravel uses environment variables to store configuration settings. These variables are defined in the .env file in your application's root directory. You'll need to configure some of these variables to match your server environment.

First, copy the .env.example file to .env:

cp .env.example .env

Then, open the .env file in your favorite text editor. For example, to use nano, run the following command:

nano .env

You'll need to configure the following variables:

  • APP_NAME: This is the name of your application.
  • APP_ENV: This should be set to production on a production server.
  • APP_DEBUG: This should be set to false on a production server.
  • APP_URL: This should be set to your application's URL.
  • DB_CONNECTION: This should be set to the database connection you're using (e.g., mysql, pgsql, sqlite).
  • DB_HOST: This should be set to the hostname of your database server.
  • DB_PORT: This should be set to the port number of your database server.
  • DB_DATABASE: This should be set to the name of your database.
  • DB_USERNAME: This should be set to the username for your database.
  • DB_PASSWORD: This should be set to the password for your database.

Make sure to set these variables to the correct values for your environment. Once you've configured the environment variables, you need to generate an application key. This key is used to encrypt sensitive data, such as passwords and session data. You can generate an application key by running the following command:

php artisan key:generate

This will generate a new application key and store it in the APP_KEY environment variable. Make sure to keep this key secret, as it's essential for the security of your application.

Step 7: Configure the Database

If your Laravel application uses a database, you'll need to create a database and configure your application to connect to it. The exact steps will depend on which database you're using, but we'll cover the basics for MySQL.

First, log in to your MySQL server as the root user:

mysql -u root -p

You'll be prompted for the root password. Enter the password and press Enter. Then, create a new database for your Laravel application:

CREATE DATABASE example_db;

Replace example_db with the name you want to give your database. Then, create a new user for your application:

CREATE USER 'example_user'@'localhost' IDENTIFIED BY 'password';

Replace example_user with the username you want to use and password with the password for the user. Make sure to choose a strong password. Then, grant the user privileges to the database:

GRANT ALL PRIVILEGES ON example_db.* TO 'example_user'@'localhost';

Replace example_db with the name of your database and example_user with the username you created. Then, flush the privileges to apply the changes:

FLUSH PRIVILEGES;

Finally, exit the MySQL shell:

exit;

Now, you need to configure your Laravel application to connect to the database. Open the .env file and set the following variables:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=example_db
DB_USERNAME=example_user
DB_PASSWORD=password

Replace example_db with the name of your database, example_user with the username you created, and password with the password for the user. Now your Laravel application is configured to connect to the database.

Step 8: Run Migrations

Laravel uses migrations to manage your database schema. Migrations are PHP files that define the structure of your database tables. You can use migrations to create, modify, and delete tables in a controlled and repeatable way.

To run the migrations, run the following command:

php artisan migrate

This will run all the pending migrations and create the necessary tables in your database. If you're starting a new project, this will create the default users and password_resets tables.

Step 9: Access Your Application

Congratulations! You've successfully installed Laravel on your Ubuntu server. Now you can access your application by opening your server's IP address or domain name in a web browser.

If you've configured your web server correctly, you should see the default Laravel welcome page. If you don't see the welcome page, check your web server configuration and make sure that the root directory is set to the public directory of your Laravel application.

You can also try creating a simple route to test that your application is working correctly. Open the routes/web.php file and add the following route:

Route::get('/test', function () {
    return 'Hello, world!';
});

Then, access the /test route in your web browser. You should see the message "Hello, world!" displayed.

Conclusion

Installing Laravel on an Ubuntu server might seem daunting at first, but by following these steps, you can get your application up and running in no time. Remember to keep your system updated, configure your environment variables correctly, and use migrations to manage your database schema. With a little practice, you'll be deploying Laravel applications like a pro!

Happy coding, guys!