LoginSignup
3
0

DockerをつかてRubyからSQLを発行してPostgreSQLを利用する

Posted at

今回やることの詳細

  1. Docker-composeを使ってRubyとPostgreSQLの二つのコンテナを作成してネットワークで繋ぎます。
  2. RubyスクリプトからSQLを発行して取得内容をコンソールに表示します。

説明すること

  • Docker-composeの使い方
  • rubyでPostreSQLにアクセスする方法

説明しないこと

  • Dockerのインストール方法
  • Linuxの基本コマンド
  • rubyの基本
  • SQL

今回使用するファイル

RubyのDockerfile

FROM ruby:3.2.2

WORKDIR /home/

COPY ./Gemfile /home/

# vendor/bundleに依存関係をインストールするよう設定する
RUN bundle config set --local path 'vendor/bundle' && \
    bundle install && \
    echo 'alias b="bundle exec"' >> ~/.bashrc

Gemfile

# frozen_string_literal: true

source "https://rubygems.org"

gem 'pg'

PostgreSQLのDockerfile

FROM postgres:15.2

ENV POSTGRES_USER=root
ENV POSTGRES_PASSWORD=pass
ENV POSTGRES_DB=test

docker-compose.yml

version: "3.8"
services:
  ap:
    build: ./src/ruby
    image: ruby:1.0
    container_name: ruby
    stdin_open: true
    tty: true
    volumes:
      - ./src/ruby/script:/home/ruby
    networks:
      - my_network
  db:
    build: ./src/postgres
    image: postgres:1.0
    container_name: postgres
    volumes:
      - ./src/postgres/data:/var/lib/postgresql/data
      - ./src/postgres/sql:/home/postgres
    networks:
      - my_network
networks:
  my_network:

test_postgresql.rb

require 'pg'

conn = PG.connect(
  host: 'postgres', # docker-composeで作成したPostgreSQLサービスのコンテナ名を指定します。
  port: 5432, # PostgreSQLのデフォルトポート番号です
  # Gemfileで指定したDBの名前とユーザー名とパスワードです
  dbname: 'test',# 
  user: 'root',
  password: 'pass'
)

# テーブルを作成します。
conn.exec("CREATE TABLE IF NOT EXISTS test1(
               id SERIAL PRIMARY KEY,
             name VARCHAR(100));"
)
#サンプルデータを1つ作成します。
conn.exec("INSERT INTO test1 VALUES (1, 'test_name') ON CONFLICT (id) DO NOTHING;")
#全てのデータを取得します。
result = conn.exec("SELECT * FROM test1;")
# 表示します。
result.each do |row|
    puts "ID: #{row['id']}, Name: #{row['name']}"
end
conn.close

ディレクトリ構成

スクリーンショット 2023-05-22 18.13.24.png
docker-dompose.ymlとsrcが同じディレクトリの中にあり、srcの中にrubyとpostgreSQLのディレクトリがあります。

作業手順

  1. docker-compose.ymlがあるフォルダに移動します
  2. docker compose build
  3. docker compose up -d
  4. docker exec -it ruby /bin/bash
  5. bundle exec ruby ruby/test_postgresql.rb
    無事テストデータが取得できれば完了です。お疲れ様でした。
3
0
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
3
0