본문 바로가기

리눅스

우분투에서 Laravel을 설치하는 방법

728x90

우분투에서 Laravel을 설치하는 방법

테스트 환경

도커 컨테이너 실행

docker run -d --privileged -p 80:80 --name ubuntu --hostname ubuntu anti1346/ubuntu-init:22.04 /sbin/init

ubuntu 컨테이너에 진입

docker exec -it ubuntu bash
더보기

---

lsb-release 패키지 설치

apt-get update
apt-get install -y lsb-release
apt-get install -y sudo

---

도커 컨테이너 운영체제 버전 정보

  • 운영체제 버전 정보
$ lsb_release -d
Description:	Ubuntu 22.04 LTS
  • 웹 서버 : Nginx + PHP-FPM

Nginx, PHP-FPM 설치

시스템 업데이트

sudo apt-get update && sudo apt upgrade -y
sudo apt-get install -y wget gnupg2 ca-certificates lsb-release ubuntu-keyring software-properties-common

Nginx 설치 및 설정

Nginx(stable) 리포지토리 추가

curl -Ss https://nginx.org/keys/nginx_signing.key | gpg --dearmor | tee /usr/share/keyrings/nginx-archive-keyring.gpg >/dev/null

Nginx stable 리포지토리 추가

echo deb [arch=amd64,arm64 signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] http://nginx.org/packages/ubuntu `lsb_release -cs` nginx | tee /etc/apt/sources.list.d/nginx-stable.list
sudo apt-get update

Nginx 설치

sudo apt-get install -y nginx

Nginx 버전 확인

nginx -v
$ nginx -v
nginx version: nginx/1.20.2

Nginx 서비스 활성화 및 시작

sudo systemctl --now enable nginx
$ sudo systemctl --now enable nginx
Synchronizing state of nginx.service with SysV service script with /lib/systemd/systemd-sysv-install.
Executing: /lib/systemd/systemd-sysv-install enable nginx

Nginx 서비스 상태 확인

sudo systemctl status nginx

nginx.conf 파일 편집

sudo vim /etc/nginx/nginx.conf
# For more information on configuration
user www-data;

worker_processes  auto;

error_log  /var/log/nginx/error.log notice;

pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
}

Nginx default.conf 편집

sudo vim /etc/nginx/conf.d/default.conf
server {
    listen 80;
    server_name _;
    root /usr/share/nginx/html;
    index index.html index.htm;

    access_log /var/log/nginx/host.access.log  main;

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    location /nginx_status {
    # Nginx status 페이지 설정
        stub_status;
        access_log off;
        allow 127.0.0.1;
        allow 192.168.0.0/24;
        deny all;
    }
}

Nginx 서비스 재시작

sudo systemctl status nginx

브라우저에서 테스트 페이지 확인

http://localhost

nginx1

PHP-FPM 설치 및 설정

PPA(Personal Package Archive) 추가

add-apt-repository ppa:ondrej/php -y
apt update

PHP-FPM(PHP) 설치

sudo apt-get install -y php8.1-fpm php8.1-cli php8.1-common php8.1-dev

PHP-FPM 버전 확인

php --version
$ php --version
PHP 8.1.6 (cli) (built: May 17 2022 16:46:54) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.1.6, Copyright (c) Zend Technologies
    with Zend OPcache v8.1.6, Copyright (c), by Zend Technologies

PHP-FPM 서비스 활성화 및 시작

sudo systemctl --now enable php8.1-fpm

PHP-FPM 모듈 추가 설치

sudo apt-get install -y php8.1-gd php8.1-xml php8.1-curl php8.1-igbinary
sudo apt-get install -y php8.1-xml php8.1-redis php8.1-mongodb php8.1-zip php8.1-imagick

PHP-FPM 확장 모듈 확인

php-fpm8.1 -m | egrep 'redis|imagick'
$ php-fpm8.1 -m | egrep 'redis|imagick'
imagick
redis

PHP-FPM 로그 디렉토리 생성

mkdir -p /var/log/php-fpm

php-fpm.conf 파일 편집

sudo vim /etc/php/8.1/fpm/php-fpm.conf
include=/etc/php/8.1/fpm/pool.d/*.conf

[global]
pid = /run/php/php8.1-fpm.pid

error_log = /var/log/php-fpm/error.log

daemonize = yes

www.conf 파일 편집

sudo vim /etc/php/8.1/fpm/pool.d/www.conf
[www]
user = www-data
group = www-data

listen = /var/run/php/php8.1-fpm.sock

listen.owner = www-data
listen.group = www-data
listen.mode = 0660

pm = dynamic
pm.max_children = 5
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3

slowlog = /var/log/php-fpm/www-slow.log

pm.status_path = /status

ping.path = /ping

access.log = /var/log/php-fpm/access.log

access.format = "%R - %u %t \"%m %r%Q%q\" %s %f %{mili}d %{kilo}M %C%%"

php_admin_value[error_log] = /var/log/php-fpm/www-error.log
php_admin_flag[log_errors] = on
php_value[session.save_handler] = files
php_value[session.save_path]    = /var/lib/php/sessions
php_value[soap.wsdl_cache_dir]  = /var/lib/php/wsdlcache

phpinfo 페이지 생성

echo "<?php phpinfo(); ?>" > /usr/share/nginx/html/phpinfo.php

Nginx default.conf 파일 편집

sudo vim /etc/nginx/conf.d/default.conf
server {
    listen 80;
    server_name _;
    root /usr/share/nginx/html;
    index index.html index.htm index.php;

    access_log  /var/log/nginx/host.access.log  main;
    
    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    location ~ \.php$ {
	    fastcgi_pass  unix:/var/run/php/php8.1-fpm.sock;
        fastcgi_index index.php;
	    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include       fastcgi_params;
    }

    location /nginx_status {
    # Nginx status 페이지 설정
        stub_status;
        access_log off;
        allow 127.0.0.1;
        allow 192.168.0.0/24;
        deny all;
    }

    location ~ ^/(ping|status)$ {
        # PHP-FPM ping 및 status 페이지 설정
        fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
        include fastcgi_params;
        access_log off;
        allow 127.0.0.1;
        allow 192.168.0.0/24;
        deny all;
    }
}

Nginx, PHP-FPM 서비스 재시작

systemctl restart nginx php8.1-fpm
http://localhost/phpinfo.php

php1

Composer 설치

curl, unzip 패키지 설치

sudo apt-get install -y curl unzip

PHP-FPM 모듈 추가 설치

sudo apt-get install -y php8.1-mbstring php8.1-opcache php8.1-phpdbg php8.1-readline
sudo apt-get install -y php-json php-tokenizer

Composer 다운로드

curl -fsSL https://getcomposer.org/installer -o composer-setup.php

PHP를 사용하여 Composer 설치

Laravel 프로젝트를 생성하고 관리하기 위해 Composer를 설치합니다.

php composer-setup.php --install-dir=/usr/local/bin --filename=composer
$ php composer-setup.php --install-dir=/usr/local/bin --filename=composer
All settings correct for using Composer
Downloading...

Composer (version 2.3.5) successfully installed to: /usr/local/bin/composer
Use it: php /usr/local/bin/composer

composer 버전 확인

composer -V
$ composer -V
Composer version 2.3.5 2022-04-13 16:43:00

HTML 디렉토리로 이동

cd /usr/share/nginx/html

라라벨 설치 프로그램 설치(Laravel Installer 설치)

Laravel Installer를 사용하여 Laravel 프로젝트를 생성합니다.

composer global require laravel/installer
$ composer global require laravel/installer
Changed current directory to /root/.config/composer
Info from https://repo.packagist.org: #StandWithUkraine
Using version ^4.2 for laravel/installer
./composer.json has been created
Running composer update laravel/installer
Loading composer repositories with package information
Updating dependencies
Lock file operations: 10 installs, 0 updates, 0 removals
  - Locking laravel/installer (v4.2.10)
  - Locking psr/container (2.0.2)

...

  - Installing symfony/console (v6.0.8): Extracting archive
  - Installing laravel/installer (v4.2.10): Extracting archive
4 package suggestions were added by new dependencies, use `composer suggest` to see details.
Generating autoload files
8 packages you are using are looking for funding.
Use the `composer fund` command to find out more!

환경변수(PATH) 등록

echo 'PATH=$PATH:$HOME/.config/composer/vendor/bin' >> ~/.bashrc
source ~/.bashrc

라라벨 프로젝트(helloworld) 생성

composer create-project --prefer-dist laravel/laravel /usr/share/nginx/helloworld
$ composer create-project --prefer-dist laravel/laravel /usr/share/nginx/helloworld
...
Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover --ansi

   INFO  Discovering packages.

  laravel/sail ................................................................................................................................ DONE
  laravel/sanctum ............................................................................................................................. DONE
  laravel/tinker .............................................................................................................................. DONE
  nesbot/carbon ............................................................................................................................... DONE
  nunomaduro/collision ........................................................................................................................ DONE
  nunomaduro/termwind ......................................................................................................................... DONE
  spatie/laravel-ignition ..................................................................................................................... DONE

82 packages you are using are looking for funding.
Use the `composer fund` command to find out more!
> @php artisan vendor:publish --tag=laravel-assets --ansi --force

   INFO  No publishable resources for tag [laravel-assets].

No security vulnerability advisories found.
> @php artisan key:generate --ansi

   INFO  Application key set successfully.
ls -l /usr/share/nginx/helloworld
$ ls -l /usr/share/nginx/helloworld
total 360
-rw-r--r--  1 root root   4158 Aug 10 16:19 README.md
drwxr-xr-x  7 root root   4096 Aug 10 16:19 app
-rwxr-xr-x  1 root root   1686 Aug 10 16:19 artisan
drwxr-xr-x  3 root root   4096 Aug 10 16:19 bootstrap
-rw-r--r--  1 root root   1882 Aug 10 16:19 composer.json
-rw-r--r--  1 root root 296202 Oct 20 20:02 composer.lock
drwxr-xr-x  2 root root   4096 Aug 10 16:19 config
drwxr-xr-x  5 root root   4096 Aug 10 16:19 database
-rw-r--r--  1 root root    248 Aug 10 16:19 package.json
-rw-r--r--  1 root root   1084 Aug 10 16:19 phpunit.xml
drwxr-xr-x  2 root root   4096 Aug 10 16:19 public
drwxr-xr-x  5 root root   4096 Aug 10 16:19 resources
drwxr-xr-x  2 root root   4096 Aug 10 16:19 routes
drwxr-xr-x  5 root root   4096 Aug 10 16:19 storage
drwxr-xr-x  4 root root   4096 Aug 10 16:19 tests
drwxr-xr-x 39 root root   4096 Oct 20 20:03 vendor
-rw-r--r--  1 root root    263 Aug 10 16:19 vite.config.js

라라벨 버전 확인(Laravel Framework Version)

php artisan --version
$ php artisan --version
Laravel Framework 9.13.0

라라벨 디렉토리 권한 설정

cd /usr/share/nginx/helloworld
chown -R :www-data ./{storage,bootstrap/cache}
chmod -R 777 storage
chmod -R 775 bootstrap/cache

애플리케이션 키 생성

php artisan key:generate
$ php artisan key:generate

   INFO  Application key set successfully.
cat .env | grep "^APP_KEY"
$ cat .env | grep "^APP_KEY"
APP_KEY=base64:sT6S2fGjMtU8AhvHhIuzToJ8BGbHO7Z+9RCkWNqqYBE=

nginx, php(php-fpm) 설정

default.conf 편집

server {
    listen 80;
    server_name _;
    root /usr/share/nginx/helloworld/public;
    index index.html index.htm index.php;

    access_log /var/log/nginx/host.access.log main;

    #error_page 404 /404.html;

    # redirect server error pages to the static page /50x.html
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    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; }

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Content-Type-Options "nosniff";

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    location ~ \.php$ {
	try_files $uri =404;
	fastcgi_split_path_info ^(.+\.php)(/.+)$;
	fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
        fastcgi_index index.php;
	fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
	#fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.ht {
        deny  all;
    }

    location /nginx_status {
        # Nginx status 페이지 설정
        stub_status;
        access_log off;
        allow 127.0.0.1;
        allow 192.168.0.0/24;
        deny all;
    }

    location ~ ^/(ping|status)$ {
        # PHP-FPM ping 및 status 페이지 설정
        fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
        include fastcgi_params;
        access_log off;
        allow 127.0.0.1;
        allow 192.168.0.0/24;
        deny all;
    }
}

fastcgi_params 파일 편집

cat <<'EOF' >> /etc/nginx/fastcgi_params

fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
fastcgi_param  PATH_TRANSLATED    $document_root$fastcgi_path_info;
fastcgi_param  PATH_INFO          $fastcgi_path_info;
EOF

fastcgi_params 파일 확인

더보기

---

vim /etc/nginx/fastcgi_params
fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
fastcgi_param  PATH_TRANSLATED    $document_root$fastcgi_path_info;
fastcgi_param  PATH_INFO          $fastcgi_path_info;

---

Nginx, PHP-FPM 서비스 재시작

systemctl restart nginx php8.1-fpm

브라우저에서 Laravel 페이지 확인

http://localhost

laravel1

helloworld 페이지

작업 디렉토리로 이동

cd /usr/share/nginx/helloworld

1안)

web.php 편집

vim routes/web.php
$ vim routes/web.php
<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::get('helloworld', function () {
    return '<h1>Hello World!!</h1>';
});
http://localhost/helloworld


2안)

web.php 편집

vim routes/web.php
$ vim routes/web.php
<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::get('helloworld', function () {
    return view('helloworld');
});

helloworld.blade.php 생성 및 편집

vim resources/views/helloworld.blade.php
$ vim resources/views/helloworld.blade.php
<html>
  <body>
    <h1> Hello World!! </h1>
    <?php
      echo "Hello World!!";
      echo "<br/>";
      echo "<br/>";
      date_default_timezone_set('Asia/Seoul');
      $formatted = date('Y-m-d H:i:s T');
      echo "The date and time is $formatted.";
    ?>
  </body>
</html>

 

http://localhost/helloworld

 

728x90