Deployment error can't reach database

I’m developing an app with the blues stack from Remix and I’m having some troubles deploying it to fly.

I created the postgres database and connected it to the main app but when I’m deploying it gives me this error.

2023-05-26T08:28:23Z   [info]🔌 setting up prisma client to bog.vanguard-adf5-db.flycast:5432
2023-05-26T08:28:23Z   [info]✅ app ready: http://localhost:8080
2023-05-26T08:28:23Z   [info]✅ metrics ready: http://localhost:8081/metrics
2023-05-26T08:28:24Z   [info]this.engine?.query(s,o,i?.id),this.lastQuery=s;let l=this
2023-05-26T08:28:24Z   [info]You may have to run ${Yt.default.greenBright("prisma generate")} for your changes to take effect.`,this.config.clientVersion);return r}parseEngineResponse(r){if(!r)throw new Z("Response from the Engine was empty",{clientVersion:this.config.clientVersion});try{return JSON.parse(r)}catch{throw new Z("Unable to JSON.parse response from engine",{clientVersion:this.config.clientVersion})}}convertDatasources(r){let n=Object.create(null);for(let{name:i,url:o}of r)n[i]=o;return n}async loadEngine(){if(!this.engine){this.QueryEngineConstructor||(this.library=await this.libraryLoader.loadLibrary(),this.QueryEngineConstructor=this.library.QueryEngine);try{let r=new WeakRef(this);this.engine=new this.QueryEngineConstructor({datamodel:this.datamodel,env:process.env,logQueries:this.config.logQueries??!1,ignoreEnvVarErrors:!0,datasourceOverrides:this.datasourceOverrides,logLevel:this.logLevel,configDir:this.config.cwd,engineProtocol:this.engineProtocol},n=>{r.deref()?.logger(n)}),Hl++}catch(r){let n=r,i=this.parseInitError(n.message);throw typeof i=="string"?n:new G(i.message,this.config.clientVersion,i.error_code)}}}logger(r){let n=this.parseEngineResponse(r);if(!!n){if("span"in n){this.config.tracingConfig.enabled===!0&&Co(n);return}n.level=n?.level.toLowerCase()??"unknown",Em(n)?this.logEmitter.emit("query",{timestamp:new Date,query:n.query,params:n.params,duration:Number(n.duration_ms),target:n.module_path}):wm(n)?this.loggerRustPanic=new fe(this.getErrorMessageWithLink(`${n.message}: ${n.reason} in ${n.file}:${n.line}:${n.column}`),this.config.clientVersion):this.logEmitter.emit(n.level,{timestamp:new Date,message:n.message,target:n.module_path})}}getErrorMessageWithLink(r){return dl({platform:this.platform,title:r,version:this.config.clientVersion,engineVersion:this.versionInfo?.commit,database:this.config.activeProvider,query:this.lastQuery})}parseInitError(r){try{return JSON.parse(r)}catch{}return r}parseRequestError(r){try{return JSON.parse(r)}catch{}return r}on(r,n){r==="beforeExit"?this.beforeExitListener=n:this.logEmitter.on(r,n)}async start(){if(await this.libraryInstantiationPromise,await this.libraryStoppingPromise,this.libraryStartingPromise)return Ue(`library already starting, this.libraryStarted: ${this.libraryStarted}`),this.libraryStartingPromise;if(this.libraryStarted)return;let r=a(async()=>{Ue("library starting");try{let i={traceparent:De({tracingConfig:this.config.tracingConfig})};await this.engine?.connect(JSON.stringify(i)),this.libraryStarted=!0,Ue("library started")}catch(i){let o=this.parseInitError(i.message);throw typeof o=="string"?i:new G(o.message,this.config.clientVersion,o.error_code)}finally{this.libraryStartingPromise=void 0}},"startFn"),n={name:"connect",enabled:this.config.tracingConfig.enabled};return this.libraryStartingPromise=me(n,r),this.libraryStartingPromise}async stop(){if(await this.libraryStartingPromise,await this.executingQueryPromise,this.libraryStoppingPromise)return Ue("library is already stopping"),this.libraryStoppingPromise;if(!this.libraryStarted)return;let r=a(async()=>{await new Promise(o=>setTimeout(o,5)),Ue("library stopping");let i={traceparent:De({tracingConfig:this.config.tracingConfig})};await this.engine?.disconnect(JSON.stringify(i)),this.libraryStarted=!1,this.libraryStoppingPromise=void 0,Ue("library stopped")},"stopFn"),n={name:"disconnect",enabled:this.config.tracingConfig.enabled};return this.libraryStoppingPromise=me(n,r),this.libraryStoppingPromise}async getDmmf(){await this.start();let r=De({tracingConfig:this.config.tracingConfig}),n=await this.engine.dmmf(JSON.stringify({traceparent:r}));return me({name:"parseDmmf",enabled:this.config.tracingConfig.enabled,internal:!0},()=>JSON.parse(n))}version(){return this.versionInfo=this.library?.version(),this.versionInfo?.version??"unknown"}debugPanic(r){return this.library?.debugPanic(r)}async request(r,{traceparent:n,interactiveTransaction:i}){Ue(`sending request, this.libraryStarted: ${this.libraryStarted}`);let o=JSON.stringify({traceparent:n}),s=JSON.stringify(r);try{await this.start(),this.executingQueryPromise=this.engine?.query(s,o,i?.id),this.lastQuery=s;let l=this.parseEngineResponse(await this.executingQueryPromise);if(l.errors)throw l.errors.length===1?this.buildQueryError(l.errors[0]):new Z(JSON.stringify(l.errors),{clientVersion:this.config.clientVersion});if(this.loggerRustPanic)throw this.loggerRustPanic;return{data:l,elapsed:0}}catch(l){if(l instanceof G)throw l;if(l.code==="GenericFailure"&&l.message?.startsWith("PANIC:"))throw new fe(this.getErrorMessageWithLink(l.message),this.config.clientVersion);let u=this.parseRequestError(l.message);throw typeof u=="string"?l:new Z(`${u.message}
2023-05-26T08:28:24Z   [info]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     ^
2023-05-26T08:28:24Z   [info]Error: Can't reach database server at `bog.vanguard-adf5-db.flycast`:`5432`
2023-05-26T08:28:24Z   [info]Please make sure your database server is running at `bog.vanguard-adf5-db.flycast`:`5432`.
2023-05-26T08:28:24Z   [info]    at startFn (/myapp/node_modules/@prisma/client/runtime/library.js:101:2598)
2023-05-26T08:28:24Z   [info]Starting clean up.

I’ve tried creating a new project from scratch of Remix with fly deployment option and it gives me error so I’m guessing it’s not Remix or even Prisma error. I even changed region so it makes me think it’s maybe some config stuff. If it helps, this is the fly.toml

app = "vanguard-adf5"
kill_signal = "SIGINT"
kill_timeout = 5
processes = [ ]

[env]
PORT = "8080"
METRICS_PORT = "8081"

[metrics]
port = 8_081
path = "/metrics"

[deploy]
release_command = "bash ./scripts/migrate.sh"

[experimental]
allowed_public_ports = [ ]
auto_rollback = true

[[services]]
internal_port = 8_080
processes = [ "app" ]
protocol = "tcp"
script_checks = [ ]

  [services.concurrency]
  hard_limit = 25
  soft_limit = 20
  type = "connections"

  [[services.ports]]
  handlers = [ "http" ]
  port = 80
  force_https = true

  [[services.ports]]
  handlers = [ "tls", "http" ]
  port = 443

  [[services.tcp_checks]]
  grace_period = "1s"
  interval = "15s"
  restart_limit = 0
  timeout = "2s"

  [[services.http_checks]]
  interval = "10s"
  grace_period = "5s"
  method = "get"
  path = "/healthcheck"
  protocol = "http"
  timeout = "2s"
  tls_skip_verify = false
  headers = { }

I can connect from my PC to the postgres instance or with prisma studio and see all the tables from my prisma schema and add recorda so I know in fact that’s running. I’ve tried everything but I can’t get it to work. I’d appreciate some help.

Also, if it’s worth, I’m adding the Dockerfile

# base node image
FROM node:16-bullseye-slim as base

# set for base and all layer that inherit from it
ENV NODE_ENV production

# Install openssl for Prisma
RUN apt-get update && apt-get install -y openssl

# Install all node_modules, including dev dependencies
FROM base as deps

WORKDIR /myapp

ADD package.json package-lock.json .npmrc ./
RUN npm install --include=dev

# Setup production node_modules
FROM base as production-deps

WORKDIR /myapp

COPY --from=deps /myapp/node_modules /myapp/node_modules
ADD package.json package-lock.json .npmrc ./
RUN npm prune --omit=dev

# Build the app
FROM base as build

WORKDIR /myapp

COPY --from=deps /myapp/node_modules /myapp/node_modules

ADD prisma .
RUN npx prisma generate

ADD . .
RUN npm run build

# Finally, build the production image with minimal footprint
FROM base

WORKDIR /myapp

COPY --from=production-deps /myapp/node_modules /myapp/node_modules
COPY --from=build /myapp/node_modules/.prisma /myapp/node_modules/.prisma

COPY --from=build /myapp/build /myapp/build
COPY --from=build /myapp/public /myapp/public
ADD . .

CMD ["npm", "start"]

Hi @Eiley

There was a bug is blues-stack that got fixed recently: fix: don't add `FLY_REGION` prefix when using recent `flyctl` version by benwaffle · Pull Request #187 · remix-run/blues-stack · GitHub

The DB address needs to be vanguard-adf5-db.flycast instead of bog.vanguard-adf5-db.flycast

How can i avoid that? I don’t set up the secret myself, i just run fly postgres attach --app vanguard-adf5 vanguard-adf5-db and it does it for me. Should i set it up manually?

Also, i don’t know what I’m doing wrong but when i put the string connection in my local secrets and run npm run dev, it gives me the same error but I’m not using the bog. at the beginning. It’s worth mentioning that I’m using the host name that ends with fly.dev

Just fixed it modifying the db.server.ts file from the PR that Pavel sent me.

if (!isLocalHost) {
    databaseUrl.host = `${FLY_REGION}.${databaseUrl.host}`;
    if (!isReadReplicaRegion) {
      // 5433 is the read-replica port
      databaseUrl.port = "5433";
    }
  }

Converted it to

if (!isLocalHost) {
    databaseUrl.host = `${databaseUrl.host}`;
    if (!isReadReplicaRegion) {
      // 5433 is the read-replica port
      databaseUrl.port = "5433";
    }
  }

Thank you so much! @pavel