Deploy Laravel application on Openlitespeed DigitalOcean droplet

Deploy Laravel application on  Openlitespeed  DigitalOcean droplet

Why Openlitespeed & DigitalOcean

Let's dive into the exhilarating world of hosting your apps on DigitalOcean, and why pairing it with OpenLiteSpeed turns your project into a speed demon!

DigitalOcean isn't just a hosting platform; it's a treasure trove of resources that make the tech journey smoother and way more enjoyable.

Imagine a web server that's not just open source like nginx or apache but also turbocharges your app's performance. That's OpenLiteSpeed for you – it's built for speed, making your apps zip through the internet with ease.

Getting OpenLiteSpeed up and running on DigitalOcean for my Laravel app was a bit of a puzzle since there's no direct one-click install for it. But, after some tinkering, I found the perfect setup steps. I'm here to break it down for you, so you can skip the headache and jump straight to the fun part!

1. Setting Up on DigitalOcean

First off, if you're new to DigitalOcean, do yourself a favor and sign up with my referral link. You'll get a sweet $200 to kickstart your projects, and I get a little something too. It's a win-win!

After making sure your account is setup go to https://cloud.digitalocean.com/droplets/new to create your droplet or click the green create button at the top right.

I will choose the following setting but you're completely free to change them if you want you can check this guide form DO on droplet creation

Droplet image: Ubuntu 20.04 (LTS) x64

Pricing Plan: 5$/mo (suitable if you don't have heavy traffic & can easily be increased latter on)

Datacenter region: Frankfurt (Choose the closest place to your users) and we don't need to add block storage of VPC

I have my ssh key on DigitalOcean and will be using it for the rest of the article.

If you need create one check this guide

Then hit Create Droplet button and wait until it's created, then copy the droplet ip

2. Securing Your Droplet: Initial Server Setup

This step isn't required but it's recommended to keep your droplet safe.

From your terminal, SSH into your droplet to get started

ssh root@<droplet_ip>

Let's make sure everything is up to date

sudo apt-get update && sudo apt-get upgrade -y

Create new user. replace with you username of choice, you will be asked to choose a password and fill in some data

adduser <username>

Add your new user to the sudo group

usermod -aG sudo <username>

Enable UFW firewall

IMPORTANT: For this to work you should have logged in using SSH like we did

ufw allow OpenSSH && ufw enable
# Type 'y' when you get this message
# Command may disrupt existing ssh connections. Proceed with operation (y|n)?

Check if the firewall is enabled & SSH access is available

ufw status

The output should look like this

Status: active

To                         Action      From
--                         ------      ----
OpenSSH                    ALLOW       Anywhere
OpenSSH (v6)               ALLOW       Anywhere (v6)

Now we need to copy the ssh authorized_keys to our new user

rsync --archive --chown=<username>:<username> ~/.ssh /home/<username>

To test the changes open a new terminal session and try to connect using the new username

ssh <username>@<droplet_ip>

Test your sudo access

sudo apt-get update

3. Install OpenliteSpeed server

Now we are ready to start installing the needed software and will start by installing OpenLiteSpeed, run the following commands:

wget -qO - https://rpms.litespeedtech.com/debian/lst_repo.gpg | sudo apt-key add -
sudo add-apt-repository 'deb http://rpms.litespeedtech.com/debian/ focal main'

# Note: 'focal' is the name of Ubuntu 20.04, you will need use 'bionic' if you go with Ubuntu 18.04
sudo apt install openlitespeed lsphp74 -y
sudo ln -sf /usr/local/lsws/lsphp74/bin/lsphp /usr/local/lsws/fcgi-bin/lsphp5

Now we successfully installed OpenliteSpeed server, let's configure it's the admin panel to be able to log in as admin and change the configuration.

Run the following script and follow the instructions to crate username and password. will need them later.

sudo /usr/local/lsws/admin/misc/admpass.sh

# At the end you should get message like this:
# Administrator's username/password is updated successfully!

Make sure the server is running

sudo /usr/local/lsws/bin/lswsctrl status

# The output should be something like:
# litespeed is running with PID 33075.

If the server isn't running start it using this command

sudo /usr/local/lsws/bin/lswsctrl start

By default OpenLiteSpeed uses the port 8080, we will need to change that but first will need to open the access to this port via ufw firewall. Will also open port 7080 for the admin panel.

sudo ufw allow 8088 && sudo ufw allow 7080

If you go now to :8088 you should see the default landing page of OpenLiteSpeed

Also if you have a domain name, now would be a good time to add the droplet IP as an A record for the domain from the domain provider website. Check this guide for Godaddy domains.

Now we need to run this page on port 80 which is the default http port. So that our users won't have to add :8088 to view the website.

Will do this by going to the :7080, if the browser gave you warning about the SSL just ignore it and proceed.

You should see this page. Enter the admin username & password that you choose earlier.

If you lost them you can run sudo /usr/local/lsws/admin/misc/admpass.sh to change them anytime

When you login successfully you will see something like that

To change the default port from 8088 to 80. Go to the Listeners tab from the left bar and click on the view action under the only listener in the table.

Click edit to edit the listener details

Change the port to 80 and click that weird desk to save

Click the green refresh button to restart the server

Now allow the port 80 from the firewall

sudo ufw allow 80

You should be able to access the default server page now from directly or via your domain.

4. Configure PHP version to use 7.4

Inside the admin panel go to the Server configuration page, choose the External App tab and click the Edit action on the only app available

Scroll until you find the Command input

Change the command from lsphp73/bin/lsphp to lsphp74/bin/lsphp to tell OpenLiteSpeed to use php7.4.

Now save and restart the server the same way we did before

5. Install PHP composer

First will install PHP4.7 cli

sudo apt install php7.4-cli -y

Navigate to the home directory and download composer

cd ~
sudo curl -sS https://getcomposer.org/installer -o composer-setup.php

Next will need to verify the installer, will fetch the signature using CURL and store it in a HASH variable

HASH=`curl -sS https://composer.github.io/installer.sig`

Next execute the verify script

php -r "if (hash_file('SHA384', 'composer-setup.php') === '$HASH') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"

The output should be

Installer verified

Now will install composer globally

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

Now if you run composer in the terminal, you should see:

  	______
  / ____/___  ____ ___  ____  ____  ________  _____
 / /   / __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___/
/ /___/ /_/ / / / / / / /_/ / /_/ (__  )  __/ /
\____/\____/_/ /_/ /_/ .___/\____/____/\___/_/
                    /_/
Composer version 1.10.9 2020-07-16 12:57:00

Usage:
  command [options] [arguments]

Options:
  -h, --help                     Display this help message
  -q, --quiet                    Do not output any message
  -V, --version                  Display this application version
      --ansi                     Force ANSI output
      --no-ansi                  Disable ANSI output
  -n, --no-interaction           Do not ask any interactive question
      --profile                  Display timing and memory usage information
      --no-plugins               Whether to disable plugins.
  -d, --working-dir=WORKING-DIR  If specified, use the given directory as working directory.
      --no-cache                 Prevent use of the cache
  -v|vv|vvv, --verbose           Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

...

Congratulations! you are about half the way there 😆

6. Install MySQL server

Will need a database server for laravel to operate, you can choose whatever you like, I'll go with MySQL.

Run the following command to install the server:

sudo apt update && sudo apt install mysql-server -y

To configure the MySQL we need to run this script which will ask you some questions. you can choose your options but make sure you to enter a good password for the root user, maybe through some password generator and save the password in a safe place.

You can press Y and then ENTER to accept the default options after that.

sudo mysql_secure_installation

Now MySQL shell will be available using mysql -u root -p command which will ask for the password we created.

Now let's create a database for our laravel app, run this command and enter the root password you created.

sudo mysql -u root -p

If successful you should see something like:

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 14
Server version: 8.0.20-0ubuntu0.20.04.1 (Ubuntu)

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

Inside MySQL shell, let's create our database using the following command and replacing with you DB name of choice

CREATE DATABASE <database_name>;

# The result should be like:
# Query OK, 1 row affected (0.00 sec)

Now we need to create a new mysql user and give it access to the created db

CREATE USER '<new_db_user>'@'localhost' IDENTIFIED BY '<new_db_user_password>';

GRANT ALL PRIVILEGES ON <database_name>.* TO '<new_db_user>'@'localhost';

That's it for the sql shell, you can now exit using:

exit;

Hooray! we can finally start pulling our app from git to deploy. I will assume you are using GitHub but the process is very similar on GitLab or BitBucket.

This method is used to pull your private repo securely from GitHub to the droplet, if your repo is public you won't need this and you can move on to the next step.

Create a new SSH key for this server, run the following command and click ENTER to apply the defalts

cd ~ 
ssh-keygen -t rsa -b 2048 -C "email@example.com" # Replace by your email

Now we need to copy the public key and add it to GitHub, to print the public key into our terminal run:

cat ~/.ssh/id_rsa.pub

Take the public key starting from ssh-rsa until the end of the email

Now Open your repo on GitHub and head over to the settings tab, then choose "Deploy keys" and click "add key". you should have a page like this add your key, give it any name and save.

Now you can use ssh to pull your private repo code from the droplet.

8. Clone and configure our laravel app

Navigate to the directory that holds OpenLiteSpeed app

cd /usr/local/lsws/Example/

# List the directories
ls

When you ls you will see a directory called html that holds the test site created by OpenLiteSpeed, we will rename this directory to html.old and clone our website in html

Move the html to html.old

sudo mv html html.old
sudo mkdir html

Before cloning we need to give our current user the ownership of html/ directory to be able to use git and edit files without sudo:

sudo chown -R <your_username> html

Now you can pull inside html

# Clone your repo in html directory
git clone git@github.com:<username>/<repo>.git html

cd html

We have our laravel app now, let's start by make a copy of the env file edit using nano

cp .env.example .env && nano .env

Inside .env you will need to edit some values

  1. set APP_DEBUG=false
  2. set APP_URL=http:// or your domain if ready
  3. set DB_DATABASE= the one we created in mysql
  4. set DB_USERNAME= the mysql user we created for the db
  5. set DB_PASSWORD= the one we created while installing mysql

Install the required packages using composer

# Install some PHP extensions required by laravel
sudo apt-get install php-mbstring php-xml php-curl zip unzip php-zip php-mysql -y

# Then
composer install

When compose finishes it's magic, let's set the correct permissions for the laravel app

sudo find . -type f -exec chmod 664 {} \; && sudo find . -type d -exec chmod 775 {} \;

chown <your_username>:www-data .

sudo chgrp -R nogroup storage bootstrap/cache

sudo chmod -R ug+rwx storage bootstrap/cache

generate an app key for laravel and migrate the database tables

php artisan key:generate
php artisan migrate

Now our laravel app is ready, we need to test it, let's open the port 800

sudo ufw allow 8000

Run laravel app on the main host

php artisan ser --host=0.0.0.0

Now you should be able to see your app running on http://:8000 or http://:8000 , after you check if everything okay let's move the app to be running directly on the host or domain without the 8000 port

If you get PDOException error, make sure that ;extension=pdo_mysql line is uncommented in your php.ini

# Lookup the user php.ini file path
php -i | grep "Configuration File"

# Open the file with nano
sudo nano /etc/php/7.4/cli/php.ini

Ctrl + w to search for 'pdo_mysql' and remove the semicolon so ;extension=pdo_mysql becomes extension=pdo_mysql

Then restart the

sudo service mysql restart

9. Run Laravel app on port 80

Open the server admin panel at http://:7080 and goto the Virtual Hosts page and click view on the only virtual host there

Open the General tab and click edit on general table

Now replace $VH_ROOT/html/ with $VH_ROOT/html/public/ then save and restart the server

After this step your app should be working fine on the main host ip or the domain.

Conclusion

Combining DigitalOcean and OpenLiteSpeed offers a powerful, efficient hosting solution for Laravel apps. This guide simplifies the setup into straightforward steps, ensuring your application runs securely and swiftly. The journey of web development is full of learning and experimentation. With DigitalOcean's reliability and OpenLiteSpeed's performance, you're set for success. Keep exploring, stay curious, and enjoy the process of building engaging, fast applications. Here's to smooth deployments and exciting coding adventures!

Share this page:

Excited about the possibility of collaborating? Let's hop on a call and dive into the details together!

Hire Me