Ossian Story
article thumbnail

[WEB & WAS] Apache & Django & MariaDB


WEB & DB Server 구성


WEB Server에는 Apache & Django, DB Server에는 MariaDB로 구성하여 WEB Server와 DB Server를 나눈 형태로 구성합니다.

이번 포스팅에서는 Apache & Django & MariaDB를 구성하는 포스팅을 진행합니다.


아직 Django를 설치하지 않았다면 Apache & Django Python2.x or Apache & Django Python3.x 설치하기를 참조 부탁드립니다.



MariaDB (DB Server) 설치 및 환경설정


Yum을 통해 MariaDB를 설치합니다.


[root@db-test-01 ~]# yum install -y mariadb mariadb-server




MariaDB 초기 설정


[root@db-test-01 ~]# systemctl restart mariadb
 
[root@db-test-01 ~]# mysql_secure_installation
 
 
NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!
 
In order to log into MariaDB to secure it, we'll need the current
password for the root user.  If you've just installed MariaDB, and
you haven't set the root password yet, the password will be blank,
so you should just press enter here.'
 
Enter current password for root (enter for none):    # 초기 패스워드가 없으므로 enter 입력
OK, successfully used password, moving on...
 
Setting the root password ensures that nobody can log into the MariaDB
root user without the proper authorisation.
 
Set root password? [Y/n] y      # DB Root 패스워드 설정
New password:                    # 패스워드 입력
Re-enter new password:            # 패스워드 재 입력
Password updated successfully!
Reloading privilege tables..
 ... Success!
 
 
By default, a MariaDB installation has an anonymous user, allowing anyone
to log into MariaDB 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? [Y/n] 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.
 
Disallow root login remotely? [Y/n] y    # DB Root User의 원격접속을 막을 것인지? 보안을 위해 막는 것을 권고
 ... Success!
 
By default, MariaDB 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? [Y/n] y    # Test로 생성된 데이터 베이스를 삭제할 것인지?
 - 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? [Y/n] y    # 현재 설정한 값을 적용할 것인지?
 ... Success!
 
Cleaning up...
 
All done!  If you've completed all of the above steps, your MariaDB
installation should now be secure.
Thanks for using MariaDB!'




MariaDB UTF8 설정 및 MariaDB 재시작


#/etc/mysql/my.cnf 파일에 추가
 
[client]
default-character-set=utf8
 
[mysql]
default-character-set=utf8
 
[mysqld]
collation-server = utf8_unicode_ci
init-connect='SET NAMES utf8'
character-set-server = utf8


[root@db-test-01 ~]# systemctl restart mariadb




MariaDB 접속


[root@db-test-01 ~]# mysql -u root -p




Database 생성


MariaDB [(none)]> create database web_test;




생성된 데이터베이스 선택 및 계정 생성 & 데이터베이스 사용 권한을 부여합니다.


# mysql Database 선택
MariaDB [mysql]> use mysql;
Database changed
 
# 계정 생성
MariaDB [mysql]> create user '[계정명]'@'%' identified by '[비밀번호]';
Query OK, 0 rows affected (0.00 sec)
 
 
# 생성된 데이터베이스에 접근권한 부여
MariaDB [mysql]> grant all privileges on [데이터베이스명].* to '[계정명]'@'%';
Query OK, 0 rows affected (0.00 sec)
 
 
# 계정의 접근권한 확인
MariaDB [mysql]> show grants for 'web_admin'@'%';
+------------------------------------------------------------------------------------------------------------+
| Grants for web_admin@%                                                                                   |
+------------------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'web_admin'@'%' IDENTIFIED BY PASSWORD '*994FC172DB76E7D5C7486EAF7907B6E5B54EEF3B' |
| GRANT ALL PRIVILEGES ON `web_test`.* TO 'web_admin'@'%'                                             |
+------------------------------------------------------------------------------------------------------------+
2 rows in set (0.00 sec)
 
# 변경사항 저장 및 반영
MariaDB [mysql]> flush privileges;
Query OK, 0 rows affected (0.00 sec)



신규로 생성된 계정으로 접속이 잘 되는지 확인합니다.


MariaDB [mysql]> exit
Bye
[root@db-test-01 ~]# mysql -u web_admin -p
Enter password:
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 3
Server version: 5.5.56-MariaDB MariaDB Server
 
Copyright (c) 20002017, Oracle, MariaDB Corporation Ab and others.
 
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
 
MariaDB [(none)]>




mysql port(3306)가 Listen 상태인지 확인합니다.


[root@db-test-01 ~]# netstat -anpt | grep 3306
tcp        0      0 0.0.0.0:3306            0.0.0.0:*               LISTEN      1510/mysqld




WEB Server에서 Telnet을 통해 DB Server의 3306 Port로 접근이 가능한지 확인합니다.


[root@web-test-01]# telnet 10.146.0.3 3306
Trying 10.146.0.3...
Connected to 10.146.0.3.
Escape character is '^]'.
R
5.5.56-MariaDB'6wvk9u▒wJL{I9"?Sd}gmysql_native_password





Django & MariaDB 연동


Django 서버에서 아래 패키지 설치


[root@web-test-01 ~]# yum -y install mariadb-devel gcc




[root@web-test-01 ~]# pip3.6 install mysqlclient




Django settings.py에 Databases 설정


[root@web-test-01 ~]# vi /opt/web01/web01/settings.py
 
DATABASES = {
    'default': {
        'ENGINE''django.db.backends.mysql',  # mysql 엔진 설정
        'NAME''web_test',                    # 데이터베이스 이름
        'USER''web_admin',                   # 데이터베이스 연결 시 사용할 계정
        'PASSWORD''Password',                # 계정 비밀번호
        'HOST''10.146.0.3',                  # 데이터베이스 서버 IP
        'PORT''3306',                        # 데이터베이스 연결 Port
        'OPTIONS': {                           # MySQL 연결 옵션 설정
            'init_command'"SET sql_mode='STRICT_TRANS_TABLES'",
        },
    }
}




데이터베이스 연결 및 초기 테이블 생성


[root@web-test-01 ~]# cd /opt/web01/
 
[root@web-test-01 web01]# python3.6 manage.py migrate




Django 초기 관리자 계정 생성 및 접속


Django 관리자 계정 생성


[root@web-test-01 web01]# python3.6 manage.py createsuperuser




Apache 재시작


[root@web-test-01 web01]# systemctl restart httpd




웹브라우저 실행 후 admin 페이지 접속 후 생성된 관리자 계정으로 로그인




아래와 같이 관리자페이지 접속이 정상적으로 된다면 Apache & Django & MariaDB 연동완료




※ 만약 Admin 페이지로 접속이 되지 않는다면 Django 서버에서 SELINUX를 Disabled 했는지 확인



profile

Ossian Story

@ossians