You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel DB类无法通过Laradock+SSH隧道连接远程PostgreSQL

解决Laravel DB类无法通过SSH隧道连接远程PostgreSQL的问题

问题背景

  • 运行在Laradock Docker环境的Laravel项目,配置了两个PostgreSQL连接:本地容器库,以及通过postgres_tunnel容器的SSH隧道连接远程库。
  • 原生PHP函数pg_connect("host=postgres_tunnel dbname=remotedbname user=postgres port=9512")可成功建立连接,但调用Laravel的DB::connection('remotedb')->getPDO()时触发错误:

Doctrine/DBAL/Driver/PDO/Exception with message 'SQLSTATE[08006] [7] could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.9512"?'

问题原因

Laravel的PostgreSQL驱动默认优先尝试Unix套接字连接,若配置中未明确强制使用TCP连接,PDO会忽略host参数,转而查找本地Unix套接文件,而非通过TCP连接到postgres_tunnel容器的端口。

解决方案

修改Laravel项目的数据库配置,强制指定TCP连接方式:

步骤1:更新数据库配置文件

打开config/database.php,找到connections数组中的remotedb配置项,添加'unix_socket' => ''参数以禁用Unix套接字连接:

'remotedb' => [
    'driver' => 'pgsql',
    'host' => env('DB_REMOTE_HOST', 'postgres_tunnel'),
    'port' => env('DB_REMOTE_PORT', '9512'),
    'database' => env('DB_REMOTE_DATABASE', 'remotedbname'),
    'username' => env('DB_REMOTE_USERNAME', 'postgres'),
    'password' => env('DB_REMOTE_PASSWORD', ''),
    'charset' => 'utf8',
    'prefix' => '',
    'prefix_indexes' => true,
    'search_path' => 'public',
    'sslmode' => 'prefer',
    // 关键配置:强制使用TCP连接,禁用Unix套接字
    'unix_socket' => '',
],

步骤2:验证修复效果

  1. 清除Laravel配置缓存:
php artisan config:clear
  1. 进入tinker测试连接:
php artisan tinker
DB::connection('remotedb')->getPDO();

额外注意事项

  • 确认.env文件中对应远程数据库的环境变量配置正确:
DB_REMOTE_HOST=postgres_tunnel
DB_REMOTE_PORT=9512
DB_REMOTE_DATABASE=remotedbname
DB_REMOTE_USERNAME=postgres
DB_REMOTE_PASSWORD=your_actual_password
  • 原生pg_connect已验证postgres_tunnel容器的网络和端口映射正常,无需调整Docker配置。

内容的提问来源于stack exchange,提问作者alvaro.canepa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 05:03:08