본문 바로가기

OS/Linux

ubuntu) LEMP(nginx + php + mysql) 설치 및 연동테스트

2024.04.05 - [OS/Linux] - centos) LEMP(nginx + php + mysql) 설치 및 연동테스트

 

centos) LEMP(nginx + php + mysql) 설치 및 연동테스트

apache와 php, mysql을 리눅스와 사용하면 Linux, Apache, PHP, MySQL을 앞글자만 사용하여 LAMP라고 표현합니다. LAMP를 설치하기 위한 과정은 전 글을 참고하여 진행할 수 있습니다. 2024.03.28 - [OS/Linux] - Centos7

engineer1.tistory.com

 

이전 게시글은 centos7에서 구성해 보았고,

이번에는 ubuntu22.04에서 구성하는 방법을 알아보겠습니다.

 

ubuntu에는 대체로 소스컴파일을 사용하여 소프트웨어를 설치하지 않습니다.

구성 환경은 다음과 같습니다.

ubuntu 22.04, root계정, nginx 1.18.0, mysql 8.0.36, php 8.1.2, 방화벽은 사용하지 않았습니다.

 

1. 기초 작업

먼저 패키지 설치를 위해 update와 upgrade를 진행합니다.

apt update -y && apt upgrade -y

 

2. nginx

nginx를 설치합니다.

apt install -y nginx

 

버전을 확인합니다.

nginx -v

 

localhost를 호출하여 웹페이지 확인합니다.

curl localhost

 

 

3. mysql

mysql-server를 설치합니다.

apt install mysql-server

 

root계정의 비밀번호를 설정합니다.

mysql -u root
# test DATABASE 생성
CREATE DATABASE test;

# tes DATABASE 접속 후 계정 패스워드 생성
USE test;
SELECT user, authentication_string FROM user WHERE user = 'root';
# new_password 자리에 숫자, 특수문자, 대문자 등을 섞어 비밀번호를 지정합니다. 
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'new_password';

# 설정을 저장하고 MySQL을 재로드합니다.
FLUSH PRIVILEGES;
EXIT;

 

mysql 서비스를 재시작합니다.

systemctl restart mysql

 

 

4. php

php-fpm과 php-mysql 패키지를 설치합니다.

apt install php8.1-fpm php-mysql

 

5. 연동 및 테스트

nginx와 php연동

nginx의 config를 수정합니다.

vim /etc/nginx/sites-available/default

server {
        listen 80 default_server;
        listen [::]:80 default_server;

        # SSL configuration
        #
        # listen 443 ssl default_server;
        # listen [::]:443 ssl default_server;
        #
        # Note: You should disable gzip for SSL traffic.
        # See: https://bugs.debian.org/773332
        #
        # Read up on ssl_ciphers to ensure a secure configuration.
        # See: https://bugs.debian.org/765782
        #
        # Self signed certs generated by the ssl-cert package
        # Don't use them in a production server!
        #
        # include snippets/snakeoil.conf;

        root /var/www/html;

        # Add index.php to the list if you are using PHP
        index index.html index.htm index.nginx-debian.html index.php; # index.php 추가

        server_name _;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404;
        }

        # pass PHP scripts to FastCGI server
        #
        location ~ \.php$ { # 주석 해제
                include snippets/fastcgi-php.conf;

                # With php-fpm (or other unix sockets): # 소켓모드로 실행
                fastcgi_pass unix:/run/php/php8.1-fpm.sock;
                # With php-cgi (or other tcp sockets):
                #fastcgi_pass 127.0.0.1:9000;
        }

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        location ~ /\.ht { # 주석 해제, 보안상 .ht파일 접근 거부합니다.
                deny all;
        }
}

 

설정을 적용하기 위해 재시작을 합니다.

systemctl restart nginx

 

php와 mysql 연동 테스트

mysql test database에 테스트용 테이블 생성합니다.

# test 데이터 베이서 접속
USE test;

# 테스트용 테이블(todo_list) 생성
CREATE TABLE todo_list (
	item_id INT AUTO_INCREMENT,
	content VARCHAR(255),
	PRIMARY KEY(item_id)
);

# 테이블 확인
SELECT * FROM todo_list;

 

index.php파일을 수정합니다.

vim /var/www/html/index.php

<?php
$user = "root"; 
$password = "password"; # 비밀번호 지정
$database = "test";
$table = "todo_list";

try {
  $db = new PDO("mysql:host=localhost;dbname=$database", $user, $password);
  echo "<h2>TODO</h2><ol>"; 
  foreach($db->query("SELECT content FROM $table") as $row) {
    echo "<li>" . $row['content'] . "</li>";
  }
  echo "</ol>";
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}

 

마지막으로 페이지를 확인합니다.

index.php 출력 화면

 

해당 화면이 출력되었다면, ububtu 22.04에서 nginx, mysql, php를 정상적으로 작동된 것입니다.

이상으로 LEMP구성을 마치겠습니다. 감사합니다!