Reputation: 1575
I have an issue to connect to Postgres container from Laravel.
They are on the same host created as separated Docker containers.
Here is YML:
version: '3'
services:
# The Application
app:
env_file: .env
container_name: "laravel"
build:
context: ./
dockerfile: app.dockerfile
working_dir: /var/www
volumes:
- ./:/var/www
environment:
- "DB_PORT=${DB_PORT}"
- "DB_HOST=${DB_HOST}"
- "DB_USER=${DB_USER}"
- "DB_PASS=${DB_PASS}"
- "DB_DATABASE=${DB_DATABASE}"
- "DB_SCHEMA=${DB_SCHEMA}"
restart: 'always'
# The Web Server
web:
container_name: "nginx"
build:
context: ./
dockerfile: web.dockerfile
working_dir: /var/www
volumes:
- ./:/app
ports:
- 8080:80
restart: 'always'
# The Database
pgsql:
image: postgres:10.1
container_name: "baza"
environment:
- 'DB_USER=${DB_USER}'
- 'DB_PASS=${DB_PASS}'
volumes:
- '${DB_VOLUME_LOCATION}:/var/lib/postgresql/data'
ports:
- "${DB_PORT}:${PGSQL_CONTAINER_PORT}"
restart: 'always'
Here .env
variables for Laravel 5:
# postgres
DB_HOST=localhost
DB_PORT=6666
DB_DATABASE=postgres
DB_USER=postgres
DB_PASS=postgres
PGSQL_CONTAINER_PORT=5432
docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
2b8e667bcb08 postgres:10.1 "docker-entrypoint.s…" 4 seconds ago Up 1 second 0.0.0.0:6666->5432/tcp baza
58f1573bf016 laraveldockerized_app "php-fpm" 4 seconds ago Up 2 seconds 9000/tcp laravel
8a24bd5073a8 laraveldockerized_web "nginx -g 'daemon of…" 4 seconds ago Up 3 seconds 443/tcp, 0.0.0.0:8080->80/tcp nginx
I'm able to connect to postgres from outside using DataGrip and:
But when I try to connect with Laravel I'm getting following error:
SQLSTATE[08006] [7] could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 6666? could not connect to server: Cannot assign requested address Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 6666? (SQL: select * from "dokuments")
I tried to change DB_HOST in .env to:
but nothing of above works.
Upvotes: 3
Views: 8676
Reputation: 66
You should get the ip of Postgres container by using following command.
docker inspect -f '{{.Name}} - {{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $(docker ps -aq)
Then Replace the Ip of Postgres container in your Laravel .env as host.
Upvotes: 3
Reputation: 1651
add change name of databae
environment:
- 'DB_USER=${DB_USER}'
- 'DB_PASS=${DB_PASS}'
# - 'DB_NAME=${DB_NAME}'
-------------------------------
DB_HOST=pgsql
DB_PORT=5432
DB_DATABASE=postgres
DB_USER=postgres
DB_PASS=postgres
Upvotes: 2