如何使用 laradock 配置 laravel 和 postgres?无法连接到服务器:端口 5432 上的连接被拒绝

how to configure laravel with postgres using laradock? could not connect to server: Connection refused on port 5432

我正在开始一个新的 laravel 项目,并尝试使用 laradock postgres 容器将其配置为 运行。我在端口 5432 中有 postgres 容器 运行ning 但是当我 运行:

docker-compose exec workspace bash
php artisan migrate

我收到错误:

PDOException::("SQLSTATE[08006] [7] could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432?")

Seens Laravel 找不到 postgres。我一定是漏掉了什么。

要在 my-laravel-app/laradock/ 中 运行 构建容器:

docker-compose up -d nginx postgres

而且我可以检查一切是否正常,运行宁可精细打字 docker-compose ps:

           Name                          Command              State                     Ports
---------------------------------------------------------------------------------------------------------------
laradock_docker-in-docker_1   dockerd-entrypoint.sh           Up       2375/tcp
laradock_mysql_1              docker-entrypoint.sh mysqld     Exit 0
laradock_nginx_1              /bin/bash /opt/startup.sh       Up       0.0.0.0:443->443/tcp, 0.0.0.0:80->80/tcp
laradock_php-fpm_1            docker-php-entrypoint php-fpm   Up       9000/tcp
laradock_postgres_1           docker-entrypoint.sh postgres   Up       0.0.0.0:5432->5432/tcp
laradock_workspace_1          /sbin/my_init                   Up       0.0.0.0:2222->22/tcp

我输入了 lsof -Pan -i tcp,我可以看到 postgres 容器 运行ning 在端口 5432:

com.docke 693 marcelo   18u  IPv4 0x483d469672d04c2b      0t0  TCP *:5432 (LISTEN)
com.docke 693 marcelo   21u  IPv6 0x483d46967542a923      0t0  TCP [::1]:5432 (LISTEN)

我的laradock/.env:

### POSTGRES ##############################################

POSTGRES_DB=sicob_dev
POSTGRES_USER=postgres
POSTGRES_PASSWORD=secret
POSTGRES_PORT=5432
POSTGRES_ENTRYPOINT_INITDB=./postgres/docker-entrypoint-initdb.d

我的.env:

DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5432
DB_DATABASE=sicob_database
DB_USERNAME=postgres
DB_PASSWORD=secret

我的config/database.php:

# ...
'default' => env('DB_CONNECTION', 'pgsql'),

'connections' => [
    # ...
    'pgsql' => [
        'driver' => 'pgsql',
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '5432'),
        'database' => env('DB_DATABASE', 'sicob_dev'),
        'username' => env('DB_USERNAME', 'postgres'),
        'password' => env('DB_PASSWORD', 'secret'),
        'charset' => 'utf8',
        'prefix' => '',
        'prefix_indexes' => true,
        'schema' => 'public',
        'sslmode' => 'prefer',
    ],
 ],
 # ...

对于未来的搜索者:您的项目 .env 应该如下所示:

DB_CONNECTION=pgsql
DB_HOST=postgres *(no need to use the full container name, as Laradock exposes 'postgres' as the volume name (check docker-compose.yml))*
DB_PORT=5432
DB_DATABASE=mydb (postgress database you want to connect)
DB_USERNAME=root (postgres user)
DB_PASSWORD=root (postgres password)