맥 환경에 PostgreSQL 설치하는 방법

맥 M3 모델 환경에서 Homebrew를 이용하여 PostgreSQL을 설치하는 방법을 정리해봤습니다.

1. Homebrew 설치 확인

우선, Homebrew가 설치되어 있는지 확인하세요. 터미널을 열고 아래 명령어를 입력하세요:

brew --version

Homebrew가 설치되어 있지 않다면, 아래 명령어를 터미널에 입력하여 설치할 수 있습니다:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

2. PostgreSQL 설치

Homebrew가 설치되어 있다면, PostgreSQL을 설치할 수 있습니다. 터미널에 아래 명령어를 입력하세요:

brew install postgresql

3. PostgreSQL 서비스 시작

PostgreSQL이 설치되면, 서비스를 시작해야 합니다. 서비스 시작 명령어는 다음과 같습니다:

brew services start postgresql

서비스를 수동으로 실행하고 싶다면 아래 명령어를 사용할 수도 있습니다:

pg_ctl -D /opt/homebrew/var/postgres start

4. PostgreSQL 데이터베이스 초기화

PostgreSQL을 처음 설치한 경우, 데이터베이스를 초기화해야 합니다. 이 단계는 한 번만 수행하면 됩니다:

initdb /opt/homebrew/var/postgres

5. PostgreSQL 사용

PostgreSQL 서비스가 시작된 후, 데이터베이스에 접속하여 사용할 수 있습니다. 기본적으로 PostgreSQL은 postgres라는 사용자를 만듭니다. 아래 명령어를 사용하여 PostgreSQL 쉘에 접속할 수 있습니다:

psql postgres

여기서 postgres는 데이터베이스의 이름입니다. 다른 데이터베이스를 만들고 싶다면, 다음 명령어를 사용할 수 있습니다:

createdb mydb
psql mydb

6. PostgreSQL 서비스 중지

더 이상 PostgreSQL을 사용하지 않을 경우, 서비스를 중지할 수 있습니다:

brew services stop postgresql

7. 설치 확인 및 버전 확인

마지막으로, PostgreSQL이 제대로 설치되었는지 확인하고 버전을 확인할 수 있습니다:

postgres --version

8. 현재 설치된 버전이 이미 있는지 확인하는 방법

그리고 현재 설치된 버전이 이미 있는지 확인하는 방법도 정리해봤습니다.
PostgreSQL이 현재 시스템에 설치되어 있는지 확인하는 방법은 여러 가지가 있습니다. 아래에 그 방법들을 정리해드리겠습니다.

1. brew 명령어로 확인

Homebrew를 통해 PostgreSQL이 설치되어 있는지 확인하는 방법입니다.

brew list postgresql

이 명령어를 실행했을 때 PostgreSQL이 설치되어 있다면, 설치된 버전이 표시됩니다. 설치되지 않았다면 아무런 출력도 없거나 에러 메시지가 표시됩니다.

2. psql 명령어로 확인

psql은 PostgreSQL의 커맨드라인 도구입니다. 이 명령어를 사용하여 PostgreSQL이 설치되었는지 확인할 수 있습니다.

psql --version

이 명령어를 실행했을 때, PostgreSQL이 설치되어 있다면 버전 정보를 출력합니다. 만약 psql: command not found와 같은 메시지가 나오면 PostgreSQL이 설치되어 있지 않거나, 설치된 경로가 시스템 경로에 포함되어 있지 않은 것입니다.

3. which 명령어로 확인

which 명령어를 사용하여 psql 명령어의 경로를 확인할 수도 있습니다.

which psql

psql의 경로가 출력되면, PostgreSQL이 설치된 상태입니다. 출력이 없으면 설치되지 않은 것입니다.

4. pg_ctl 명령어로 확인

pg_ctl은 PostgreSQL 서버의 상태를 관리하는 도구입니다. 이 도구를 사용하여 PostgreSQL의 설치 여부를 확인할 수 있습니다.

pg_ctl --version

이 명령어도 버전 정보를 출력하면 PostgreSQL이 설치된 상태입니다. 그렇지 않다면 설치되지 않은 것입니다.

맥 M3 환경에서 pgAdmin을 사용하여 PostgreSQL을 관리하는 방법은 다음과 같습니다. pgAdmin은 PostgreSQL을 관리하기 위한 GUI 도구로, 데이터베이스를 시각적으로 관리하고 쿼리를 실행할 수 있습니다.

9. pgAdmin 설치

9.1 Homebrew를 통한 설치

Homebrew를 사용하여 pgAdmin을 설치할 수 있습니다. 터미널을 열고 아래 명령어를 입력하세요:

brew install --cask pgadmin4

이 명령어는 pgAdmin의 최신 버전을 설치합니다. 설치가 완료되면 애플리케이션 폴더에 pgAdmin 4가 추가됩니다.

9.2 공식 웹사이트에서 설치

Homebrew 대신 pgAdmin공식 웹사이트에서 설치 파일을 직접 다운로드할 수도 있습니다.

  1. pgAdmin 다운로드 페이지로 이동합니다.
  2. macOS용 설치 파일을 다운로드하고 설치합니다.

9.3 pgAdmin 실행

설치가 완료되면, 다음 방법으로 pgAdmin을 실행할 수 있습니다:

  1. 애플리케이션 폴더에서 pgAdmin 4를 찾아서 실행합니다.
  2. 또는 Spotlight(Command + Space)를 사용하여 "pgAdmin"을 검색하고 실행할 수도 있습니다.

9.4 PostgreSQL 서버에 연결

pgAdmin이 실행되면 PostgreSQL 서버에 연결할 수 있습니다.

  1. pgAdmin을 실행하고, 상단의 Server 부분에서 우클릭하여 Create > Server를 선택합니다.
  2. General 탭에서 서버의 이름을 입력합니다. 이 이름은 pgAdmin 내에서만 표시됩니다.
  3. Connection 탭으로 이동하여 아래 정보를 입력합니다:

    • Host name/address: localhost (또는 PostgreSQL 서버가 실행 중인 IP 주소)
    • Port: 5432 (기본 포트)
    • Username: postgres (기본 사용자 이름)
    • Password: PostgreSQL을 설치할 때 설정한 비밀번호
  4. 모든 설정이 완료되면 Save를 클릭하여 연결을 완료합니다.

9.5 데이터베이스 관리

서버에 연결된 후, pgAdmin에서 PostgreSQL 데이터베이스를 관리할 수 있습니다. 데이터베이스를 만들거나 테이블을 생성하고, SQL 쿼리를 실행하는 등의 작업을 할 수 있습니다.

9.6 pgAdmin 업데이트 및 제거

Homebrew를 사용하여 설치한 경우, 아래 명령어를 통해 pgAdmin을 업데이트하거나 제거할 수 있습니다:

  • 업데이트:

    brew upgrade --cask pgadmin4
  • 제거:
    brew uninstall --cask pgadmin4

이제 pgAdmin을 사용하여 macOS에서 PostgreSQL 데이터베이스를 쉽게 관리할 수 있습니다.

10. db table 조회하기

To see the list of tables in your PostgreSQL database using psql, you can use the following command:

\dt

log into your PostgreSQL database using the psql command-line interface:

   psql -U your_username -d your_database_name

Once you're in the psql environment, use the \dt command to list all the tables in the current database:

   \dt

This will show a list of tables along with their schema, name, type, and owner.

If you want to see the tables in a specific schema, you can do:

\dt schema_name.*

If you want to see more detailed information about a specific table, you can use:

\d table_name

This will display the structure of the table, including its columns, types, and any indexes or constraints.

11. 백업

To back up your PostgreSQL database for later use, there are several methods you can use. The best practice is to use PostgreSQL's built-in tools rather than copying files directly, as this ensures data consistency and reliability. However, if you need to back up the raw data files, here's what you should consider:

1. Recommended Method: Using pg_dump

The safest and most portable way to back up your PostgreSQL database is by using the pg_dump utility. This tool creates a logical backup, which you can easily restore on any PostgreSQL instance.

  • Backup:

    pg_dump -U your_username -d mydb -F c -b -v -f /path/to/backup/mydb.backup
    • -F c: Specifies the format as custom, which is compressed and includes metadata.
    • -b: Includes large objects.
    • -v: Verbose mode.
    • -f: Specifies the output file.
  • Restore:

    pg_restore -U your_username -d mydb -v /path/to/backup/mydb.backup

This method is the most reliable and recommended for backups.

2. Alternative: Copying the Data Directory (Not Recommended)

If you still prefer copying the files directly (e.g., for quick local backups), you need to back up the entire PostgreSQL data directory. However, this method is not recommended because it can lead to data corruption if the database is active during the copy.

Steps to Back Up the Data Directory:

  1. Stop PostgreSQL Service:
    You should stop the PostgreSQL service to ensure data consistency before copying the files:

    brew services stop postgresql
  2. Copy the Data Directory:
    Find the data directory (as mentioned earlier) and copy it:

    cp -r /usr/local/var/postgres /path/to/backup/

    Or, if using Apple Silicon:

    cp -r /opt/homebrew/var/postgres /path/to/backup/

    Make sure the backup location has enough space and is secure.

  3. Restart PostgreSQL Service:
    After copying, restart the PostgreSQL service:

    brew services start postgresql

To Restore:

To restore, you would stop PostgreSQL, replace the data directory with your backup, and restart the service. Again, this is risky and can lead to issues if not done carefully.

Summary:

  • Best Practice: Use pg_dump and pg_restore for safe, consistent backups and easy restoration.
  • Copying Files: If you must, back up the entire PostgreSQL data directory after stopping the service. However, this method is generally discouraged.

Using pg_dump ensures that your backups are portable, consistent, and less prone to errors, making it the preferred choice for database backups.

Leave a Comment