docker-composeでPythonとPostgreSQLを同時起動する

docker-composeでPythonとPostgreSQLを同時起動します.

# dockerの設定

# ファイル構成

project_dir
├── /db
│   ├── /psgl
│   └── Dockerfile
└── docker-compose.yml

# /db/DockerFile

FROM postgres:14
RUN localedef -i ja_JP -c -f UTF-8 -A /usr/share/locale/locale.alias ja_JP.UTF-8
ENV LANG ja_JP.UTF-8

# ./docker-compose.yml

version: "3"
services:
  # postgres
  postgres:
      build: ./db
      ports:
        - "5432:5432"
      environment:
        POSTGRES_USER: postgre
        POSTGRES_PASSWORD: postgre
        LANG: ja_JP.UTF-8
      volumes:
        - ./db/psgl:/var/lib/postgresql/data

  notebook:
    # https://hub.docker.com/r/jupyter/datascience-notebookからimageをpullする
    image: jupyter/datascience-notebook
    # ポートの設定("ホスト:コンテナ")
    user: root
    ports:
      - "8888:8888"
    # 環境変数の設定
    environment:
      - JUPYTER_ENABLE_LAB=yes
      - "GRANT_SUDO=yes"
    # ボリューム(データの永続化の場所)の設定(ホスト:コンテナ)
    # ホスト内のworkディレクトリとコンテナ内の/home/jovyan/workディレクトリが紐づいているイメージ
    volumes:
      - ./:/home/jovyan/work
    # postgres -> notebook
    depends_on:
      - postgres
    # 最後にjupyterLabに接続するためのコマンドを実行する。
    command: start-notebook.sh --NotebookApp.token=''

# ライブラリのインストール

下記のコードでライブラリをインストールします.

!sudo apt-get update
!sudo apt-get -y install libpq-dev gcc
!pip install psycopg2

# postgreSQLの操作

# postgreSQLの接続確認

import os
import psycopg2

# DATABASE_URL='postgresql://postgre:postgre@localhost:5432/postgres'
DATABASE_URL='postgresql://postgre:postgre@workspace-postgres-1:5432/postgres'

def main():
    cursor = psycopg2.connect(DATABASE_URL)
    print(cursor)

if __name__ == '__main__':
    main()

# データベース一覧の確認

import os
import psycopg2

# DATABASE_URL='postgresql://postgre:postgre@localhost:5432/postgres'
DATABASE_URL='postgresql://postgre:postgre@workspace-postgres-1:5432/postgres'

def main():
    # postgresの接続
    conn = psycopg2.connect(DATABASE_URL)
    print(conn.autocommit)
    cur = conn.cursor()
    
    # データベース一覧の確認
    cur.execute('SELECT datname FROM pg_database;')
    data = cur.fetchall() # 出力結果
    print(data)
    
    # dbとカーソルを閉じる
    cur.close()
    conn.close()

if __name__ == '__main__':
    main()

# データベースの作成

import os
import psycopg2

# DATABASE_URL='postgresql://postgre:postgre@localhost:5432/postgres'
DATABASE_URL='postgresql://postgre:postgre@workspace-postgres-1:5432/postgres'

def main():
    # postgresの接続
    conn = psycopg2.connect(DATABASE_URL)
    conn.autocommit = True # 操作の重複を防ぐ(databaseの操作)呪文
    cur = conn.cursor()
    
    # データベースの削除
    cur.execute('CREATE database db_test1')
    
    # データベース一覧の確認
    cur.execute('SELECT datname FROM pg_database;')
    data = cur.fetchall() # 出力結果
    print(data)
    
    # dbとカーソルを閉じる
    cur.close()
    conn.close()
    
if __name__ == '__main__':
    main()

# データベースの削除

import os
import psycopg2

# DATABASE_URL='postgresql://postgre:postgre@localhost:5432/postgres'
DATABASE_URL='postgresql://postgre:postgre@workspace-postgres-1:5432/postgres'

def main():
    # postgresの接続
    conn = psycopg2.connect(DATABASE_URL)
    conn.autocommit = True # 操作の重複を防ぐ(databaseの操作)呪文
    cur = conn.cursor()
    
    # データベースの作成
    cur.execute('DROP database db_test')
    
    # データベース一覧の確認
    cur.execute('SELECT datname FROM pg_database;')
    data = cur.fetchall() # 出力結果
    print(data)
    
    # dbとカーソルを閉じる
    cur.close()
    conn.close()
    
if __name__ == '__main__':
    main()

# テーブル一覧の表示

import os
import psycopg2

# DATABASE_URL='postgresql://postgre:postgre@localhost:5432/postgres'
DATABASE_URL='postgresql://postgre:postgre@workspace-postgres-1:5432/postgres'

def main():
    # postgresの接続
    conn = psycopg2.connect(DATABASE_URL)
    print(conn.autocommit)
    cur = conn.cursor()
    
    # データベース一覧の確認
    query = '''
            SELECT t.* 
            FROM (
                SELECT TABLENAME,SCHEMANAME,'table' as TYPE from PG_TABLES
                UNION SELECT VIEWNAME,SCHEMANAME,'view' as TYPE from PG_VIEWS
            ) t
            WHERE TABLENAME LIKE LOWER('{0}') 
            and SCHEMANAME like LOWER('{1}') 
            and TYPE like LOWER('{2}')'''
    cur.execute(query)
    data = cur.fetchall() # 出力結果
    print(data)
    
    # dbとカーソルを閉じる
    cur.close()
    conn.close()

if __name__ == '__main__':
    main()

# まとめ

docker-composeでPythonとpostgreSQLを同時起動しました.

# 参考サイト

docker compose

Dockerコンテナ上のPythonプログラムからPostgreSQLに接続する (opens new window)

日本語モードのPostgreSQL, pgAdmin4同時起動docker-compose.yaml (opens new window)

docker-composeでDjangoとPostgreSQLを連携した構築手順(VPS環境) (opens new window)

Docker Compose の depends_on の使い方まとめ (opens new window)

Python + PostgreSQL

Pythonでpsycopg2を使用しPostgreSQLデータベースを作成する (opens new window)

CREATE DATABASE (opens new window)

[DROP DATABASE]((https://www.postgresql.jp/document/9.4/html/sql-dropdatabase.html)

PythonでPostgreSQL(テーブル作成〜) (opens new window)

Python で PostgreSQL を操作してみよう! (opens new window)

PostgreSQLでオートコミットをオフにする方法 † (opens new window)

【 コピペでOK】9割の機能を網羅!PytonからPostgreSQLを扱うクラスを作ってみました。 (opens new window)

PostgreSQLでデータベースの一覧を取得する方法 (opens new window)

Python(psycopg2) + PostgreSQLで作成テーブル一覧を作成する

Python(psycopg2) + PostgreSQLで作成テーブル一覧を作成する

Python(psycopg2) + PostgreSQLで作成テーブル一覧を出力します。

Python(psycopg2) + PostgreSQLでosmを入出力する

Python(psycopg2) + PostgreSQLでosmを入出力する

Python(psycopg2) + PostgreSQLでosmを入出力します.