I.K.Picture & IT Info.

[PostgreSQL] Master /Slave 이중화 작업 본문

Development/Database

[PostgreSQL] Master /Slave 이중화 작업

helpful-intruder 2018. 9. 22. 16:32
반응형

데이터베이스 이중화 작업을 하려면 장비를 통한 방법도 있지만,


Replication이라는... 방식으로 별도 장비 없이 구축가능한 방법이 있습니다. 


MySQL도 그렇고 PostgreSQL도 모두 가능한데요 


전 이번에 PostgreSQL에 대한 Replication 하는 방법을 정리해보고자 합니다. 


일단 구성은 간단히 Master 1대와 Slaver 1대로 구축을 해보았습니다.


운영체제는 모두 Windows Server 2012 R2로 사용하였는데 

사실 다른 운영체제를 사용해도 방법은 모두 동일합니다. 

대신 설정 파일 위치 자체가 조금 달라지지 그 부분만 정확히 아신다면 문제 없겠네요~



자 그럼 이제 정리해보겠습니다. 


일단 정보에 대해 간단히 정리하겠습니다. 


   Master 

     > ip: 192.168.0.10

   Slave

     > ip: 192.168.0.11


  공통사항

    > 운영체제 : Windows 2012 R2

    > 데이터베이스 : PostgreSQL 9.5


일단 DB를 각 서버에 설치했다는 가정하에 시작하겠습니다. 


제일 먼저, "서비스(services)" 에 들어가보면 PostgreSQL 서비스가 등록되어 있습니다 




더블클릭 or 오른쪽클릭 속성을 가보면 로그온(Log On) 탭으로 이동을 합니다. 

이 때 권한 설정때문에 Log on 계정을 현재 로그인한 계정 또는 서비스를 할 계정으로 변경해줘야합니다. 


변경은 Browse 를 클릭하여 아이디 검색 후 설정해주면됩니다.

Password 를 작성해줘야합니다. 


(아디디 검색 시 사용자 이름 검색 후 Check Names 를 눌러주면 디테일하게 로그인 이름이 나옵니다)







이 작업은 Master/ Slave 에 모두 작업하시고 그 다음 서비스를 재시작 해주시기 바랍니다 





자 이제 설정 부분입니다.


일단 제일 먼저 Master 부분입니다.


PostgreSQL 일반 설정인 postgresql.conf 설정입니다. 

일반적으로 Windows 에서는 "C:\Program Files\PostgreSQL\9.5\data" 위치에 있습니다.


postgresql.conf 에대한 파일 수정 부분은 아래와 같습니다. 

전체 파일을 보여드리고 수정 부분을 빨간색으로 표시해놓을께요

(위쪽과 아래쪽 필요 없는 부분 그리고 내용에 대한 주석들은 모두 제거하였습니다)


...


#------------------------------------------------------------------------------

# CONNECTIONS AND AUTHENTICATION

#------------------------------------------------------------------------------


# - Connection Settings -


listen_addresses = '*' # what IP address(es) to listen on;

# comma-separated list of addresses;

# defaults to 'localhost'; use '*' for all

# (change requires restart)

port = 5432 # (change requires restart)

max_connections = 100 # (change requires restart)

#superuser_reserved_connections = 3 # (change requires restart)

#unix_socket_directories = '' # comma-separated list of directories

# (change requires restart)

#unix_socket_group = '' # (change requires restart)

#unix_socket_permissions = 0777 # begin with 0 to use octal notation

# (change requires restart)

#bonjour = off # advertise server via Bonjour

# (change requires restart)

#bonjour_name = '' # defaults to the computer name

# (change requires restart)


# - Security and Authentication -


#authentication_timeout = 1min # 1s-600s

#ssl = off # (change requires restart)

#ssl_ciphers = 'HIGH:MEDIUM:+3DES:!aNULL' # allowed SSL ciphers

# (change requires restart)

#ssl_prefer_server_ciphers = on # (change requires restart)

#ssl_ecdh_curve = 'prime256v1' # (change requires restart)

#ssl_cert_file = 'server.crt' # (change requires restart)

#ssl_key_file = 'server.key' # (change requires restart)

#ssl_ca_file = '' # (change requires restart)

#ssl_crl_file = '' # (change requires restart)

#password_encryption = on

#db_user_namespace = off

#row_security = on


# GSSAPI using Kerberos

#krb_server_keyfile = ''

#krb_caseins_users = off


# - TCP Keepalives -

# see "man 7 tcp" for details


#tcp_keepalives_idle = 0 # TCP_KEEPIDLE, in seconds;

# 0 selects the system default

#tcp_keepalives_interval = 0 # TCP_KEEPINTVL, in seconds;

# 0 selects the system default

#tcp_keepalives_count = 0 # TCP_KEEPCNT;

# 0 selects the system default


...



#------------------------------------------------------------------------------

# WRITE AHEAD LOG

#------------------------------------------------------------------------------


# - Settings -

 

wal_level = hot_standby # minimal, archive, hot_standby, or logical

# (change requires restart)

#fsync = on # turns forced synchronization on or off

#synchronous_commit = on # synchronization level;

# off, local, remote_write, or on

#wal_sync_method = fsync # the default is the first option

# supported by the operating system:

#   open_datasync

#   fdatasync (default on Linux)

#   fsync

#   fsync_writethrough

#   open_sync

#full_page_writes = on # recover from partial page writes

#wal_compression = off # enable compression of full-page writes

#wal_log_hints = off # also do full page writes of non-critical updates

# (change requires restart)

#wal_buffers = -1 # min 32kB, -1 sets based on shared_buffers

# (change requires restart)

#wal_writer_delay = 200ms # 1-10000 milliseconds


#commit_delay = 0 # range 0-100000, in microseconds

#commit_siblings = 5 # range 1-1000


# - Checkpoints -


#checkpoint_timeout = 5min # range 30s-1h

#max_wal_size = 1GB

#min_wal_size = 80MB

#checkpoint_completion_target = 0.5 # checkpoint target duration, 0.0 - 1.0

#checkpoint_warning = 30s # 0 disables


# - Archiving -

 

archive_mode = on # enables archiving; off, on, or always

# (change requires restart) 

archive_command = 'copy "%p" "\\\\192.168.0.11\\archive\\%f"'

# command to use to archive a logfile segment

# placeholders: %p = path of file to archive

#               %f = file name only

# e.g. 'test ! -f /mnt/server/archivedir/%f && cp %p /mnt/server/archivedir/%f'

#archive_timeout = 0 # force a logfile segment switch after this

# number of seconds; 0 disables



#------------------------------------------------------------------------------

# REPLICATION

#------------------------------------------------------------------------------


# - Sending Server(s) -


# Set these on the master and on any standby that will send replication data.

 

max_wal_senders = 1 # max number of walsender processes

# (change requires restart) 

wal_keep_segments = 32 # in logfile segments, 16MB each; 0 disables


...


위 내용중 archive_command 같은 경우에는 네트워크 공유 폴더 형식으로 데이터를 받아오는 것이기 때문에 

두 서버간 해당 포트가 개방되어 있어야합니다.

   TCP : 137, 138, 445

   UDP : 137, 138


물론 PostgreSQL 포트인 TCP 5432도 개방되어 있어야겠죠??


공유폴더로 할 폴더 이름이 지금 archive가 되어 있는데 이 부분에 대해 궁금하신 분은 아래 slave 쪽 설명을 먼저 

확인해보시면 좀 더 이해하기 쉬우실꺼같아요~!



그 다음이 pg_hba.conf 입니다. 

postgresql.conf와 동일 폴더에 있습니다. 


...


# TYPE  DATABASE        USER            ADDRESS                 METHOD


# IPv4 local connections:

host    all             all             127.0.0.1/32            md5

# IPv6 local connections:

host    all             all             ::1/128                 md5

# Allow replication connections from localhost, by a user with the

# replication privilege.

#host    replication     postgres        127.0.0.1/32            md5

#host    replication     postgres        ::1/128                 md5

host replication     postgres 192.168.0.11/32 trust


해당 내용은 slave에서 접속이 가능하도록 설정해놓는 것입니다. 



자 그럼 이제 Slave 쪽 설정입니다. 

Slave 쪽도 마찬가지로 일단 postgresql.conf를 수정해줘야되는데요 

Master하고는 다르게 딱하나만 변경해주면됩니다.


... 

 

hot_standby = on # "on" allows queries during recovery

# (change requires restart)

#max_standby_archive_delay = 30s # max delay before canceling queries

# when reading WAL from archive;

# -1 allows indefinite delay

#max_standby_streaming_delay = 30s # max delay before canceling queries

# when reading streaming WAL;

# -1 allows indefinite delay

#wal_receiver_status_interval = 10s # send replies at least this often

# 0 disables

#hot_standby_feedback = off # send info from standby to prevent

# query conflicts

#wal_receiver_timeout = 60s # time that receiver waits for

# communication from master

# in milliseconds; 0 disables

#wal_retrieve_retry_interval = 5s # time to wait before retrying to

# retrieve WAL after a failed attempt


...




대신 새로운 파일을 만들어야하는데 recovery.conf 라는 파일을 동일 폴더에 생성하여 아래처럼 작성해주세요



standby_mode ='on'

primary_conninfo = 'host=192.168.0.10 port=5432 user=postgres password=postgres'

restore_command = 'copy "\\\\192.168.0.11\\archive\\%f" "%p"'



당연히 primary_conninfo 에는 master 접속 정보를 작성해주시면되구요

restore_command에는 master에서 command측에 작성한 경로를 적어주시면됩니다.


참고로 Windows에서는 copy가 cmd에서 파일 복사 명령어로 저렇게 써준 것이구요

Linux에서는 cp 이기 때문에 뭐 그건 운영체제에 맞춰서 작성해주시면 되겠습니다 :)



자 일단 이렇게 하면 설정 파일은 모두 건드린 것인데... 

일단 slave 측에 원하는 폴더 부분에 archive 폴더를 생성해서 공유폴더로 만들어버립니다. 

(필요에 맞춰 폴더 이름은 변경할 수 있으며 master 측에 저장을 해도 큰 문제 없습니다)


전 그냥 C:드라이브에 폴더 하나 만들어서 공유 폴더로 만들었습니다. 

공유 폴더를 만드는 방법으로는 


   1. 폴더 생성

   2. 오른쪽 클릭 후 속성

   3. 공유 (sharing) 탭

   4. 공유 버튼 누른 후 읽기 쓰기 방식으로 공유 확인






자 이제 Master에 있는 초기 모든 데이터를 일단 Slave 측에 동일하게 맞춰주는 역할을 하면서 설정 또한 동일하게 맞춰주는 작업을 해야합니다.



먼저 Master 측 PostgreSQL 서버를 재시작해주세요

그 다음 psql 쉘을 들어갑니다.  Windows에서는 아래 그림처럼 검색해서 들어가면 좀 더 편리하게 쉘로 접근할 수 있습니다. 





쉘 로그인이 되면 다음 명령어를 작성해줍니다.

postgres=#   select pg_start_backup('based'); 




저 결과가 보여지게되면 data폴더에 있는 파일들을 아래 그림처럼 특정 파일을 제외 후 복사를 합니다. 



보면 수정한 pg_hba, postgersql 을 제외했구요 특정 서비스 구동 id인 postmaster.pid,  pg_ident를 제외하였습니다. 


이렇게 복사한 내용을 slave   data폴더에 그대로 덮어쓰기 해줍니다 

(혹시 모르니 기존 data폴더는 백업해놓고 붙여넣어주세요)


붙여넣기가 다 되면 아까 start_backup 쉘 부분에 아래 내용을 작성해서 backup 부분을 정지시켜줍니다.


postgres=#   select pg_stop_backup(); 





자 그럼 이제 slave 측  서비스도 재시작을 해줍니다..!!!


이렇게 하면 이중화 작업이 끝납니다~!


테스트를 위해서 Master쪽 테이블이나 내용을 한번 pgadmin으로 변경해보면 slave 측에 자동으로 업그레이드되는 것을 확인할 수 있습니다.


간단하게 보여드리기 위해 Master 1대, Slave 1대를 가지고 했지만


Slave 쪽 작업은 계속 증가할 수 있습니다.


물론 증가될 때마다 Master 쪽에 있는 PostgreSQL 설정 중 REPLICATION 부분을 Slave 갯수에 맞게 해줘야한다는 것입니다.



반응형
Comments