0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Dpcker環境での環境変数 DATABASE_URL

Posted at

Docker環境で開発しているとき、DBへの接続URLがよくわからない...ということがあった。

compose.yamlで db という名前がついているから、
DATABASE_URL="postgresql://user:password@db:5432/mydatabase"
にしていたら、突然接続できなくなってサーバーエラーが起きたり...

正攻法かは不明だが、以下の方法でうまく行ったので記録。

前提

  • バックエンドはExpress、ORMにPrisma採用、RDBはPOstgreSQL
  • Docker環境
    compose.yaml
    version: "3"
    services:
      next:
        build:
          context: ./next-app
          dockerfile: Dockerfile
        ports:
          - "3000:3000"
        environment:
          - PORT=3000
        volumes:
          - ./next-app:/usr/src/app
          - /usr/src/app/node_modules
        command: npm run dev
    
      app:
        build: ./api
        ports:
          - "4000:4000"
          - "9229:9229"
        volumes:
          - ./api:/usr/src/app
        depends_on:
          - db
        environment:
          - DATABASE_URL=${DATABASE_URL_DOCKER}
    
      db:
        image: postgres:latest
        ports:
          - "5432:5432"
        environment:
          POSTGRES_USER: user 
          POSTGRES_PASSWORD: password
          POSTGRES_DB: mydatabase
        volumes:
          - pgdata:/var/lib/postgresql/data
    
      playwright:
        image: mcr.microsoft.com/playwright:focal
        working_dir: /tests
        volumes:
          - ./next-app:/tests
          - ./tests:/tests
        command: ["npx", "playwright", "test"]
        depends_on:
          - next
    
    volumes:
      pgdata:
    

対応したこと

.env
# For local development (when running Prisma commands locally)
DATABASE_URL=postgresql://postgres:password@localhost:5432/mydatabase

# For Docker (when running the app inside a Docker container)
DATABASE_URL_DOCKER=postgresql://postgres:password@db:5432/mydatabase
/prismaInitialize.ts
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient({
    datasources: {
        db: {
            // 環境変数のURLどちらも良しとしつつ、基本はローカルからコマンド等を実行するので localhost:5432を優先
            url: process.env.DATABASE_URL || process.env.DATABASE_URL_DOCKER,
        },
    },
});

export default prisma;

// Prismaクエリを使用する各ファイルでimportする
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?