LoginSignup
6
1

More than 1 year has passed since last update.

【PostgreSQL】起動と停止

Last updated at Posted at 2021-08-21

1.背景

Ruby on Railsを主に学習しています。
PostgreSQLはアプリを作成して-d でデータベース指定しておく、という認識でした。
(自動で作成してもらえるので仕組みを理解できていなかったです...)

cd XX # 作成したいフォルダに移動
rails new sample_app -d postgresql # データベースを指定
rails db:create  # データベースを作成

現在Rubyでアプリ作成をしており、PostgreSQLについて学習しているので備忘録としてまとめます。

2.環境

  • mac.os バージョン10.15.6
  • Ruby 2.7.3
  • Rails 6.1.3.1
  • psql (PostgreSQL) 12.6

3.手順

①導入

brew install postgresql
brew services start postgresql

②起動と停止

その1
hogehoge@hogenoMacBook-Air ~ % postgres -D /usr/local/var/postgres
2021-08-21 15:03:44.123 JST [2927] LOG:  starting PostgreSQL 12.6 on x86_64-apple-darwin19.6.0, compiled by Apple clang version 12.0.0 (clang-1200.0.32.29), 64-bit
... -- ログが続く

上記の方法の場合、実行後にリアルタイムでログが更新されていきターミナルでの入力ができなくなります。Ctrl+cで停止できます。

その2
hogehoge@hogenoMacBook-Air ~ % pg_ctl -l /usr/local/var/postgres/server.log start
waiting for server to start.... done
server started

上記の方法ではバッグエンドでサーバーを実行することができ、ターミナルの入力が可能です。
pg_ctl stopで停止できます。

その3(その2の応用)

pg_ctl -l /usr/local/var/postgres/server.log startを毎回打つのは手間なので、環境変数を設定します。そうすると、pg_ctl startで起動できます。

※方法は、こちら7.環境変数へPATHを通す(zshの場合)を参考にしました。

環境の確認(zshかどうか)は下記のコマンドで確認できます。

hogehoge@hogenoMacBook-Air ~ % echo $SHELL

-- 実行結果が /bin/zsh の場合
echo 'export PGDATA=/usr/local/var/postgres' >> ~/.zshrc
$ source ~/.zshrc

-- 実行結果が /bin/bash の場合
echo 'export PGDATA=/usr/local/var/postgres' >> ~/.bash_profile
source ~/.bash_profile
hogehoge@hogenoMacBook-Air ~ % pg_ctl start                       
waiting for server to start....2021-08-21 15:31:47.286 JST [3240] LOG:  starting PostgreSQL 12.6 on x86_64-apple-darwin19.6.0, compiled by Apple clang version 12.0.0 (clang-1200.0.32.29), 64-bit
2021-08-21 15:31:47.286 JST [3240] LOG:  listening on IPv6 address "::", port 5432
...
 done
server started

上記の方法ではその2同様、バッグエンドでサーバーを実行することができ、ターミナルの入力が可能です。
pg_ctl stopで停止できます。

4.まとめ

とても基本的な内容かと思いますが、改めて復習することで整理できました。

5.参考

1.【PostgreSQL】MacでPostgreSQLデータベースの環境をつくろう!
2.初心者のMac + PostgreSQL インストール
3.PostgreSQLの起動・接続・終了・停止コマンドとよく使うpsqlコマンド

6.最後に

記事の感想や意見、ご指摘等あれば伝えていただけるとありがたいです。
読んでいただき、ありがとうございました。

6
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
1