MariaDB 기본 Charset 확인하기

MariaDB [(none)]> show variables like 'c%';
+----------------------------------+----------------------------+
| Variable_name                    | Value                      |
+----------------------------------+----------------------------+
| character_set_client             | utf8mb4                    |
| character_set_connection         | utf8mb4                    |
| character_set_database           | utf8mb4                    |
| character_set_filesystem         | binary                     |
| character_set_results            | utf8mb4                    |
| character_set_server             | utf8mb4                    |
| character_set_system             | utf8mb3                    |
| character_sets_dir               | /usr/share/mysql/charsets/ |
| check_constraint_checks          | ON                         |
| collation_connection             | utf8mb4_general_ci         |
| collation_database               | utf8mb4_general_ci         |
| collation_server                 | utf8mb4_general_ci         |
| column_compression_threshold     | 100                        |
| column_compression_zlib_level    | 6                          |
| column_compression_zlib_strategy | DEFAULT_STRATEGY           |
| column_compression_zlib_wrap     | OFF                        |
| completion_type                  | NO_CHAIN                   |
| concurrent_insert                | AUTO                       |
| connect_timeout                  | 10                         |
| core_file                        | OFF                        |
+----------------------------------+----------------------------+

 

 

데이터베이스의 인코딩 확인하기

MariaDB [(none)]> SELECT default_character_set_name, DEFAULT_COLLATION_NAME FROM information_schema.SCHEMATA WHERE schema_name = "wordpress";
+----------------------------+------------------------+
| default_character_set_name | DEFAULT_COLLATION_NAME |
+----------------------------+------------------------+
| utf8mb4                    | utf8mb4_general_ci     |
+----------------------------+------------------------+

 

테이블의 인코딩 확인하기

결과 중에 Collation 컬럼 확인해보면 된다.

MariaDB [wordpress]> SHOW FULL COLUMNS FROM wp_posts;
+-----------------------+---------------------+--------------------+------+-----+---------------------+----------------+---------------------------------+---------+
| Field                 | Type                | Collation          | Null | Key | Default             | Extra          | Privileges                      | Comment |
+-----------------------+---------------------+--------------------+------+-----+---------------------+----------------+---------------------------------+---------+
| ID                    | bigint(20) unsigned | NULL               | NO   | PRI | NULL                | auto_increment | select,insert,update,references |         |
| post_author           | bigint(20) unsigned | NULL               | NO   | MUL | 0                   |                | select,insert,update,references |         |
| post_date             | datetime            | NULL               | NO   |     | 0000-00-00 00:00:00 |                | select,insert,update,references |         |
| post_date_gmt         | datetime            | NULL               | NO   |     | 0000-00-00 00:00:00 |                | select,insert,update,references |         |
| post_content          | longtext            | utf8mb4_unicode_ci | NO   |     | NULL                |                | select,insert,update,references |         |
| post_title            | text                | utf8mb4_unicode_ci | NO   |     | NULL                |                | select,insert,update,references |         |
| post_excerpt          | text                | utf8mb4_unicode_ci | NO   |     | NULL                |                | select,insert,update,references |         |
| post_status           | varchar(20)         | utf8mb4_unicode_ci | NO   |     | publish             |                | select,insert,update,references |         |
| comment_status        | varchar(20)         | utf8mb4_unicode_ci | NO   |     | open                |                | select,insert,update,references |         |
| ping_status           | varchar(20)         | utf8mb4_unicode_ci | NO   |     | open                |                | select,insert,update,references |         |
| post_password         | varchar(255)        | utf8mb4_unicode_ci | NO   |     |                     |                | select,insert,update,references |         |
| post_name             | varchar(200)        | utf8mb4_unicode_ci | NO   | MUL |                     |                | select,insert,update,references |         |
| to_ping               | text                | utf8mb4_unicode_ci | NO   |     | NULL                |                | select,insert,update,references |         |
| pinged                | text                | utf8mb4_unicode_ci | NO   |     | NULL                |                | select,insert,update,references |         |
| post_modified         | datetime            | NULL               | NO   |     | 0000-00-00 00:00:00 |                | select,insert,update,references |         |
| post_modified_gmt     | datetime            | NULL               | NO   |     | 0000-00-00 00:00:00 |                | select,insert,update,references |         |
| post_content_filtered | longtext            | utf8mb4_unicode_ci | NO   |     | NULL                |                | select,insert,update,references |         |
| post_parent           | bigint(20) unsigned | NULL               | NO   | MUL | 0                   |                | select,insert,update,references |         |
| guid                  | varchar(255)        | utf8mb4_unicode_ci | NO   |     |                     |                | select,insert,update,references |         |
| menu_order            | int(11)             | NULL               | NO   |     | 0                   |                | select,insert,update,references |         |
| post_type             | varchar(20)         | utf8mb4_unicode_ci | NO   | MUL | post                |                | select,insert,update,references |         |
| post_mime_type        | varchar(100)        | utf8mb4_unicode_ci | NO   |     |                     |                | select,insert,update,references |         |
| comment_count         | bigint(20)          | NULL               | NO   |     | 0                   |                | select,insert,update,references |         |
+-----------------------+---------------------+--------------------+------+-----+---------------------+----------------+---------------------------------+---------+

utf8과 utf8mb4의 차이

UTF-8 and UTFMB4 are character sets used in MySQL to store text data.

UTF-8 is a character encoding that can represent a wide range of characters and symbols, including most of the characters used in the world's written languages. UTF-8 is a variable-width encoding, which means that characters can take up anywhere from 1 to 4 bytes of storage space in a database.

UTFMB4 is an extension of UTF-8 that can store a wider range of characters, including emoji and other special symbols. UTFMB4 uses a maximum of 4 bytes to encode characters, which makes it more memory-intensive than UTF-8.

In general, if you need to store text data that includes a limited range of characters, UTF-8 is a good choice. However, if you need to store a wider range of characters, including emoji and special symbols, UTFMB4 is the better choice. It's important to note that using UTFMB4 requires a more powerful database setup and can lead to increased memory usage, so it may not be appropriate for all applications.

 

utf8bm4_general_ci  와 utf7mb4_unicode_ci의 차이

UTF8MB4_GENERAL_CI and UTF8MB4_UNICODE_CI are collation types for UTF8MB4 character sets in MySQL.

A collation determines how text data is compared and sorted in a database. The collation type you choose affects how text data is treated in comparison operations, such as equal to (==), not equal to (!=), greater than (>), and less than (<).

UTF8MB4_GENERAL_CI is a case-insensitive collation that sorts text data in a way that is suitable for most applications. It only considers the basic letter and number characters and ignores special characters and symbols.

UTF8MB4_UNICODE_CI, on the other hand, is a case-insensitive collation that takes into account the full range of Unicode characters, including special symbols and emoji. This collation type is more suitable for applications that need to handle a wide range of characters, such as multilingual websites.

In general, UTF8MB4_GENERAL_CI is faster and uses less memory than UTF8MB4_UNICODE_CI, but it provides less accurate comparison results for special characters and symbols. UTF8MB4_UNICODE_CI provides more accurate comparison results, but is slower and uses more memory.

The choice between UTF8MB4_GENERAL_CI and UTF8MB4_UNICODE_CI depends on the specific needs of your application and the text data that you need to store in your database.

윈도우 운영체제에서 php 7.4를 설치하고, VScode 디버깅 설정하는 방법을 정리한다.

 

PHP 7.4 설치

1. 아래 사이트에서 windows용 php를 다운받는다. (설치할 버전)

https://windows.php.net/download/

 

2. 적절한 폴더에 압축을 해제한다.

예) C:/APM/php-7.4.33-Win32-vc15-x64

 

3. httpd.conf 파일 설정에서, php 경로를 변경해준다.

PHPIniDir "C:/APM/php-7.4.33-Win32-vc15-x64"
LoadModule php7_module "C:/APM/php-7.4.33-Win32-vc15-x64/php7apache2_4.dll"
AddType application/x-httpd-php .html .php
AddHandler application/x-httpd-php .php

 

4. 고급 시스템 설정에 php 경로를 등록해준다. (어디서든 php.exe 실행 가능하게 하려면)

예) C:/APM/php-7.4.33-Win32-vc15-x64 추가

 

5. 아파치를 재시작한다.

서비스 > Apache2.4 다시시작

 

VScode 에 php 디버깅 설정

1. cmd 창에 "php -i" 입력하면 phpinfo 내용이 쭉 나온다. 전부 복사한다.

 

2. https://xdebug.org/wizard 사이트에 가서 해당 내용을 붙여넣는다.

 

3. Analyse my phpinfo() output 버튼을 클릭한다.

 

4. 내 정보가 나오고, 해당 내용에 맞는 dll을 다운받을 수 있는 녹색 링크가 나온다. 클릭해서 다운받는다.

5. php 압축 푼 폴더 하위에 해당 dll을 복사한다.

예) C:\APM\php-7.2.34-Win32-VC15-x64\ext\php_xdebug-3.0.0-7.2-vc15-x86_64.dll

 

6. cmd 창에 php -m 입력해서 [PHP Modules]와 [Zend Modules]에 Xdebug가 있는지 확인한다.

 

7. php.ini 파일 설정을 변경한다.

- 기존 설정이 있는 경우, 동일하게 맞춤

- 디버깅을 위해, 아래와 같이 xDebug 설정을 추가한다.

예) C:/PHP/php-7.4.33-Win32-vc15-x64/php.ini 

[xDebug]
zend_extension = C:/APM/php-7.4.33-Win32-vc15-x64/ext/php_xdebug-3.1.6-7.4-vc15-x86_64.dll
xdebug.mode=debug
xdebug.start_with_request=yes
xdebug.client_host = localhost
xdebug.client_port = 9003
xdebug.output_dir = C:/APM/php-7.4.33-Win32-vc15-x64/tmp

 

8. 아파치를 재시작한다.

 

9. VScode를 열어, launch.json 파일 내용을 아래와 같이 수정한다.

(위 php.ini 에서 설정한 port 가 일치하도록 하고, php가 설치된 경로를 넣어준다.)

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Listen for XDebug",
            "type": "php",
            "runtimeExecutable": "C:/APM/php-7.4.33-Win32-vc15-x64/php.exe",
            "request": "launch",
            "port": 9003
        },
        {
            "name": "Launch currently open script",
            "type": "php",
            "runtimeExecutable": "C:/APM/php-7.4.33-Win32-vc15-x64/php.exe",
            "request": "launch",
            "program": "${file}",
            "cwd": "${fileDirname}",
            "port": 9003
        },
        {
            "name": "Launch Index",
            "type": "php",
            "runtimeExecutable": "C:/APM/php-7.4.33-Win32-vc15-x64/php.exe",
            "request": "launch",
            "program": "${workspaceRoot}/index.php",
            "cwd": "${workspaceRoot}",
            "port": 9003
        }
    ]
}

 

10. VScode에서 settings.json을 열어 php path를 아래와 같이 바꾸어준다.

    "php.validate.executablePath": "C:/APM/php-7.4.33-Win32-vc15-x64/php.exe",
    "php.validate.enable": false,
    "php.executablePath": "C:/APM/php-7.4.33-Win32-vc15-x64/php.exe",

 

11. 테스트용 index.php 파일 만들고, VScode에서 F5 눌러 디버깅 모드 실행한다.

 

12. 웹 브라우저에서 index.php를 실행해본다. 디버깅이 걸리면 성공!

현재 워드프레스 6.1.1에서 지원하는 안정적인 최신버전은 php 7.4이다.

(php 8.x 는 beta support 중이라.. 바로 쓰기는 불안하다)

 

이에 기존 php 7.2 버전을 php7.4로 업그레이드 하는 작업을 했다.

(운영체제 : CentOS 7)

 

1. 기존 PHP 삭제 

- 현재 설치된 php 리스트 확인

yum list installed | grep php

- php 삭제

yum remove php-*
위 명령어로 삭제가 안될때, 
yum remove --setopt=clean_requirements_on_remove=1 php php-common php-cli php-devel php-fpm php-gd php-json php-ldap php-mbstring php-mysqlnd php-odbc php-pdo php-imagick php-snmp php-soap php-xml php-xmlrpc php-opcache

 

2. EPEL 설치

 - EPEL(Extra Packages for Enterprise Linux) 각종 패키지의 최신 버전을 제공하는 저장소

yum install epel-release yum-utils -y

 

3. 기존 php7.2 remi 저장소 비활성화

yum-config-manager --disable remi-php72

 

4. php7.4 저장소 활성화

yum-config-manager --enable remi-php74

 

5. yum install 로 php7.4 버전 및 모듈들 설치

yum install php php-common php-cli php-devel php-fpm php-gd php-json php-ldap php-mbstring php-mysqlnd php-odbc php-pdo php-imagick php-snmp php-soap php-xml php-xmlrpc php-opcache -y

 

6. 설치된 php 버전 확인

php -v

 

7. php.ini 수정

기존 설정이 있다면, 그대로 변경해줌

 

8. 아파치 재시작

systemctl restart httpd

9. 사이트 정상 동작하는지 확인

 

참고

https://www.ezeelogin.com/kb/article/how-to-upgrade-php-to-7-4-on-centos-7-393.html

https://sailer.tistory.com/entry/Cent-OS-7-PHP-%EB%B2%84%EC%A0%84-%EC%98%AC%EB%A6%AC%EA%B8%B054-74

Docker compose(도커 컴포즈)란?

복수 개의 컨테이너를 실행시키는 도커 애플리케이션을 정의하기 위한 툴이다.

 

도커 컴포즈를 이용해, DB와 Wordpress 두개의 컨테이너를 만들어 실행해서 워드프레스를 설치해보도록 하겠다.

시작 전에 도커 컴포즈가 설치되어 있어야 한다. https://docs.docker.com/compose/install/

 

프로젝트 정의

1. 빈 프로젝트 디렉토리를 생성한다.

디렉토리 명은 편한것으로 만들면 된다. 이 디렉토리 안에 docker-compose.yml 파일을 저장할 것이다.

 

2. 방금 만든 디렉토리 안으로 이동한다.

예를 들어, my_wordpress라는 폴더를 만들었다면 아래 명령으로 해당 디렉토리 안으로 이동 가능하다 :

$ cd my_wordpress/

 

3. 아래의 내용으로 docker-compose.yml 파일을 생성한다. (워드프레스 블로그와, 볼륨 마운드를 한 별도의 MySQL 인스턴스를 생성할 수 있는 스크립트이다.)

services:
  db:
    # We use a mariadb image which supports both amd64 & arm64 architecture
    image: mariadb:10.6.4-focal
    # If you really want to use MySQL, uncomment the following line
    #image: mysql:8.0.27
    command: '--default-authentication-plugin=mysql_native_password'
    volumes:
      - db_data:/var/lib/mysql
    restart: always
    environment:
      - MYSQL_ROOT_PASSWORD=somewordpress
      - MYSQL_DATABASE=wordpress
      - MYSQL_USER=wordpress
      - MYSQL_PASSWORD=wordpress
    expose:
      - 3306
      - 33060
  wordpress:
    image: wordpress:latest
    ports:
      - 80:80
    restart: always
    environment:
      - WORDPRESS_DB_HOST=db
      - WORDPRESS_DB_USER=wordpress
      - WORDPRESS_DB_PASSWORD=wordpress
      - WORDPRESS_DB_NAME=wordpress
volumes:
  db_data:

 

프로젝트 빌드

프로젝트 디렉토리 안에서 아래 명령을 실행한다.

$ docker compose up -d

위 명령은 docker compose up 을 detached mode로 실행하고, 도커 이미지를 가져오고, 워드프레스와 데이터베이스 컨테이너를 시작한다. 

브라우저에서 워드프레스 접속 및 설치

이제, 워드프레스가 도커 호스트의 80 포트에서 동작한다. 브라우저로 접속해보면, 설지 시작 화면을 볼 수 있다.

도커가 로컬호스트에 설치되어 있다면, 브라우저 주소창에 http://localhost  를 입력하면 접속 가능하다.

원격 서버에 설치되어 있다면, localhost 대신 서버의 ip 주소나, 도메인명을 입력하면 된다.

종료 및 삭제

컨테이너와 기본 네트워크를 종료하지만 워드프레스 데이터베이스를 남기고 싶다면 docker compose down 명령을 입력한다.

컨테이너, 기본 네트워크, 데이터베이스까지 모두 삭제하고 싶다면 docker compose down --volumes 명령을 입력한다.

 

참고

https://docs.docker.com/samples/wordpress/

 

문제상황

EC2 서버에 접속시, 인스턴스를 시작시 생성한 key pair 이용한다.

이 때 해당 key로 ssh 접속은 잘 되는데, putty로 접속하려고 하면 'server refused our key' 라는 메시지가 뜨면서 접속이 안된다.

(기본적인 연결 설정은 모두 다 했다. PuTTYgen을 이용하여 프라이빗 키 .pem을 ppk로 변경하고 키 파일경로 설정, 올바른 username 입력 등. 방법은 다음 링크 참고 : https://docs.aws.amazon.com/ko_kr/AWSEC2/latest/UserGuide/putty.html)

 

그래도 연결이 안되고, 서버쪽 로그를 살펴보면 아래와 같은 로그가 남아있다.

userauth_pubkey: key type ssh-rsa not in PubkeyAcceptedAlgorithms [preauth]
sshd[15855]: error: Received disconnect from xxx.xxx.xxxx port 51001:14: No supported authentication methods available [preauth]

 

해결방법

ssd_config를 수정 후, sshd를 재실행 해주니 putty 접속이 된다.

 

1. /etc/ssh/sshd_config를 아래와 같이 수정해준다.

# /etc/ssh/sshd_config
PubkeyAuthentication yes # 주석을 풀어, PubKeyAuthentication을 허용해준다.
PubkeyAcceptedKeyTypes=+ssh-rsa	# 이 내용을 추가해준다.

 

2. sshd를 재실행 한다. (ubuntu 에서의 명령어)

$ sudo systemctl restart sshd

 

3. putty로 다시 접속 해본다.

문제상황

리눅스에서 docker login을 하려고 하는데, 아래와 같은 메시지가 뜨면서 로그인이 안되는 경우가 있다.

Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Post "http://%2Fvar%2Frun%2Fdocker.sock/v1.24/auth": dial unix /var/run/docker.sock: connect: permission denied

 

해결방법

/var/run/docker.sock에 접근할 권한이 없어서 그렇다. sudo 명령어 사용해서 로그인 하면, 에러 없이 잘 된다.

# sudo docker login

# Username: 아이디 입력

# Password : 비밀번호 입력

로그인 된다.

AWS EC2 서버에 설치된 도커에, MariaDB를 설치해보도록 하겠다.

 

1. DB 이미지를 받아온다 (docker pull)

docker pull [이미지명:태그]

 

아래는 최신버전의 mariadb 이미지를 받아오는 명령이다.

# sudo docker pull mariadb

특정 버전을 받고 싶다면, [:버전태그] 를 추가해준다.

사용 가능한 버전은 https://hub.docker.com/ 여기서 확인 가능하다.

# sudo docker pull mariadb:10.8

 

2. DB 이미지를 컨테이너로 실행한다. (docker run)

docker run --name [컨테이너 이름] -e [환경변수=값] -d -p [포트:포트] -v [호스트 디렉토리:컨테이터 디렉토리] [이미지명:버전태그]

 

아래는 mariadb-container라는 컨테이너 이름으로 mariadb:latest 이미지를 실행하는 예이다.

# sudo docker run --name mariadb-container -e MYSQL_ROOT_PASSWORD=wordpress -d -p 3306:3306 -v /home/username/volume/mysql:/var/lib/mysql mariadb:latest --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci
※ 옵션 설명
--name
: 생성할 컨테이너 이름
-e : 환경변수 (password) 설정
-d : Dispatch mode (백그라운드에서 실행)
-p : 포트 연결 (외부포트: Docker 내부포트)
mariadb:latest : 컨테이너로 실행할 이미지 이름 
-v : 디렉토리 마운트. 호스트 디렉토리를 컨테이너의 디렉토리로 마운트
▶ docker에 DB를 설치하는 경우, 컨테이너를 삭제하면 데이터도 함께 날아가므로, 저장소는 꼭 외부 저장소(호스트 디렉토리)를 마운트하여 사용해야 한다
▶ 호스트 디렉토리는 EC2 서버에 존재하는 디렉토리이다. (원하는 경로를 마운트 해주면 된다.)
▶컨테이너 디렉토리 경로로 지정한 /var/lib/mysql 는 일반적으로 mysql 데이터파일이 저장되는 경로이다.
▶즉, 도커에 설치된 DB는 /var/lib/mysql 폴더에 데이터를 저장하는데, 이 폴더가 호스트 디렉토리에 마운트 되어 있으므로 실제 데이터가 호스트 디렉토리에 저장이 되게 됨. 따라서 컨테이너를 삭제 해도 호스트 디렉토리에 DB 데이터가 남아있을 수 있게 된다.
--character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci : 한글이 깨지지 않도록 설정하기 위한 인자값

 

3. 컨테이너에 접속하기 (docker exec)

docker exec -it [컨테이너명] bash

 

실행중인 mariadb-container에 접속하여, bash shell에서 커맨드를 실행할 수 있다.

#sudo docker exec -it mariadb-container bash
※ 옵션 설명
-it : -i interactive 옵션과 -t Pseudo-tty 옵션을 함께 준 것으로, bash shell에서 입/출력을 가능하게 해주는 옵션이다.

 

4. MysqlWorkbench로 DB 접속해보기

- hostname엔 도커가 실행되는 서버의 IP를 입력한다. (workbench와 같은 컴퓨터에서 실행되면 127.0.0.1로 그냥 두고, 다른 서버에서 실행중이라면 다른 서버의 공인 IP를 입력)

- Store in Vault ... 를 클릭해서 비밀번호 넣어주고

- Test Connection 해보면 정상 연결이 된다. [OK] 누르면 접속 됨

 

 

참고

http://jmlim.github.io/docker/2019/07/30/docker-mysql-setup/

문제상황

웹브라우저에서 AWS 관리 콘솔로 EC2에 연결하려고 할 때, 아래와 같은 메시지가 뜨며 연결이 안되는 경우가 있다.

원인

브라우저 기반 SSH 연결은 EC2 Instance Connect 서비스를 통해 사용자의 인스턴스를 리다이렉션하여 접속하게 된다고 한다.

따라서 내 PC의 IP 주소가 아닌, EC2 인스턴스가 위치하는 리전의 AWS IP 주소를 해당 EC2 인스턴스의 Security Group에 할당해 주어야 한다.

  • 한국 리전에서 사용하는 AWS IP : 13.209.1.56/29

해결방법

1. EC2 서비스 클릭 > 좌측 [네트워크 및 보안] 메뉴 하위의 [보안 그룹] 클릭 하여 보안그룹 메뉴로 이동

 

2. 접속하려는 EC2 인스턴스에 적용되는 보안그룹에 체크 > [인바운드 규칙] 클릭 > [인바운드 규칙 편집] 클릭

 

3. [규칙 추가] 클릭

4. 아래와 같이 인바운드 규칙 추가 후 [규칙 저장] 클릭

5. 다시 [연결] 클릭해서, 인스턴스에 연결해봄

6. 아래와 같이 연결됨

참고

https://support.skdt.co.kr/ko/support/solutions/articles/42000093546--ec2-aws-%EA%B4%80%EB%A6%AC-%EC%BD%98%EC%86%94-%EC%9B%B9%EB%B8%8C%EB%9D%BC%EC%9A%B0%EC%A0%80-%EC%97%90%EC%84%9C-ec2%EC%97%90-%EC%97%B0%EA%B2%B0%ED%95%A0-%EC%88%98-%EC%97%86%EC%8A%B5%EB%8B%88%EB%8B%A4-

+ Recent posts