Install and Configure Laravel on AlmaLinux 9 with Best Steps

Posted on

Install and Configure Laravel on AlmaLinux 9 with Best Steps

Install and Configure Laravel on AlmaLinux 9 with Best Steps

In this guide, we will demonstrate how to Install and Configure Laravel on AlmaLinux 9 using a LEMP stack. You will also learn how to secure the Laravel application on your AlmaLinux 9 server. Laravel is a popular, free, and open-source PHP web framework widely used for building web applications. Follow these steps to get familiar with Laravel and begin the installation process on your AlmaLinux 9 system.

Laravel PHP Web Framework Introduction

Laravel follows the MVC (Model-View-Controller) architectural pattern. Its primary goal is to accelerate and streamline the web development process by offering a comprehensive suite of tools and resources specifically designed for building web applications.

Laravel is renowned for its elegant and expressive syntax and its extensive toolkit. This toolkit encompasses features for routing, authentication, caching, and many other essential functionalities.

Many developers choose Laravel for its capacity to rapidly develop robust and scalable web applications. Laravel is fundamentally a backend web framework, meaning it is primarily used for developing the server-side logic of web applications.

Laravel, written in PHP, is used to build web applications that run on a web server. It is not typically used for developing the front-end or client-side of web applications, which is usually handled by JavaScript frameworks like Vue.js or React. Therefore, to truly Install and Configure Laravel on AlmaLinux 9 requires a solid understanding of the server-side.

To Install and Configure Laravel on AlmaLinux 9, some prerequisites must be met.

1. Requirements For Laravel Setup

First, you need to log in to your server as a root or non-root user with sudo privileges and set up a basic firewall. You can refer to our article on Initial Server Setup with AlmaLinux 9 for detailed instructions.

Next, you need to have the LEMP stack installed on your server. For this, you can consult the article How To Install LEMP Stack on AlmaLinux 9.

Finally, you’ll need a domain name that is pointed to your server’s IP address.

Once these requirements are fulfilled, proceed with the following steps to complete the Install and Configure Laravel on AlmaLinux 9 process.

2. Configure PHP For Laravel Framework

Begin by installing the necessary PHP extensions and packages using the following command:

dnf install php-common php-xml php-mbstring php-json php-zip curl unzip -y

Next, edit the PHP-FPM configuration file. Open the file using your preferred text editor; here, we use the vi editor:

vi /etc/php-fpm.d/www.conf

Locate the following lines and uncomment them by removing the ";" from the beginning of the line and modifying them to reflect Nginx:

listen.owner = nginx
listen.group = nginx

Save and close the file.

Then, edit the php.ini configuration file:

vi /etc/php.ini

Modify the following lines. Set your own time zone and uncomment them by removing the ";" from the beginning of the line:

date.timezone = America/New_York
cgi.fix_pathinfo=1

Save and close the file.

3. Install Composer For Laravel

In this guide, you will install Laravel using Composer. Therefore, you need to install Composer on AlmaLinux 9 with the command below:

curl -sS https://getcomposer.org/installer | php

Upon successful installation, you will see the following output:

**Output**
All settings correct for using Composer
Downloading...

Composer (version 2.5.4) successfully installed to: /root/composer.phar
Use it: php composer.phar

Now, move the Composer binary to the system path:

mv composer.phar /usr/local/bin/composer

Then, set the correct permissions for it:

chmod +x /usr/local/bin/composer

Verify your Composer installation by checking its version:

composer --version
**Output**
Composer version 2.5.4 2023-02-15 13:10:06

4. Install Laravel on AlmaLinux 9

Now, you can proceed to install Laravel on your server.

First, navigate to the Nginx web root directory:

cd /var/www/html/

Then, install Laravel using Composer:

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

After the installation completes, you will see the following output:

**Output**
   INFO  Application key set successfully.

Then, use the following commands to set the correct permissions and ownership to Laravel:

# chown -R nginx:nginx /var/www/html/laravel/
# chown -R nginx:nginx /var/www/html/laravel/storage/
# chown -R nginx:nginx /var/www/html/laravel/bootstrap/cache/
# chmod -R 0777 /var/www/html/laravel/storage/
# chmod -R 0775 /var/www/html/laravel/bootstrap/cache/

5. Create an Nginx VirtualHost for Laravel

Create an Nginx configuration file for Laravel; we’ll use vi:

vi /etc/nginx/conf.d/laravel.conf

Add the following content to the file, replacing the domain name with your own:

server {
       listen 80;
       server_name domain-name;
       root        /var/www/html/laravel/public;
       index       index.php;
       charset utf-8;
       gzip on;
    gzip_types text/css application/javascript text/javascript application/x-javascript  image/svg+xml text/plain text/xsd text/xsl text/xml image/x-icon;
        location / {
            try_files $uri $uri/ /index.php?$query_string;
        }

        location ~ .php {
                include fastcgi.conf;
                fastcgi_split_path_info ^(.+.php)(/.+)$;
                fastcgi_pass unix:/run/php-fpm/www.sock;
        }
        location ~ /.ht {
                deny all;
        }
}

Save and close the file.

Then, verify Laravel for any configuration error on AlmaLinux 9:

nginx -t
**Output**
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

To apply the changes, restart Nginx and PHP-FPM:

# systemctl restart php-fpm
# systemctl restart nginx

6. Configure Firewall For Laravel Framework

Allow ports 80 and 443 through the firewall:

# firewall-cmd --zone=public --permanent --add-service=http
# firewall-cmd --zone=public --permanent --add-service=https

Reload the firewall to apply the new rules:

firewall-cmd --reload

7. Access Laravel Framework Web Interface

Access your Laravel application through the web interface by typing your domain name or server’s IP address:

http://domain-name

You should see the default Laravel welcome page.

8. Secure Laravel Application with Let’s Encrypt

It’s recommended to enable SSL on the Laravel website to secure the connection. Let’s Encrypt provides a free SSL to obtain, renew, and manage SSL/TLS certificates for your domain.

First, install the Certbot client on AlmaLinux 9 with the following commands:

# dnf install epel-release -y
# dnf install certbot python3-certbot-nginx -y

Then, run the following command to download Let’s Encrypt SSL for your Laravel domain:

certbot --nginx -d domain-name

You will be asked to provide your valid email and accept the terms of service.

When the certificate has been installed, you should see the following output.

At this point, your Laravel website is secured with Let’s Encrypt SSL on AlmaLinux 9.

You can now access it securely using the URL below:

https://domain-name

Set up Auto-renewal for Laravel SSL certificates

Let’s Encrypt certificates are valid for 90 days, but it’s recommended that you renew the certificates every 60 days.

You can test automatic renewal for your certificates with the following command:

sudo certbot renew --dry-run

Your output should be similar to this:

It is safe to create a cron job that runs every week or even every day.

To edit the crontab for the root user, run the following command:

sudo crontab -e

Then, add the following line to the empty file:

0 0,12 * * * python -c 'import random; import time; time.sleep(random.random() * 3600)' && certbot renew --quiet

Save and close the file with the :wq.

Conclusion

You have now successfully learned how to Install and Configure Laravel on AlmaLinux 9. You have also learned how to secure Laravel using Let’s Encrypt on AlmaLinux 9.

Alternative Solutions for Installing Laravel on AlmaLinux 9

While the LEMP stack and Composer installation method outlined above is a common and reliable approach, other methods can be employed to Install and Configure Laravel on AlmaLinux 9. Here are two alternatives:

1. Using Docker and Docker Compose:

Docker allows you to containerize your Laravel application and its dependencies, making it highly portable and reproducible across different environments. Docker Compose simplifies the management of multi-container Docker applications.

  • Explanation: This approach encapsulates the entire Laravel application, including the web server (Nginx or Apache), PHP interpreter, and any other dependencies, into a single container. Docker Compose orchestrates the different containers needed for the application (e.g., web server, database). This eliminates environment inconsistencies and simplifies deployment.

  • Steps:

    1. Install Docker and Docker Compose on your AlmaLinux 9 server.
    2. Create a Dockerfile for your Laravel application. This file defines the steps needed to build the Docker image.
    FROM php:8.1-fpm-alpine
    
    # Copy composer.lock and composer.json
    COPY composer.lock composer.json /var/www/
    
    # Set working directory
    WORKDIR /var/www
    
    # Install dependencies
    RUN apk add --no-cache --virtual .build-deps 
        $PHPIZE_DEPS 
        zip 
        unzip 
        git
    
    RUN docker-php-ext-install pdo_mysql mbstring zip exif pcntl
    RUN composer install --optimize-autoloader --no-dev
    
    # Copy existing application source code
    COPY . /var/www
    
    # Change current user to www-data
    USER www-data
    
    EXPOSE 9000
    CMD ["php-fpm"]
    1. Create a docker-compose.yml file to define the services (containers) needed for your application.
    version: "3.7"
    services:
      app:
        build:
          context: ./
          dockerfile: Dockerfile
        image: laravel-app
        container_name: laravel-app
        restart: unless-stopped
        working_dir: /var/www/
        volumes:
          - ./:/var/www
        networks:
          - laravel
      web:
        image: nginx:alpine
        container_name: webserver
        restart: unless-stopped
        ports:
          - 80:80
          - 443:443
        volumes:
          - ./:/var/www
          - ./docker/nginx:/etc/nginx/conf.d/
        networks:
          - laravel
        depends_on:
          - app
    networks:
      laravel:
        driver: bridge
    1. Create an Nginx configuration file (e.g., docker/nginx/default.conf) within your project directory to configure the Nginx server to serve the Laravel application.
    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/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;
        }
    }
    1. Run docker-compose up -d to build and start the containers.

2. Using a Pre-built Virtual Machine Image:

Several providers offer pre-built virtual machine images with Laravel and its dependencies already installed. This can significantly speed up the setup process.

  • Explanation: Instead of manually installing and configuring each component of the LEMP stack and Laravel, you can download a pre-configured VM image that contains everything you need. This is a quick and easy way to get started, especially for development or testing purposes.

  • Examples:

    • Laravel Homestead: Laravel’s official development environment, provided as a Vagrant box.
    • Bitnami Laravel Stack: Bitnami offers pre-packaged stacks for various applications, including Laravel, that can be deployed on different platforms, including VMs.
  • Steps:

    1. Install a virtualization software like VirtualBox or VMware.
    2. Download a pre-built Laravel VM image (e.g., Laravel Homestead box).
    3. Import the VM image into your virtualization software.
    4. Configure the VM network settings and shared folders.
    5. Start the VM.

These alternative approaches provide different trade-offs in terms of complexity, control, and setup time. The best choice depends on your specific needs and preferences. Using Docker offers more portability and consistency, while a pre-built VM provides the fastest way to get a working Laravel environment. No matter the approach, it’s important to follow the steps carefully to Install and Configure Laravel on AlmaLinux 9 successfully.

Leave a Reply

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