How to Deploy a Laravel App on a VPS (From Zero to Production)
How to deploy our Laravel app on a server?
Alright, first things first, you need to connect to your server using SSH. How can you do that?
Well, I explained it in this article. Check it out.
After you connect to your server, it's time to create a user for that server (it's better to work with a user than the root user), so we use this command:
sudo adduser <username>fill the <username> with any name that you want!
This command will ask you about your password, and it wants you to confirm it, and other questions that you can skip by pressing enter.
But you need to add the user to sudoers group so that the user can perform sudo commands, unless you won't be able to perform sudo commands at all, so you need to run this command as the root user:
usermod -a -G sudo <username>Yeah! Now the user can perform sudo commands. So let's switch to the user:
su - <username>Well, for our app, we need a web server. We are going to use Nginx! If you don't know what that is and how to configure that, you'd better check this article, cause I already explained it in detail.
But before installing packages, we need to update the list of available packages. So it's better to run:
sudo apt updateThen we can:
sudo apt install nginxThen we need to start our Nignx:
sudo systemctl start nginxIt's better to enable Nginx, so that every time the server gets booted, it will start automatically:
sudo systemctl enable nginxAfter that, we need to install all the dependencies of our project:
Based on Laravel documentation in this link. we need these:
PHP >= 8.2
Ctype PHP Extension
cURL PHP Extension
DOM PHP Extension
Fileinfo PHP Extension
Filter PHP Extension
Hash PHP Extension
Mbstring PHP Extension
OpenSSL PHP Extension
PCRE PHP Extension
PDO PHP Extension
Session PHP Extension
Tokenizer PHP Extension
XML PHP Extension
We have to install them all, and we have to install the latest version of these, but most default repos that Linux package managers use do not include the latest version of PHP, so we need to add a proper repo to fetch the latest versions of the technologies above:
sudo apt install software-properties-commonIf you wanna know what this command do, you better check here. But in simple way it allow us to add our own repo properly.
Then we are going to add ppa:ondrej/php repo:
sudo add-apt-repository ppa:ondrej/phpAgain, we need to update our repos list so that our server can identify the new packages inside the new repo:
sudo apt update Now let's install the dependencies that Laravel mentioned:
sudo apt install php8.4 php8.4-cli php8.4-fpm php8.4-mysql php8.4-xml php8.4-curl php8.4-mbstring php8.4-zip php8.4-gd php8.4-bcmath php8.4-opcacheWe also added two extensions php8.4-bcmath and php8.4-opcache that lets PHP calculate with high accuracy and level up the PHP performance accordingly.
enable the php-fpm (the FastCGI Process Manager for PHP that handles PHP requests for the web server), so that every time the server gets rebooted, it will start automatically:
sudo systemctl enable php8.4-fpmGood, Now we need to install Node and Composer:
So we need to go to this website to install Node: https://nodejs.org/en/download
Don't forget to choose the right OS.
and this website to install Composer: https://getcomposer.org/download/
Don't forget to use this command after installing Composer, as the doc mentioned:
sudo mv composer.phar /usr/local/bin/composerOf course, we need a database for our app Let's assume that you use MySQL, so let's install it:
If you use MySQL, I highly recommend you to install MariaDB, that a wrapper around MySQL; its performance is better than MySQL, but you don't need to configure anything else. You just install MariaDB, and in your Laravel app, you define the database connection as MySQL, so:
sudo apt update
sudo apt install mariadb-serverOk! Now you need to configure your MariaDB. For that:
sudo mysql_secure_installationThis command may ask you for your root password for the database. If so, the root password is empty, so you just need to hit enter (but it may also ask for your server root password before even getting into the configuration part, cause you are using the sudo command. Don't complicate these two). After that, it will try to ask you if you wanna set a password for your database (sure you want to type Yand move on ), and it will ask you to confirm your password. After that, it might ask you different questions like "Remove anonymous user?" or "disallow root login remotely?" and something like this. I recommend hitting y on every question unless you want otherwise.
so, start and enable MariaDB:
sudo systemctl start mariadb
sudo systemctl enable mariadbYou can check the status of these by using:
sudo systemctl status <service>You can access your database by:
sudo mariadbAfter connecting to your database, try creating a DB for your app:
CREATE DATABASE <Database_name>;After creating the DB, type exit; and then press Enter to get out of there.
Greate! Now we need to clone our project to our server. I recommend you to use GitHub.
Push your code to GitHub on your local and then set up SSH connection to GitHub in your server (you can use first this link and then this one to set up that SSH key), just like when you create SSH keys to connect to this server, here(on this server), you also need to create SSH and provide the public key to Github and after that you clone your code using SSH.
We need a proper place to clone our code into. It's recommended to clone our code in /srv directory so let's create a directory inside that and then changes its owner ship so we won't face any problem in cloning or other suff:
sudo mkdir -p /srv/<arbitary_name_for_your_dir>
sudo chown $USER:$USER /srv/<arbitary_name_for_your_dir>
cd /srv/<arbitary_name_for_your_dir>Start cloning:
git clone git@github.com:path/to/your/repoAs the documentation of Laravel says, Laravel needs to write some files in specific directories, and of course, it uses www-data user to do so (Nginx sends the request to php-fpm, and php-fpm tries to write some files using www-data user, and it's already defined in its configurations). So let's grant those permissions for our app, as the doc said it needs permissions for /storage and bootstrap/cache directories so:
sudo chown -R $USER:www-data /srv/<arbitary_name_for_your_dir>/storage /srv/<arbitary_name_for_your_dir>/bootstrap/cacheWe just changed those directories and their file group to www-data (recursively using -R).
Let's configure our Nginx based on the documentation, and we're ready to go:
Creating our Nginx config file: (If you have no idea why we are creating this file you would better check this link)
sudo nano /etc/nginx/sites-available/<arbitary_name_for_your_nginx_config_app> Then paste these (that are based on the documentation of Laravel):
server {
listen 80;
listen [::]:80;
server_name example.com;
root /srv/<arbitary_name_for_your_dir>/public;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
index index.php;
charset utf-8;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt { access_log off; log_not_found off; }
error_page 404 /index.php;
location ~ ^/index\.php(/|$) {
fastcgi_pass unix:/var/run/php/php8.4-fpm.sock;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
include fastcgi_params;
fastcgi_hide_header X-Powered-By;
}
location ~ /\.(?!well-known).* {
deny all;
}
}Don't forget to change the
<arbitary_name_for_your_dir>to your project directory name and theserver_namevalue must be your domain or server IP address
After pasting it, save the file and get out of that nano( CTRL+X and press Y and then press Enter).
Run this command to delete the default config that we don't need:
sudo rm -rf /etc/nginx/sites-enabled/defaultAnd then this: (again, if you didn't understand why we created a symlink, it's better to check this out)
sudo ln -s /etc/nginx/sites-available/<arbitary_name_for_your_nginx_config_app> /etc/nginx/sites-enabled/ Now, cause we changed our Nginx config, we need to restart it using:
sudo systemctl restart nginxThen make sure you are in the directory of the project on server and only then run:
mv .env.example .envYou need to configure your .env file so you can use nano or vim:
nano .envChange those keys based on your needs.
Then:
composer install --optimize-autoloader --no-devAfter that:
php artisan key:generatenpm inpm run buildIf you faced any permission issues in your app, run this command again, cause sometimes php artisan command can change some ownerships:
sudo chown -R $USER:www-data /srv/blog/storage /srv/blog/bootstrap/cache