how to deploy laravel to vps using centos 9

  • October 6, 2023
  • 363

Hướng dẫn deploy dự án laravel lên vps sử dụng centos 9. Trong bài viết này chúng ta sẽ liệt kê các bước để deploy dự án laravel lên môi trường centos 9.

1. Ssh vào server

Đầu tiên cần ssh vào server để cài đặt, tham khảo bài viết cấu hình ssh config

2. Kiểm tra thông tin server

Kiểm tra thông tin server


cat /etc/os-release

# Ouput
NAME="CentOS Stream"
VERSION="9"

3. Install git

Cài đặt git để clone code về server


// Update your system
sudo dnf update

// Install git
sudo dnf install git

// Check version
git --version
git version 2.39.3

4. Add ssh key to git

Thêm ssh key của server vào tài khoản github


// Generate ssh key
cd ~/.ssh
ssh-keygen -t rsa -b 4096 -C "nguyenhuu140490@gmail.com"
chmod -R 600 id_rsa.pub

// ssh-agent in the background
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_rsa

Thêm ssh public key vào tài khoản github


cat ~/.ssh/id_rsa.pub

// Check server connect with git
ssh -T git@github.com

// Ouput success
Hi nguyenhuu1404! You've successfully authenticated, but GitHub does not provide shell access.

clone code từ github về server


// Add user to root group
sudo usermod -aG root [your_user]
// Create workspace
sudo mkdir /var/www/html

// Change owner for workspace
sudo chown -R [your_user]:[your_user] html

// VD user access server là centos
sudo chown -R centos:centos html

// Clone code
cd /var/www/html
git clone [repo_url]

5. Install nginx

Cài nginx web server


sudo dnf update

// Install nginx
sudo dnf install nginx

// Check version
nginx --version
nginx version: nginx/1.20.1

// Start nginx service
sudo systemctl start nginx
sudo systemctl enable nginx

// Check nginx status
sudo systemctl status nginx

// Mở post tường lửa để sử dụng nginx
sudo firewall-cmd --permanent --zone=public --add-service=http 
sudo firewall-cmd --permanent --zone=public --add-service=https
sudo firewall-cmd --reload

6. Install php 8.2

Cài đặt php 8.2 do chúng ta sử dụng laravel 10


// Install the EPEL repository
dnf install https://dl.fedoraproject.org/pub/epel/epel-release-latest-9.noarch.rpm

// Install the Remi repository
dnf install https://rpms.remirepo.net/enterprise/remi-release-9.rpm

// List php version
dnf module list php

// Install PHP 8.2 via the remi repository
dnf module install php:remi-8.2

// Check php version
php -v
// Output
PHP 8.2.0 (cli) (built: Dec  6 2022 14:26:47) (NTS gcc x86_64)
Copyright (c) The PHP Group
Zend Engine v4.2.0, Copyright (c) Zend Technologies

Cài đặt các extension cho php 8.2


// Cài đặt các extension cho php nếu sử dụng mysql
dnf install php-fpm php php-bcmath php-cli php-common php-gd php-imap php-mbstring php-mcrypt php-mysql php-mysqlnd php-pdo php-soap php-tidy php-xml php-xmlrpc php-opcache php-redis php-pecl-mcrypt php-brotli

// Cài đặt các extension cho php nếu sử dụng postgreSql
sudo dnf install php-fpm php php-bcmath php-cli php-common php-gd php-imap php-mbstring php-mcrypt php-pgsql php-soap php-tidy php-xml php-xmlrpc php-opcache php-redis php-pecl-mcrypt php-brotli

7. Config php-fpm và nginx

Start php-fpm


// Start php-fpm
systemctl enable php-fpm
systemctl start php-fpm

// Stop php fpm
systemctl stop php-fpm

// Restart php fpm
systemctl restart php-fpm

// Status php fpm
systemctl status php-fpm

// Back up config php fpm
sudo cp /etc/php-fpm.d/www.conf /etc/php-fpm.d/www.conf.bak

Thay đổi config cho php fpm


sudo vim /etc/php-fpm.d/www.conf
# Make the following modifications.
# Sửa user group mặc định sang user mà bạn đănng nhập vps
# VD user của mình là centos
user =centos
group = centos
listen = 127.0.0.1:9000
listen = /var/run/php-fpm.sock
listen.owner = centos
listen.group = centos
listen.mode = 0660

// Restart php fpm
systemctl restart php-fpm

Thêm file config nginx php-fpm


vi /etc/nginx/conf.d/default.conf
server {
    listen 80;
    root /var/www/html/demo/public;
    server_name demo.com;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";

    access_log /var/log/nginx/demo-access.log;
    error_log /var/log/nginx/demo-error.log;

    index index.php;

    charset utf-8;

    # Setting basic auth
    location / {
        # auth_basic  "Authorized personnel only.";
        # auth_basic_user_file /etc/nginx/conf.d/.htpasswd;

        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 ~ \.php$ {
		try_files $uri =404;
		fastcgi_split_path_info ^(.+\.php)(/.+)$;
		fastcgi_pass unix:/var/run/php-fpm.sock;
		fastcgi_index index.php;
		fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
		include fastcgi_params;
	}

    location ~ /\.(?!well-known).* {
        deny all;
    }
}

Như vậy là chúng ta đã cài đặt xong nginx và php fpm

8. Install postgreSql 14

Chúng ta sẽ dùng postgreSql 14 và giờ hãy cài nó


sudo dnf install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-9-x86_64/pgdg-redhat-repo-latest.noarch.rpm

// Disable the built-in PostgreSQL module
sudo dnf -qy module disable postgresql

// Update system
sudo dnf update -y

// Install postgreSql 14
sudo dnf install -y postgresql14-server

// Start and enable the PostgreSQL server
sudo /usr/pgsql-14/bin/postgresql-14-setup initdb
sudo systemctl enable postgresql-14
sudo systemctl start postgresql-14

// Access db
sudo -i -u postgres psql

// Check connect
postgres=# \conninfo

// Check version
postgres=# SELECT version();

// Exist connect
postgres=# \q

Tạo user, password access db


// Create users
sudo -i -u postgres createuser demo

// Create password for user
sudo -i -u postgres psql
ALTER USER technixleo PASSWORD 'demo';
ALTER ROLE

// Quit the shell
\q

Create database


sudo -i -u postgres

// Create a database
createdb application

// Access db
psql application

// Access db từ server
psql -h localhost -p 5432 -U [user] [db_name]
psql -h localhost -p 5432 -U demo application

Thêm config vào file .env để conect db


DB_CONNECTION=pgsql
DB_HOST=localhost
DB_PORT=5432
DB_DATABASE=application
DB_USERNAME=demo
DB_PASSWORD=demo

9. Install composer

Cài đặt composer


dnf install php
dnf -y install wget
wget https://getcomposer.org/installer -O composer-installer.php
php composer-installer.php --filename=composer --install-dir=/usr/local/bin 

// Check composer
composer --version

// Install packagist for laravel
cd /var/www/html/demo
composer install

10. Install nvm, node 18

Cài đặt nvm và node verison 18


sudo dnf update -y 
sudo dnf groupinstall "Development Tools" -y 
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh | bash 
source ~/.bashrc 

// Check version nvm
nvm --version

// List node version
nvm install --lts 

// Install node 18
nvm install 18.16.0  
nvm use 18.16.0  

// Check node version
node -v

11. Install supervisor

Cài đặt suppervisor


sudo yum install epel-release
sudo yum install supervisor

Sửa lại file config cho suppervisor từ file .ini sang file .conf cho giống document của laravel


vi /etc/supervisord.conf

[include]
files = supervisord.d/*.ini

// change file config
[include]
files = supervisord.d/*.conf

Thêm file laravel-worker.confconfig giám sát queue của laravel


vi /etc/supervisord.d/laravel-worker.conf

// Input
[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/html/demo/artisan queue:work sqs --sleep=3 --tries=3 --max-time=3600
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
;user=forge
numprocs=8
redirect_stderr=true
stdout_logfile=/var/www/html/sales-dx-34/closb-app/storage/logs/worker.log
stopwaitsecs=3600

Khởi động suppervisor


sudo systemctl enable supervisord
sudo systemctl start supervisord

// Check status
sudo supervisorctl status

// Restart suppervisord
 sudo systemctl restart supervisord

// Update code when deploy 
php artisan queue:restart

12. Install crontabs

Cài đặt crontabs để run schedule


sudo dnf update
sudo dnf install crontabs

// Start cron
sudo systemctl start crond.service
sudo systemctl enable crond.service

Thêm crontab run chedule laravel


contab -e
// Input
* * * * * cd /var/www/html/demo && php artisan schedule:run >> /dev/null 2>&1

// Check crontab
crontab -l

13. Install certbot

Cài đặt certbot để đăng kí ssl miễn phí. Trước tiên chúng ta sẽ cài đặt snapd


// Installing and start snapd
dnf install epel-release
dnf install snapd
systemctl enable --now snapd.socket
ln -s /var/lib/snapd/snap /snap
snap install core;

Cài đặt cerbot bằng snapd


dnf remove certbot
snap install --classic certbot
ln -s /snap/bin/certbot /usr/bin/certbot

Đăng kí ssl bằng command


sudo certbot --nginx

// Ouput
Saving debug log to /var/log/letsencrypt/letsencrypt.log

Which names would you like to activate HTTPS for?
We recommend selecting either all domains, or all domains in a VirtualHost/server block.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1: demo.com
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Select the appropriate numbers separated by commas and/or spaces, or leave input
blank to select all options shown (Enter 'c' to cancel):

Command trên sẽ tự động check các server name trong các file config nginx. sau đó chọn domain muốn đăng kí ssl làm theo các step của command là xong. Command sẽ tự động tại file ssl và thêm vào file config nginx cho chúng ta.


cat /etc/nginx/conf.d/default.conf
server {
    root /var/www/html/demo/public;
    server_name demo.com;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";

    access_log /var/log/nginx/demo-access.log;
    error_log /var/log/nginx/demo-error.log;

    index index.php;

    charset utf-8;

    location / {
        # auth_basic  "Authorized personnel only.";
        # auth_basic_user_file /etc/nginx/conf.d/.htpasswd;

        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 ~ \.php$ {
		try_files $uri =404;
		fastcgi_split_path_info ^(.+\.php)(/.+)$;
		fastcgi_pass unix:/var/run/php-fpm.sock;
		fastcgi_index index.php;
		fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
		include fastcgi_params;
	}

    location ~ /\.(?!well-known).* {
        deny all;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/demo.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/demo.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

server {
    if ($host = demo.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    listen 80;
    server_name demo.com
    return 404; # managed by Certbot
}

Khởi động lại nginx là chúng ta đã đăng kí ssl thành công


systemctl restart nginx

Gia hạn ssl


certbot renew --dry-run
Update email register ssl by document

// Create email
sudo certbot register --email example@gmail.com

// Update email
sudo certbot update_account --email example@gmail.com

Tổng kết

Như vậy là chúng ta đã cài đặt xong các service để deploy dự án laravel lên môi trường centos 9. Thanks for reading...

Nguồn tham khảo:
Install nginx:
https://unixcop.com/how-to-install-nginx-on-centos-9-stream
Install php 8.2:
https://wiki.crowncloud.net/?How_to_Install_PHP_8_2_in_CentOS_9_Stream
https://techviewleo.com/install-php-8-on-centos-stream-centos-stream
Install postgreSql 14:
https://technixleo.com/install-postgresql-on-centos-alma-rhel-9
Install certbot:
https://serverspace.io/support/help/setup-lets-encrypt-ssl-nginx-on-centos-8
Install supervisor:
https://www.linode.com/docs/guides/how-to-install-and-configure-supervisor-on-centos-8