Install Laravel on Ubuntu with Apache or Nginx

Posted on

Install Laravel on Ubuntu with Apache or Nginx

Install Laravel on Ubuntu with Apache or Nginx

Laravel is a highly regarded PHP framework celebrated for its clean, expressive syntax and a rich set of features. This comprehensive tutorial will walk you through installing Laravel on Ubuntu 18.04/20.04/22.04 and Debian systems, utilizing both Apache and Nginx as web servers. The instructions are designed to be clear and straightforward, ensuring a seamless installation experience. Let’s begin!

Prerequisites

Before proceeding with the installation, ensure you have the following:

  1. An Ubuntu 18.04/20.04/22.04 or Debian system.
  2. A user account with sudo privileges.
  3. Basic familiarity with the command line.

Step 1: Update System Packages

Start by updating your system’s package list and upgrading installed packages to their latest versions. This ensures you have the most recent security patches and software updates. Open a terminal and execute the following commands:

$ sudo apt update
$ sudo apt upgrade

Step 2: Install PHP and Required Extensions

Laravel requires PHP and several specific extensions to function correctly. Install PHP and the necessary extensions using the following command:

$ sudo apt install php php-cli php-common php-mbstring php-xml php-zip php-mysql php-pgsql php-sqlite3 php-json php-bcmath php-gd php-tokenizer php-xmlwriter

After the installation is complete, verify the installed PHP version by running:

$ php -v

This command will display the PHP version number, confirming that PHP has been installed successfully.

Step 3: Install Composer

Composer is a dependency management tool for PHP projects. Laravel relies on Composer to manage its dependencies. Install Composer globally using the following commands:

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

Verify the Composer installation by running:

$ composer --version

This command will display the Composer version number, indicating that Composer has been installed correctly.

Step 4: Install Laravel

With Composer installed, you can now install Laravel. Navigate to the document root of your web server. For Apache, the document root is typically located at /var/www/html, and for Nginx, it is usually at /var/www.

Install Laravel using the following command:

$ composer create-project --prefer-dist laravel/laravel your-project-name

Replace your-project-name with the desired name for your Laravel project. Composer will download the Laravel framework and its dependencies. This process may take a few minutes, depending on your internet connection speed.

Once the installation is complete, navigate to the project directory:

$ cd your-project-name

Step 5: Configure Apache

If you are using Apache as your web server, follow these steps to configure it for Laravel.

Create a new Apache configuration file for your Laravel project:

$ sudo nano /etc/apache2/sites-available/your-project-name.conf

Replace your-project-name with the actual name of your project.

Add the following content to the configuration file:

<VirtualHost *:80>
    ServerName your-domain-or-ip
    DocumentRoot /var/www/html/your-project-name/public
    <Directory /var/www/html/your-project-name>
        AllowOverride All
    </Directory>
</VirtualHost>

Replace your-domain-or-ip with your actual domain name or server IP address.

Enable the Apache rewrite module:

$ sudo a2enmod rewrite

Enable the virtual host:

$ sudo a2ensite your-project-name.conf

Restart Apache for the changes to take effect:

$ sudo systemctl restart apache2

Step 6: Configure Nginx

If you are using Nginx as your web server, follow these steps to configure it for Laravel.

Create a new Nginx server block for your Laravel project:

$ sudo nano /etc/nginx/sites-available/your-project-name

Replace your-project-name with the actual name of your project.

Add the following content to the server block:

server {
    listen 80;
    server_name your-domain-or-ip;
    root /var/www/html/your-project-name/public;
    index index.php;
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }
    location ~ .php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
    }
    location ~ /.ht {
        deny all;
    }
}

Replace your-domain-or-ip with your actual domain name or server IP address. Adjust the fastcgi_pass if you are using a different PHP version.

Enable the Nginx server block:

$ sudo ln -s /etc/nginx/sites-available/your-project-name /etc/nginx/sites-enabled/

Test the Nginx configuration for any syntax errors:

$ sudo nginx -t

Restart Nginx for the changes to take effect:

$ sudo systemctl restart nginx

Step 7: Configure Laravel

Now that your web server is configured, let’s set up Laravel.

Copy the example .env file:

$ cp .env.example .env

Generate a new application key:

$ php artisan key:generate

Set the appropriate permissions on Laravel directories:

$ sudo chown -R www-data:www-data /var/www/html/your-project-name/storage
$ sudo chmod -R 775 /var/www/html/your-project-name/storage

You’re ready to use Laravel! Access your Laravel application in a web browser by visiting your domain name or server IP address.

Important:
The .env file in Laravel contains sensitive configuration information, including database credentials and API keys. Securing this file is crucial to protect your application from unauthorized access and security breaches. To enhance security, you can move the .env file outside the document root, restrict file permissions, disable directory browsing, encrypt sensitive information, and avoid storing production credentials in version control. Implementing these measures helps protect your application’s sensitive data and maintain its security. Regularly reviewing and updating security practices is important to stay proactive against potential threats.

Alternative Solutions for Installing Laravel

While the method described above is a standard and reliable approach, other options exist for installing Laravel on Ubuntu. Here are two alternative solutions:

1. Using Docker

Docker is a containerization platform that allows you to package applications and their dependencies into isolated containers. This approach simplifies deployment and ensures consistency across different environments.

Explanation:

Using Docker, you can create a containerized environment for your Laravel application, including PHP, Composer, and any other required dependencies. This eliminates the need to manually install these components on your Ubuntu system. Docker containers are lightweight and portable, making them ideal for development, testing, and production deployments.

Steps:

  1. Install Docker and Docker Compose: Follow the official Docker documentation to install Docker and Docker Compose on your Ubuntu system.

  2. Create a docker-compose.yml file: This file defines the services that make up your Laravel application, such as the web server (Nginx or Apache), PHP, and database.

Here’s an example docker-compose.yml file for a Laravel application using Nginx and MySQL:

version: "3.8"
services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
    image: laravel-app
    container_name: laravel-app
    volumes:
      - .:/var/www/html
    ports:
      - "8000:80"
    depends_on:
      - db
  db:
    image: mysql:8.0
    container_name: mysql-db
    environment:
      MYSQL_ROOT_PASSWORD: root_password
      MYSQL_DATABASE: laravel
    ports:
      - "3306:3306"

  phpmyadmin:
    image: phpmyadmin/phpmyadmin
    ports:
      - '8080:80'
    environment:
      PMA_HOST: mysql-db
      PMA_PORT: 3306
    depends_on:
      - db
  1. Create a Dockerfile file: This file contains the instructions for building the Docker image for your Laravel application.
FROM php:8.1-fpm-alpine

WORKDIR /var/www/html

RUN apk update && apk add --no-cache git zip unzip

RUN docker-php-ext-install pdo pdo_mysql mbstring zip bcmath gd

COPY --from=composer:latest /usr/bin/composer /usr/local/bin/composer

COPY . .

RUN composer install --no-interaction --optimize-autoloader

EXPOSE 9000

CMD ["php-fpm"]
  1. Create an Nginx Configuration File: This file configures the Nginx server.
server {
    listen 80;
    index index.php index.html;
    error_log  /var/log/nginx/error.log;
    access_log /var/log/nginx/access.log;
    root /var/www/html/public;

    location ~ .php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+.php)(/.+)$;
        fastcgi_pass app:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }

    location / {
        try_files $uri $uri/ /index.php?$query_string;
        gzip_static on;
    }
}
  1. Build and Run the Containers: Run the following command in the directory containing the docker-compose.yml file:

    $ docker-compose up -d --build

This command will build the Docker image and start the containers. Your Laravel application will be accessible at http://localhost:8000.

2. Using Laravel Valet (macOS only, but alternatives exist for Linux)

Laravel Valet is a minimalist development environment for macOS. It automatically configures your Mac to serve Laravel applications using Nginx. While Valet is specific to macOS, similar tools like Laravel Homestead or using a pre-configured virtual machine (like Vagrant) can achieve a similar streamlined experience on Linux.

Explanation (Adapting the Concept for Linux):

The idea behind Valet is to provide a zero-configuration setup. For Linux, we can achieve this using a combination of tools and scripts. Instead of Valet’s specific implementation, we’ll outline a strategy using Vagrant and a pre-configured virtual machine with Laravel Homestead.

Steps (for a Linux-friendly "Valet-like" experience):

  1. Install Vagrant and VirtualBox: Download and install Vagrant and VirtualBox on your Ubuntu system.

  2. Install Laravel Homestead: Laravel Homestead provides a pre-packaged Vagrant box with all the necessary tools for Laravel development.

    vagrant box add laravel/homestead
  3. Clone the Homestead repository:

    git clone https://github.com/laravel/homestead.git Homestead
    cd Homestead
  4. Initialize Homestead:

    bash init.sh
  5. Configure Homestead.yaml: This file configures the Homestead virtual machine. You’ll need to map your local project directory to a directory inside the VM, and configure a site to point to your Laravel application’s public directory. For example:

    ip: "192.168.10.10"
    memory: 2048
    cpus: 2
    provider: virtualbox
    
    authorize: ~/.ssh/id_rsa.pub
    
    keys:
        - ~/.ssh/id_rsa
    
    folders:
        - map: ~/Code/my-laravel-project  # Your local project directory
          to: /home/vagrant/code/my-laravel-project # Directory inside the VM
    
    sites:
        - map: my-laravel-project.test  # Desired domain name
          to: /home/vagrant/code/my-laravel-project/public # Laravel's public directory
    
    databases:
        - laravel
  6. Start the Virtual Machine:

    vagrant up
  7. Add the Domain to your hosts file: Add the following line to your /etc/hosts file (you’ll need sudo privileges):

    192.168.10.10 my-laravel-project.test
  8. Access your application: You can now access your Laravel application in your browser at http://my-laravel-project.test.

These alternative solutions offer different approaches to installing and running Laravel, catering to various needs and preferences. Docker provides a containerized environment for consistent deployments, while Homestead (and the concept adapted for Linux) aims for a simplified, zero-configuration development experience. Choose the method that best suits your workflow and project requirements.

Leave a Reply

Your email address will not be published. Required fields are marked *