리눅스마스터1급 : postgressSQL 데이터베이스 설치/운영/연동하기
작성자 정보
- 관리자 작성
- 작성일
컨텐츠 정보
- 2,279 조회
- 0 추천
- 목록
본문
리눅스마스터1급 : postgressSQL 데이터베이스 설치/운영/연동하기
PostgreSQL은 강력한 차세대 객체-관계형 DBMS로 Berkeley Postgres 데이터베이스 관리 시스템에서 파생되었다.
PostGreSQL은 강력한 객체-관계형 데이터 모델과 풍부한 데이터 타입, 쉬운 확장성을 가지고 있으며, PostQuel질의 언어를 확장된 SQL의 부분 집합으로 대체하고 있다.
PostgreSQL은 MySQL의 부족한 부분과 라이선스 문제를 해결하기 위해 많이 사용되었다.
대부분의 리눅스 배포판에서 PostgreSQL을 패키지로 제공한다.
설치는 패키지 관리 도구인 "yum"으로 설치하고 기본 운영 및 웹서비스와 연동하는 부분을 알아보자.
① PostgreSQL 설치
PostgreSQL은 대부분의 리눅스 배포판에서 패키지형태로 제공한다.
다음과 같이 "yum" 또는 "울"명령어로 PostgreSQL을 설치 해 보자.
|
|
|
| [root@SULinux-64Bit htdocs]# yum install postgresql-server Loaded plugins: fastestmirror Loading mirror speeds from cached hostfile Setting up Install Process Resolving Dependencies --> Running transaction check ---> Package postgresql-server.x86_64 0:8.1.22-1.SUL2.1 set to be updated --> Processing Dependency: postgresql = 8.1.22-1.SUL2.1 for package: postgresql-server --> Running transaction check ---> Package postgresql.x86_64 0:8.1.22-1.SUL2.1 set to be updated --> Finished Dependency Resolution
Dependencies Resolved
======================================================================================= Package Arch Version Repository Size ======================================================================================= Installing: postgresql-server x86_64 8.1.22-1.SUL2.1 update 7.0 M Installing for dependencies: postgresql x86_64 8.1.22-1.SUL2.1 update 3.4 M
Transaction Summary ======================================================================================= Install 2 Package(s) Upgrade 0 Package(s)
Total download size: 10 M Is this ok [y/N]: y Downloading Packages: (1/2): postgresql-8.1.22-1.SUL2.1.x86_64.rpm | 3.4 MB 00:00 (2/2): postgresql-server-8.1.22-1.SUL2.1.x86_64.rpm | 7.0 MB 00:00 --------------------------------------------------------------------------------------- Total 7.0 MB/s | 10 MB 00:01 Running rpm_check_debug Running Transaction Test Finished Transaction Test Transaction Test Succeeded Running Transaction Installing : postgresql 1/2 Installing : postgresql-server 2/2
Installed: postgresql-server.x86_64 0:8.1.22-1.SUL2.1
Dependency Installed: postgresql.x86_64 0:8.1.22-1.SUL2.1
Complete! |
|
|
|
|
[root@RockyLinux01 html]# dnf -y install postgresql-server 마지막 메타자료 만료확인 1:35:01 이전인: 2023년 06월 16일 (금) 오전 09시 56분 33초. 종속성이 해결되었습니다. ======================================================================================================================== 꾸러미 구조 버전 레포지터리 크기 ======================================================================================================================== 설치 중: postgresql-server x86_64 13.10-1.el9_1.0.1 appstream 5.7 M 종속 꾸러미 설치 중: postgresql x86_64 13.10-1.el9_1.0.1 appstream 1.5 M postgresql-private-libs x86_64 13.10-1.el9_1.0.1 appstream 134 k
연결 요약 ======================================================================================================================== 설치 3 꾸러미
총계 내려받기 크기: 7.4 M 설치된 크기 : 29 M 꾸러미 내려받기 중: (1/3): postgresql-private-libs-13.10-1.el9_1.0.1.x86_64.rpm 447 kB/s | 134 kB 00:00 (2/3): postgresql-13.10-1.el9_1.0.1.x86_64.rpm 3.9 MB/s | 1.5 MB 00:00 (3/3): postgresql-server-13.10-1.el9_1.0.1.x86_64.rpm 8.2 MB/s | 5.7 MB 00:00 ------------------------------------------------------------------------------------------------------------------------ 합계 5.7 MB/s | 7.4 MB 00:01 연결 확인 실행 중 연결 확인에 성공했습니다. 연결 시험 실행 중 연결 시험에 성공했습니다. 연결 실행 중 준비 중 : 1/1 설치 중 : postgresql-private-libs-13.10-1.el9_1.0.1.x86_64 1/3 설치 중 : postgresql-13.10-1.el9_1.0.1.x86_64 2/3 스크립트릿 실행 중: postgresql-server-13.10-1.el9_1.0.1.x86_64 3/3 설치 중 : postgresql-server-13.10-1.el9_1.0.1.x86_64 3/3 스크립트릿 실행 중: postgresql-server-13.10-1.el9_1.0.1.x86_64 3/3 /usr/lib/tmpfiles.d/cups-lp.conf:6: Failed to resolve group 'lp'. /usr/lib/tmpfiles.d/cups-lp.conf:7: Failed to resolve group 'lp'. /usr/lib/tmpfiles.d/cups-lp.conf:8: Failed to resolve group 'lp'. /usr/lib/tmpfiles.d/cups-lp.conf:9: Failed to resolve group 'lp'. /usr/lib/tmpfiles.d/cups.conf:3: Failed to resolve group 'lp'. /usr/lib/tmpfiles.d/cups.conf:4: Failed to resolve user 'lp': No such process
확인 중 : postgresql-server-13.10-1.el9_1.0.1.x86_64 1/3 확인 중 : postgresql-private-libs-13.10-1.el9_1.0.1.x86_64 2/3 확인 중 : postgresql-13.10-1.el9_1.0.1.x86_64 3/3
설치되었습니다: postgresql-13.10-1.el9_1.0.1.x86_64 postgresql-private-libs-13.10-1.el9_1.0.1.x86_64 postgresql-server-13.10-1.el9_1.0.1.x86_64
완료되었습니다! [root@RockyLinux01 html]# |
② PostgreSQL 운영
배포판에서 제공하는 패키지로 PostgreSQL를 설치하였다면 리눅스의 서비스로 등록될 것이다.
다음과 같이 서버부팅시 자동으로 시작되게 설정한다.
|
|
|
| [root@SULinux-64Bit htdocs]# chkconfig postgresql on |
|
|
|
|
표준 서비스 명령어로 PostgreSQL 시작한다.
|
|
|
| [root@SULinux-64Bit htdocs]# service postgresql start 데이타베이스를 초기화함: [ OK ] postgresql 서비스를 시작 중: [ OK ] |
|
|
|
|
PostgreSQL 동작 확인
|
|
|
| [root@SULinux-64Bit htdocs]# service postgresql status postmaster (pid 14945 14944 14943 14941 14939)를 실행 중... |
|
|
|
|
PostgreSQL 정지
|
|
|
| [root@SULinux-64Bit htdocs]# service postgresql stop postgresql 서비스를 중지 중: [ OK ] |
|
|
|
|
PostgreSQL 접속 테스트su 명령어로 postgres 사용자로 전환한 다음, psql 명령어를 통해 DB에 접속
|
|
|
| [root@SULinux-64Bit ~]# su - postgres -bash-3.2$ psql Welcome to psql 8.1.22, the PostgreSQL interactive terminal.
Type: \copyright for distribution terms \h for help with SQL commands \? for help with psql commands \g or terminate with semicolon to execute query \q to quit
postgres=# |
|
|
|
|
③ 연동 테스트를 위한 DB 및 사용자 생성
웹과 PostgreSQL을 연동하기 위해 PostgreSQL의 DB와 사용자를 생성해야 한다.
다음예제는 sulinux DB 생성, sulinux 사용자를 생성 및 접속을 위한 설정을 하는 것이다.
인증설정 수정(/var/lib/pgsql/data/pg_hba.conf)
|
|
|
| #host all all 127.0.0.1/32 ident sameuser #====> 다음과 같이 수정 ==> host all all 127.0.0.1/32 password |
|
|
|
|
위 설정은 로컬호스트에서 DB에 접속시 비밀번호를 사용한다는 설정이다.
기본 설정은 로컬사용자와 DB사용자가 같아야 접속되는 것인데, 이렇게 설정하면 웹 접근이 되지 않아 위와 같이 설정한다.
위와 같이 설정 후 DB를 재시작한다.
DB사용자 생성
|
|
|
| [root@SULinux-64Bit ~]# su - postgres -bash-3.2$ createuser -P Enter name of role to add: sulinux Enter password for new role: 비밀번호 비밀번호 확인: 비밀번호 Shall the new role be a superuser? (y/n) y CREATE ROLE |
|
|
|
|
postgres 사용자로 전환하고, createuser 명령어를 사용하여 sulinux 사용자를 생성한다.
sulinux 사용자의 DB(sulinux)를 생성한다.
|
|
|
| -bash-3.2$ createdb -U sulinux sulinux -h 127.0.0.1 비밀번호: sulinux사용자의비밀번호 CREATE DATABASE |
|
|
|
|
postgres 사용자로 전환하고, createuser 명령어를 사용하여 sulinux 사용자를 생성한다.
psql 명령어를 통한 DB접속 및 DB확인
|
|
|
| -bash-3.2$ psql -U sulinux -h localhost Password for user sulinux: 비밀번호 Welcome to psql 8.1.22, the PostgreSQL interactive terminal.
Type: \copyright for distribution terms \h for help with SQL commands \? for help with psql commands \g or terminate with semicolon to execute query \q to quit
sulinux=# \l 데이터베이스 목록 이름 | 소유주 | 인코딩 -----------+----------+-------- postgres | postgres | UTF8 sulinux | sulinux | UTF8 template0 | postgres | UTF8 template1 | postgres | UTF8 (4건 있음)
sulinux=# |
|
|
|
|
psql 명령어로 sulinux사용자로 DB서버에 접근한 것이다.
"\l"을 입력하여, 생성된 DB리스트를 확인할 수 있다.
④ PHP에 PostgreSQL모듈 올리기
PHP에 pgsql 사용여부 옵션을 사용하지 않고 설치 했다면, pgsql 모듈은 설치되지 않는다.
pgsql 모듈을 설치해야 하며, pgsql 모듈을 설치하기 위해 postgresql-devel 패키지가 필요하다.
yum 명령어로 postgresql-devel 패키지를 설치한 후, pgsql 모듈이 있는 php 소스 디렉토리로 이동하여 phpize 수행 후 다음과 같이 configure를 수행한다.
|
|
|
| [root@SULinux-64Bit pgsql]# yum -y install postgresql-devel ==== 중간 생략 ==== [root@SULinux-64Bit pgsql]# cd /usr/local/src/php-5.4.14/ext/pgsql [root@SULinux-64Bit pgsql]# /usr/local/php/bin/phpize Configuring for: PHP Api Version: 20100412 Zend Module Api No: 20100525 Zend Extension Api No: 220100525 [root@SULinux-64Bit pgsql]# ./configure --with-php-config=/usr/local/php/bin/php-config checking for egrep... grep -E checking for a sed that does not truncate output... /bin/sed checking for cc... cc checking for C compiler default output file name... a.out checking whether the C compiler works... yes checking whether we are cross compiling... no checking for suffix of executables... checking for suffix of object files... o checking whether we are using the GNU C compiler... yes checking whether cc accepts –g... yes ==== 중간 생략 ==== |
|
|
|
|
make 명령어로 컴파일 한다.
make install으로 모듈을 설치한다.
|
|
|
| [root@SULinux-64Bit pgsql]# make /bin/sh /usr/local/src/php-5.4.14/ext/pgsql/libtool --mode=compile cc -I. -I/usr/local/src/php-5.4.14/ext/pgsql -DPHP_ATOM_INC -I/u sr/local/src/php-5.4.14/ext/pgsql/include -I/usr/local/src/php-5.4.14/ext/pgsql/main -I/usr/local/src/php-5.4.14/ext/pgsql -I/usr/lo cal/php/include/php -I/usr/local/php/include/php/main -I/usr/local/php/include/php/TSRM -I/usr/local/php/include/php/Zend -I/usr/loc al/php/include/php/ext -I/usr/local/php/include/php/ext/date/lib -DHAVE_CONFIG_H -g -O2 -c /usr/local/src/php-5.4.14/ext/pgsql/p gsql.c -o pgsql.lo mkdir .libs ==== 중간 생략 ====
[root@SULinux-64Bit pgsql]# make install Installing shared extensions: /usr/local/php/lib/php/extensions/no-debug-non-zts-20100525/ |
|
|
|
|
php 설정파일(/usr/local/php/lib/php.ini)의 마지막에 다음 줄을 추가 한다.
아래 내용은 모듈의 디렉토리를 위 make install 과정에서 모듈이 설치된 디렉토리를 설정하며, 모듈을 사용할 수 있게 하는 설정이다.
|
|
|
| extension_dir = /usr/local/php/lib/php/extensions/no-debug-non-zts-20100525/ extension=pgsql.so |
|
|
|
|
PostgreSQL 관련 모듈의 로드 여부를 확인하기 위해 다음과 같이 php의 "-i" 옵션을 사용하여 확인한다.
아래와 같이 pgsql 설정이 있다면 정상 설치된 것이다.
|
|
|
| [root@SULinux-64Bit bin]# /usr/local/php/bin/php -i |grep pgsql pgsql pgsql.allow_persistent => On => On pgsql.auto_reset_persistent => Off => Off pgsql.ignore_notice => Off => Off pgsql.log_notice => Off => Off pgsql.max_links => Unlimited => Unlimited pgsql.max_persistent => Unlimited => Unlimited OLDPWD => /usr/local/src/php-5.4.14/ext/pgsql _SERVER["OLDPWD"] => /usr/local/src/php-5.4.14/ext/pgsql |
|
|
|
|
⑤ DB 연동 테스트
PHP에서 DB를 연동하는 아주 간단한 프로그램을 작성하여 테스트해 보도록 하겠다.
"/usr/local/apache/htdocs/pgsqltest.php" 파일을 다음과 같이 작성해 본다.
|
|
|
| <?php echo "DB Connect<BR>"; $pgsql = pg_Connect("host=127.0.0.1 dbname=sulinux user=sulinux password=password");
echo "Create sutable table<BR>"; $result = pg_exec($pgsql,"CREATE TABLE sutable ( a text )");
echo "Insert data<BR>"; $result = pg_exec($pgsql,"INSERT INTO sutable VALUES('DataBase Test')");
echo "Select data<BR>"; $result = pg_exec($pgsql,"SELECT * FROM sutable");
echo "Fetch data<BR>"; $row = pg_fetch_array($result); echo "Result : <FONT color=red>".$row["a"]."</FONT><BR>";
echo "Drop sutable table<BR>"; $result = pg_exec($pgsql,"DROP TABLE sutable");
?> |
|
|
|
|
위 프로그램은 PostgreSQL DB에 연결하고, sulinux DB를 선택하며, "sutable"이라는 테이블을 생성한다.
생성되 테이블에 "DataBase Test"라는 값을 삽입하고, 삽입된 데이터는 SELECT 구문을 사용하여 뽑아낸다.
뽑아낸 데이터를 배열로 만든 다음, 출력한다.
출력 후에는 "sutable"을 제거하는 간단한 프로그램이다.
웹브라우저에서 "http://localhost/pgsqltest.php"를 호출하면 다음과 같은 결과를 볼 수 있을 것이다.
관련자료
-
이전
-
다음