fix: rewrite localhost DATABASE_URL to host.docker.internal in Docker
Containers cannot reach Postgres on the VPS host via localhost; auto-rewrite when running inside Docker and improve migrate error hints. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
6382a28c7b
commit
9e75ec0e35
@ -16,13 +16,38 @@ const repoRoot = path.resolve(__dirname, '..', '..', '..');
|
||||
dotenv.config({ path: envPath });
|
||||
});
|
||||
|
||||
/** Inside Docker, localhost is the container — rewrite to reach Postgres on the host. */
|
||||
function resolveDatabaseUrl(raw: string): string {
|
||||
const trimmed = raw.trim();
|
||||
try {
|
||||
const parsed = new URL(trimmed);
|
||||
const isLocalHost =
|
||||
parsed.hostname === 'localhost' ||
|
||||
parsed.hostname === '127.0.0.1' ||
|
||||
parsed.hostname === '::1' ||
|
||||
parsed.hostname === '[::1]';
|
||||
if (isLocalHost && fs.existsSync('/.dockerenv')) {
|
||||
const dockerHost = process.env.DATABASE_DOCKER_HOST || 'host.docker.internal';
|
||||
console.warn(
|
||||
`[db] DATABASE_URL host "${parsed.hostname}" does not work inside Docker; using "${dockerHost}". ` +
|
||||
'Set DATABASE_URL=@host.docker.internal in .env to silence this.'
|
||||
);
|
||||
parsed.hostname = dockerHost;
|
||||
return parsed.toString();
|
||||
}
|
||||
} catch {
|
||||
// keep raw URL for connectionString fallback
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds pg Pool configuration from DATABASE_URL, preferring DATABASE_PASSWORD when set.
|
||||
* @returns Parsed host/port config or a raw connectionString fallback
|
||||
* @throws When DATABASE_URL is missing or empty
|
||||
*/
|
||||
function getPoolConfig(): { connectionString: string } | { host: string; port: number; database: string; user: string; password: string; max?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number } {
|
||||
const url = process.env.DATABASE_URL;
|
||||
const url = resolveDatabaseUrl(process.env.DATABASE_URL ?? '');
|
||||
if (!url || url.trim() === '') {
|
||||
throw new Error(
|
||||
'DATABASE_URL is not set. Create a .env file with DATABASE_URL=postgresql://user:password@localhost:5432/crypto_wallet'
|
||||
|
||||
@ -15,6 +15,14 @@ async function migrate() {
|
||||
console.log('Migrations completed successfully.');
|
||||
process.exit(0);
|
||||
} catch (err) {
|
||||
const code = err && typeof err === 'object' && 'code' in err ? String((err as { code?: string }).code) : '';
|
||||
if (code === 'ECONNREFUSED') {
|
||||
console.error(
|
||||
'Migration failed: cannot reach PostgreSQL (ECONNREFUSED).\n' +
|
||||
' From Docker containers use host.docker.internal in DATABASE_URL, not localhost.\n' +
|
||||
' Example: DATABASE_URL=postgresql://postgres:PASSWORD@host.docker.internal:5432/games_platform_db'
|
||||
);
|
||||
}
|
||||
console.error('Migration failed:', err);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user