반응형


Apache2 웹서버, MySQL 데이터베이스 서버, PHP를 Ubuntu에 설치하는 과정을 소개합니다.

LAMP는  운영 체제와 오픈 소스 소프트웨어 스택의 조합으로 Linux, Apache, MySQL, PHP의 첫글자만 가지고 만든 약어입니다.

본 포스팅에서는 Ubuntu 18.04 LTS가 설치되어 있는 PC에 LAMP 스택을 설치하는 방법을 설명합니다


webnautes@webnautes-pc:~$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 18.04 LTS
Release: 18.04
Codename: bionic




기존에 작성했던 다음 문서를 우분투 18.04에 맞추어 수정했습니다.


Ubuntu 16.04에 LAMP ( Apache2, MySQL , PHP5 / PHP7) 설치하는 방법

http://webnautes.tistory.com/1028




1.Apache2 웹서버 설치


2.MySQL 서버 설치


3.PHP 설치


4. phpMyAdmin 설치(옵션)


5. 참고




마지막 업데이트 -  2018. 12. 16




설치하는 모든 과정을 터미널 기반으로 설명합니다. Ctrl + Alt + T를 누르면 터미널이 실행됩니다.





패키지 설치를 시작하기 전에 저장소의 패키지 목록을 업데이트하고 기존에 설치되어 있던 패키지를 업그레이드 해줍니다.


sudo apt update && sudo apt upgrade



sudo와 함께 명령을 실행해야 하는 경우에는, 현재 로그인 중인 사용자의 암호를 입력해주어야 패키지 업그레이드가 진행 됩니다.





1. Apache2 웹서버 설치

웹서버(Web Server)는 웹브라우저 같은 클라이언트의 요청을 받아서 웹문서나 이미지 등을 전송해주는 역활을 합니다.



1-1. Apache2 웹서버 패키지를 설치합니다.


$ sudo apt install apache2



y를 입력 후 엔터를 누르면 설치가 진행됩니다.





1-2. 정상적으로 설치되었는지 확인하기 위해 웹 브라우저를 실행하고 웹 주소로 localhost 또는 서버 아이피 주소를 입력합니다.




다음과 같은 웹페이지가 보이면 정상적으로 설치된 것입니다.




문제가 있을 경우 크롬 웹브라우저의 경우 다음처럼 보입니다.





1-3. Apache2의 디폴트 Document Root는 /var/www/html 입니다.

이 경로에  HTML 또는 PHP 파일 등을 생성하면 웹 브라우저를 통해 해당 파일을 요청할 수 있습니다.




/etc/apache2/apache2.conf 파일을 수정하면 디폴트 Document Root를 수정할 수 있습니다.

변경할 디렉토리의 퍼미션과 소유자 지정 등이 추가로 필요합니다.


<Directory /var/www/>
       Options Indexes FollowSymLinks
       AllowOverride None
       Require all granted
</Directory>




1-4. 방어벽 프로그램 ufw를 활성화 합니다. (테스트 목적이라면 꼭 할 필요없습니다.)


webnautes@webnautes-pc:~$ sudo ufw enable
방화벽이 활성 상태이며 시스템이 시작할 때 사용됩니다



방어벽 기본 설정을 변경합니다.


webnautes@webnautes-pc:~$ sudo ufw default deny incoming
기본 incoming 정책이 'deny'로 바뀌었습니다
(당신의 규칙에 따라 업데이트를 하시는 걸 명심하십시오)


webnautes@webnautes-pc:~$ sudo ufw default allow outgoing
기본 outgoing 정책이 'allow'로 바뀌었습니다
(당신의 규칙에 따라 업데이트를 하시는 걸 명심하십시오)



SSH 접속을 허용합니다.


webnautes@webnautes-pc:~$ sudo ufw allow ssh
규칙이 추가되었습니다
규칙이 추가되었습니다 (v6)



웹서버에서 사용할 포트 80(HTTP), 443(HTTPS)에 따라 다음 세가지 중 하나를 선택합니다.


webnautes@webnautes-pc:~$ sudo ufw app info "Apache"
프로필: Apache
제목: Web Server
설명: Apache v2 is the next generation of the omnipresent Apache web server.

포트:
 80/tcp



webnautes@webnautes-pc:~$ sudo ufw app info "Apache Secure"
프로필: Apache Secure
제목: Web Server (HTTPS)
설명: Apache v2 is the next generation of the omnipresent Apache web server.

포트:
 443/tcp


webnautes@webnautes-pc:~$ sudo ufw app info "Apache Full"
프로필: Apache Full
제목: Web Server (HTTP,HTTPS)
설명: Apache v2 is the next generation of the omnipresent Apache web server.

포트:
 80,443/tcp



선택한 프로필을 방어벽에 적용합니다.


webnautes@webnautes-pc:~$ sudo ufw allow in "Apache Full"
규칙이 추가되었습니다
규칙이 추가되었습니다 (v6)



현재 방어벽 정책은 다음처럼 확인할 수 있습니다.


webnautes@webnautes-pc:~$ sudo ufw status numbered
상태: 활성

    목적                      동작 출발
    --                      -- --
[ 1] 22/tcp                     ALLOW IN Anywhere      
[ 2] Apache Full                ALLOW IN Anywhere      
[ 3] 22/tcp (v6)                ALLOW IN Anywhere (v6)      
[ 4] Apache Full (v6)           ALLOW IN Anywhere (v6)



자세한 ufw 사용법은 참고 [3]에서  확인하세요.




2. MySQL 서버 설치


MySQL은 관계형 데이터베이스 관리 시스템(relational database management system, RDBMS)입니다.

다중 사용자가 다수의 데이터베이스에 접근할 수 있도록 서버를 구성합니다.


2-1. MySQL 서버 패키지를 설치합니다.


$ sudo apt install mysql-server





2-2. MySQL 5.7은 설치 작업 중에 root 패스워드를 물어보지 않기 때문에 다음처럼 설정해야 합니다.  


webnautes@webnautes-pc:~$ sudo mysql_secure_installation

Securing the MySQL server deployment.

Connecting to MySQL using a blank password.

VALIDATE PASSWORD PLUGIN can be used to test passwords
and improve security. It checks the strength of password
and allows the users to set only those passwords which are
secure enough. Would you like to setup VALIDATE PASSWORD plugin?

Press y|Y for Yes, any other key for No: y

There are three levels of password validation policy:

LOW    Length >= 8
MEDIUM Length >= 8, numeric, mixed case, and special characters
STRONG Length >= 8, numeric, mixed case, special characters and dictionary                  file

Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG: 1
Please set the password for root here.

New password:   root 패스워드를 입력합니다.

Re-enter new password:

Estimated strength of the password: 50
Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) : y
By default, a MySQL installation has an anonymous user,
allowing anyone to log into MySQL without having to have
a user account created for them. This is intended only for
testing, and to make the installation go a bit smoother.
You should remove them before moving into a production
environment.


데이터베이스를 아무나 읽어볼 수 없게 합니다.
Remove anonymous users? (Press y|Y for Yes, any other key for No) : y
Success.


Normally, root should only be allowed to connect from
'localhost'. This ensures that someone cannot guess at
the root password from the network.

y를 입력하면 원격 접속으로 root 계정을 사용할 수 없습니다. 별도의 계정을 생성해야 합니다.
Disallow root login remotely? (Press y|Y for Yes, any other key for No) : y Success.

By default, MySQL comes with a database named 'test' that
anyone can access. This is also intended only for testing,
and should be removed before moving into a production
environment.


Remove test database and access to it? (Press y|Y for Yes, any other key for No) : y
- Dropping test database...
Success.

- Removing privileges on test database...
Success.

Reloading the privilege tables will ensure that all changes
made so far will take effect immediately.

Reload privilege tables now? (Press y|Y for Yes, any other key for No) : y
Success.

All done!




2-3. 우분투 16.04에서 사용하던 이 방법으로는 로그인이 되지 않습니다.

현재 설치된 mysql 패키지가 디폴트로 auth_socket 플러그인을 사용하기 때문이라네요.


webnautes@webnautes-pc:~$ mysql -u root -p
Enter password:
ERROR 1698 (28000): Access denied for user 'root'@'localhost'




2-4. 우선 다음처럼 사용할 데이터베이스를 새로 생성하고

(sudo 명령시 입력하는 암호 입력으로 기존 로그인을 대체합니다. )


webnautes@webnautes-pc:~$ sudo mysql

[sudo] webnautes의 암호:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 14
Server version: 5.7.22-0ubuntu18.04.1 (Ubuntu)

Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> create database db DEFAULT CHARACTER SET utf8;
Query OK, 1 row affected (0.00 sec)




2-5. 데이터베이스를 사용할 사용자를 생성합니다.


mysql> create user 사용자이름 identified by '패스워드';
Query OK, 0 rows affected (0.00 sec)



패스워드는 8자 이상으로  대문자, 특수문자, 숫자가 각각 하나 이상이 포함되어야 합니다. 현재 패스워드 관련 설정은 다음처럼 확인이 가능합니다.  


mysql> SHOW VARIABLES LIKE 'validate_password%';
+--------------------------------------+--------+
| Variable_name                        | Value |
+--------------------------------------+--------+
| validate_password_check_user_name    | OFF |
| validate_password_dictionary_file    | |
| validate_password_length             | 8 |
| validate_password_mixed_case_count   | 1 |
| validate_password_number_count       | 1 |
| validate_password_policy             | MEDIUM |
| validate_password_special_char_count | 1      |
+--------------------------------------+--------+
7 rows in set (0.01 sec)




2-6. 앞에서 생성했던 데이터베이스 db를 새로 생성한 사용자가 사용하도록 권한을 부여합니다.  


mysql> GRANT ALL PRIVILEGES ON db.* TO '사용자이름'@'localhost' identified by '패스워드';
Query OK, 0 rows affected, 1 warning (0.00 sec)




2-7. 잘 동작하는지 여부를 다음처럼 확인했습니다.


새로 생성한 사용자(webnautes)로 로그인합니다.

webnautes@webnautes-pc:~$ mysql -u webnautes -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 20
Server version: 5.7.22-0ubuntu18.04.1 (Ubuntu)

Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.


앞에서 생성해두었던 데이터베이스 db가 보입니다.
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| db                 |
+--------------------+
2 rows in set (0.00 sec)


데이터베이스 db를 사용하도록 하고

mysql> use db;
Database changed



Person 테이블을 생성합니다.

create table Person(

     id bigint(20) unsigned not null auto_increment,

     name varchar(255) not null,

     address varchar(255) not null,

     primary key (id)

)  DEFAULT CHARACTER SET utf8;

mysql> create table Person(
   ->      id bigint(20) unsigned not null auto_increment,
   ->      name varchar(255) not null,
   ->      address varchar(255) not null,
   ->      primary key (id)
   -> )  DEFAULT CHARACTER SET utf8;
Query OK, 0 rows affected (0.03 sec)


Person 테이블이 생성되었습니다.
mysql> show tables;
+--------------+
| Tables_in_db |
+--------------+
| Person       |
+--------------+
1 row in set (0.00 sec)

Insert를 해봅니다.
mysql> insert into Person(name, address) values('test', 'test');
Query OK, 1 row affected (0.00 sec)

정상적으로 동작합니다.
mysql> select * from Person;
+----+------+---------+
| id | name | address |
+----+------+---------+
|  1 | test | test    |
+----+------+---------+
1 row in set (0.00 sec)


Person 테이블을 삭제하고 종료합니다.
mysql> drop tables Person;
Query OK, 0 rows affected (0.01 sec)

mysql> show tables;
Empty set (0.00 sec)

mysql> exit
Bye




3. PHP 설치

대부분의 웹서버는 PHP 같은 서버 사이드 스크립트 언어(Server-side scripting)를 지원합니다.

단순한 HTML 문서에서는 할 수 없는 동적 웹페이지 생성이나 데이터베이스로부터 조회하거나 수정하는 등의 일을 할 수 있습니다.


3-1. php 패키지를 설치합니다.


$ sudo apt install php php-mysql





3-2. PHP가 정상적으로 설치되었는지 확인하기 위해  /var/www/html경로에 info.php 파일을 편집기로 열어서


$ sudo nano /var/www/html/info.php



다음 내용을 입력합니다.  Ctrl + O를 누른 후, 엔터를 누르면 저장이 됩니다.

Ctrl + X를 눌러서 빠져나옵니다.


<?php phpinfo(); ?>




3-3. 웹 브라우저를 실행하고 웹 주소로 localhost/info.php 또는 서버 아이피 주소/info.php를 입력합니다.




문제 없으면 아래 캡쳐화면처럼 설치된 PHP 정보를 보여줍니다.





4. phpMyAdmin 설치(옵션)

phpMyAdmin은 MySQL 데이터베이스를 관리할 수 있는 웹 인터페이스 입니다.



4-1. phpmyadmin 패키지를 설치합니다.


$ sudo apt install phpmyadmin





4-2. phpMyAdmin을 실행하기 위한 설정을 자동으로 할 웹서버를 선택합니다.

스페이스바를 눌러서  apache2를 선택하고 엔터를 누르면 설치가 계속 진행됩니다.





4-3. phpMyAdmin을 위한 설정을 데이터베이스에 적용하기 위해 예를 선택하고 엔터를 누릅니다.





4-4. MySQL에 등록할 phpMyAdmin을 위한 암호를 입력해줍니다.

앞에서 설정한 패스워드 보안 설정때문에 여기에서도 다음 규칙대로 패스워드를 만들어줘야 합니다.


패스워드는 8자 이상으로  대문자, 특수문자, 숫자가 각각 하나 이상이 포함.





4-5. 이제 웹 브라우저에서 localhost/phpmyadmin로 접속합니다.




Not Found가 보이는 경우 아래처럼 진행하고 다시 해보면됩니다.



/etc/apache2/apache2.conf 파일을 열어서 마지막에 다음줄을 추가합니다.


Include /etc/phpmyadmin/apache.conf



변경된 설정을 적용하기 위해서 다음처럼 아파치 서버를 재시작합니다.


$ /etc/init.d/apache2 restart



출처 - https://askubuntu.com/a/723431




MySQL 계정 정보를 입력하고 실행을 클릭합니다.





4-6. 다음과 같은 화면을 볼 수 있습니다.

데이터베이스 및 테이블 생성, SQL 질의등 다양한 작업을 웹기반으로 할 수 있습니다.





4-7. 사용할 수 있도록 권한 부여 받은 데이터베이스 db에 대한 작업외에는 다른 일을 할 수 없도록 되어 있습니다.  






5. 참고

[1] https://www.digitalocean.com/community/tutorials/how-to-install-linux-apache-mysql-php-lamp-stack-ubuntu-18-04


[2] https://ko.wikipedia.org/wiki/웹_서버


[3] https://www.digitalocean.com/community/tutorials/how-to-set-up-a-firewall-with-ufw-on-ubuntu-16-04


[4] http://kwonnam.pe.kr/wiki/database/mysql/charset

반응형

문제 발생시 지나치지 마시고 댓글 남겨주시면 가능한 빨리 답장드립니다.

도움이 되셨다면 토스아이디로 후원해주세요.
https://toss.me/momo2024


제가 쓴 책도 한번 검토해보세요 ^^

+ Recent posts