我真的不知道为什么,但我的 Dockerfile 映像无法访问使用 docker compose 运行的 postgres 数据库
// prisma.schema
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
// 包.json
"scripts": {
"build": "npx nest build",
"format": "prettier --write "src/*/.ts" "test/*/.ts"",
"start": "node dist/main",
"start:dev": "npm run start --watch",
"start:repl": "npm run start --entryFile repl",
"start:debug": "npm run start --watch --debug",
"lint": "eslint "{src,apps,libs,test}/\*/.ts" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json",
"prepare": "husky install",
"prisma:dev": "npx prisma migrate dev",
"prisma:reset": "npx prisma migrate reset",
"prisma:deploy": "npx prisma migrate deploy",
"prisma:studio": "npx prisma studio",
"docker:up": "docker compose up",
"docker:down": "docker compose down",
"docker:ls": "docker container ls"
},
// 文档文件
FROM node:18
WORKDIR /usr/src/app
COPY package\*.json ./
RUN npm install
COPY . .
RUN npm run prisma:deploy
RUN npm run build
EXPOSE 8080
CMD \["npm", "run", "start:dev"\]
// docker-compose.yml
version: '3'
services:
postgres:
image: postgres:15.3-alpine3.18
restart: always
environment:
POSTGRES_USER: postgres
POSTGRES_DB: personal
POSTGRES_PASSWORD: pass123
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
app:
build: .
depends_on:
- postgres
volumes:
postgres_data:
// 我正在运行什么
npm run docker:up
// 我有错误
> RUN npm run prisma:deploy:
> [email protected] prisma:deploy
> npx prisma migrate deploy
> Environment variables loaded from .env
> Prisma schema loaded from prisma/schema.prisma
> Datasource "db": PostgreSQL database "personal", schema "public" at "localhost:5432"
> Error: P1001: Can't reach database server at localhost:5432
> Please make sure your database server is running at localhost:5432.
//.env
# DATABASE_URL="postgresql://postgres:pass123@postgres:5432/personal?schema=public"
DATABASE_URL="postgresql://postgres:pass123@localhost:5432/personal?schema=public"
PORT=8080
HOST="0.0.0.0"
Obs:如果我仅使用 DATABASE_URL="postgresql://postgres:pass123@localhost:5432/personal?schema=public" (在本地主机上)运行 docker:up 仅针对 postgres,我无法使用 DBeaver 正常访问 postgress
我尝试将 DATABASE_URL 更改为: DATABASE_URL="postgresql://postgres:pass123@postgres:5432/personal?schema=public" 和 DATABASE_URL="postgresql://postgres:pass123@localhost:5432/personal?schema=public"
当您在 Docker 容器中运行 Postgres 数据库,然后尝试从另一个服务访问它时,例如您的 Node.js 应用程序也在 Docker 容器中运行,
localhost
将无法按预期工作。
在 Docker 上下文中,
localhost
指的是当前容器。因此,当您的 Prisma 客户端尝试连接到 localhost:5432
时,它会在与 Node.js 应用程序相同的容器内寻找 PostgreSQL 服务器,而该容器并不存在。
要解决此问题:
docker-compose.yml
中定义的服务名称作为数据库 URL 的主机名