search
HomeBackend DevelopmentPHP TutorialSetting Up Laravel on Your Own Server: A DIY Guide

Setting Up Laravel on Your Own Server: A DIY Guide

Originally published on bcd.dev

Before you go through the pain and challenge of configuring your own server you should perhaps consider Laravel forge. I trust they would know better how to deploy a laravel app.

For curious minded people, this is part of a bigger series Do it yourself series

Components

  • webserver
    • nginx
  • database
    • mysql
  • php
  • composer
  • node
  • npm / yarn
  • scheduler
  • firewall
  • log
    • papertrail
  • search
    • elastic search
    • algolia
  • other third party services
    • redis

Basic build

recepee on an ubuntu server (22-10)

  • mysql
  • php
  • composer
  • node
  • nginx
  • queue

Requirements

  • VPS Server
  • Valid DNS record pointing to your server

Mysql

sudo apt-get install -y mysql-server

# Init project by creating a user with a dedicated database
name=$1
username=${2:-$name}
password=${3:-$name}
root_username=${4:-'root'}
root_password=${5:-''}
echo '' > tmp.sql
echo "CREATE USER $name@localhost identified by \"$password\";" >> tmp.sql
echo "CREATE DATABASE $name charset utf8 collate utf8_general_ci;" >> tmp.sql
echo "GRANT ALL PRIVILEGES ON $name.* to $name@localhost;" >> tmp.sql
mysql -u$root_username -p$root_password -e "source tmp.sql"


mysql -u$root_username -p$root_password -e "CREATE DATABASE $name charset utf8 collate utf8_general_ci;"

Php

sudo apt install -y software-properties-common
sudo add-apt-repository ppa:ondrej/php
sudo apt update

# php with some extensions
PHP_VERSION=${1:-'8.2'}
sudo apt-get install -y "php$PHP_VERSION" php$PHP_VERSION-{common,cli,fpm,zip,xml,pdo,mysql,mbstring,tokenizer,ctype,curl,common,curl,gd,intl,sqlite3,xmlrpc,xsl,soap,opcache,readline,xdebug,bcmath}

Composer

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"

# For simplicity purpose, we are skipping the hash check. That is a crucial step you wouldn't want to skip when downloading stuff on the internet
# Hash below matches composer version 2.1.3
# php -r "if (hash_file('sha384', 'composer-setup.php') === '756890a4488ce9024fc62c56153228907f1545c228516cbf63f885e036d37e9a59d27d63f46af1d4d07ee0f76181c7d3') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php
php -r "unlink('composer-setup.php');"
sudo mv composer.phar /usr/local/bin/composer

Node

You can get node on their website but I prefer getting specific version from node version manager (nvm)

version=${1:-'20'}
echo "Installing nvm + node $version"
wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/install.sh | bash
source ~/.bashrc
nvm install $version
# Optional but I like yarn so here we go
nvm exec $version npm i yarn -g

Nginx

# Making sure apache is not installed to avoid conflict on port 80
sudo apt-get remove -y apache
sudo apt-get install -y nginx
rm /etc/nginx/sites-available/default  /etc/nginx/sites-enabled/default 

name=$1 # site.domain
webroot=${3:-"/var/www/vhosts/$name"}
mkdir -p $webroot
touch "/etc/nginx/sites-available/$name.conf"
ln -s "/etc/nginx/sites-available/$name.conf" "/etc/nginx/sites-enabled/$name.conf"
cat >> "/etc/nginx/sites-available/$name.conf" 



<h4>
  
  
  Secure traffic using HTTPS
</h4>

<p>At this point we are running a web server on port 80. However everyone can see the content flowing through the networking. Welcome https.<br>
</p>

<pre class="brush:php;toolbar:false">domain=$1
email=${2:-"your@email.com"}
sudo apt-get install -y python3-certbot-nginx


# manual
# certbot certonly -a manual --rsa-key-size 4096 --email $email -d $domain -d www.$domain

# auto
## With base nginx config
certbot certonly --nginx --rsa-key-size 4096 --email $email -d $domain -d www.$domain

When the steps above succeed you can carry on with nginx config for ssl. The following will redirect all non secure connection (80) to secure connection (443)

# Usage ./laravel.sh site.domain 8.2 ~/sites
## Dependencies: letsencrypt, php$php_version, php$php_version-fpm

# sudo apt-get install -y php$php_version php$php_version-fpm
name=$1 # site.domain
user=$2
php_version=${3:-'8.2'}
root=${4:-"/var/www/vhosts/$name"}
webroot=${5:-"/var/www/vhosts/$name/public"}
touch /etc/nginx/sites-available/$name.conf
ln -s /etc/nginx/sites-available/$name.conf /etc/nginx/sites-enabled/$name.conf

mkdir -p /var/www/vhosts/$name/storage/logs
touch /var/www/vhosts/$name/storage/logs/error.log
touch /var/www/vhosts/$name/storage/logs/access.log

cat >> /etc/nginx/sites-available/$name.conf > /etc/php/$php_version/cli/php.ini 



<h5>
  
  
  Auto renew certificate
</h5>



<pre class="brush:php;toolbar:false"># DISCLAIMER: it is safer to edit cron file using crontab dedicated command
# That being see given this is a script we likely want to have automated
/var/spool/cron/crontabs

## cron job to auto renew every 3 months for you
crontab -e
# 0 0 1 */3 * /usr/bin/certbot renew --quiet

## I saw people doing it monthly
# 0 0 1 * *

Queue

#! /bin/bash
user=${0:-$(USER)}
root_dir="/home/$user/www/"
processes=4
sudo apt get install -y supervisor
cat >> /etc/supervisor/conf.d/laravel-worker.conf 



<h2>
  
  
  Conclusion
</h2>

<p>No conclusion as this is a starting point only but gets you an operational laravel app.<br>
Made a lot of arbitrary choices. Adapt for your usecase.<br>
Next up</p>

  • automate script using orchestration (ie ansible)
  • deploy using aws code deploy
  • CI / CD pipeline from github
  • tighting security with firewall policies
  • monitoring
  • load management / balancing

Originally published on bcd.dev

The above is the detailed content of Setting Up Laravel on Your Own Server: A DIY Guide. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

What is the importance of setting the httponly flag for session cookies?What is the importance of setting the httponly flag for session cookies?May 03, 2025 am 12:10 AM

Setting the httponly flag is crucial for session cookies because it can effectively prevent XSS attacks and protect user session information. Specifically, 1) the httponly flag prevents JavaScript from accessing cookies, 2) the flag can be set through setcookies and make_response in PHP and Flask, 3) Although it cannot be prevented from all attacks, it should be part of the overall security policy.

What problem do PHP sessions solve in web development?What problem do PHP sessions solve in web development?May 03, 2025 am 12:02 AM

PHPsessionssolvetheproblemofmaintainingstateacrossmultipleHTTPrequestsbystoringdataontheserverandassociatingitwithauniquesessionID.1)Theystoredataserver-side,typicallyinfilesordatabases,anduseasessionIDstoredinacookietoretrievedata.2)Sessionsenhances

What data can be stored in a PHP session?What data can be stored in a PHP session?May 02, 2025 am 12:17 AM

PHPsessionscanstorestrings,numbers,arrays,andobjects.1.Strings:textdatalikeusernames.2.Numbers:integersorfloatsforcounters.3.Arrays:listslikeshoppingcarts.4.Objects:complexstructuresthatareserialized.

How do you start a PHP session?How do you start a PHP session?May 02, 2025 am 12:16 AM

TostartaPHPsession,usesession_start()atthescript'sbeginning.1)Placeitbeforeanyoutputtosetthesessioncookie.2)Usesessionsforuserdatalikeloginstatusorshoppingcarts.3)RegeneratesessionIDstopreventfixationattacks.4)Considerusingadatabaseforsessionstoragei

What is session regeneration, and how does it improve security?What is session regeneration, and how does it improve security?May 02, 2025 am 12:15 AM

Session regeneration refers to generating a new session ID and invalidating the old ID when the user performs sensitive operations in case of session fixed attacks. The implementation steps include: 1. Detect sensitive operations, 2. Generate new session ID, 3. Destroy old session ID, 4. Update user-side session information.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools