I have a yii2 app dockerized with the docker-compose.yml file. And I try to connect the docker container with my localhost db.
So this is the docker-compose.yml file:
version: "3.8"
services:
php:
image: yiisoftware/yii2-php:8.2-apache
container_name: yii2
volumes:
- ~/.composer-docker/cache:/root/.composer/cache:delegated
- ./:/app:delegated
ports:
- "8000:80"
env_file: ./env/dev/.env
and the db.php file:
<?php
// phpcs:ignoreFile
$config = [
'class' => 'yiidbConnection',
'dsn' => 'pgsql:host=' . $_ENV['DB_HOST'] . ';dbname=' . $_ENV['DB_NAME'] . $_ENV['DB_PORT'],
'username' => $_ENV['DB_USER'],
'password' => $_ENV['DB_PASSWORD'],
'charset' => $_ENV['DB_CHARSET'],
];
return $config;
And in the root folder I have a folder name: env/dev/.env file with content:
YII_DEBUG=1
YII_ENV=dev
DB_HOST=localhost
DB_NAME=name
DB_USER=postgres
DB_PASSWORD=pass
DB_CHARSET=utf8
DB_PORT=5432
# * or ip1,ip2,ip3
ALLOWED_DEBUG_IPS=*
So the docker container is running. But if I try to connect to the database with an api call:
I get this error:
"name": "Database Exception",
"message": "SQLSTATE[08006] [7] connection to server at "localhost" (::1), port 5432 failed: Connection refusedntIs the server running on that host and accepting TCP/IP connections?nconnection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refusedntIs the server running on that host and accepting TCP/IP connections?",
"code": 7,
"type": "yii\db\Exception",
"file": "/app/vendor/yiisoft/yii2/db/Connection.php",
"line": 648,
if I omit in de docker-compose.yml file the env_file propertie it works – I can connect to the postgres database.
And of course I searched for this error. For example I found this link:
/questions/45637206/docker-is-the-server-running-on-host-localhost-1-and-accepting-tcp-ip-con
Question: How to connect to the localdb with docker-compose.yml file?