Reputation: 2483
SOLUTION: docker inspect | grep IP get the postgres running container's ip and update your env DB_HOST and DB_PORT with container's ip and port respectively.
UPDATE: Writing postgres to DB_HOST is best practice due to ip address may change.
I've been searching for a day to connect database from docker container to my Laravel app, but whatever I've tried, even though I can connect it via Postico I cannot migrate my database. I get the 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 3306?
My Dockerfile:
FROM php:7.1.3-fpm-alpine
RUN apk update && apk add build-base
RUN apk add postgresql postgresql-dev \
&& docker-php-ext-configure pgsql -with-pgsql=/usr/local/pgsql \
&& docker-php-ext-install pdo pdo_pgsql pgsql
RUN apk add zlib-dev git zip \
&& docker-php-ext-install zip
RUN curl -sS https://getcomposer.org/installer | php \
&& mv composer.phar /usr/local/bin/ \
&& ln -s /usr/local/bin/composer.phar /usr/local/bin/composer
COPY . /app
WORKDIR /app
RUN composer install --prefer-source --no-interaction
ENV PATH="~/.composer/vendor/bin:./vendor/bin:${PATH}"
My docker-compose file:
version: '2'
services:
nginx:
image: nginx:1.11.10-alpine
ports:
- 3000:80
volumes:
- ./nginx.conf:/etc/nginx/conf.d/default.conf
depends_on:
- api
api:
build: .
ports:
- 9000:9000
volumes:
- .:/app
- /app/vendor
depends_on:
- postgres
environment:
DATABASE_URL: postgres://foodorder@postgres/foodorder
postgres:
image: postgres:latest
environment:
POSTGRES_USER: foodorder
POSTGRES_DB: foodorder
POSTGRES_PASSWORD: 123123
ports:
- 3306:5432
My env file:
DB_CONNECTION = "pgsql"
DATABASE_CONNECTIONS_MASTER_PGSQL_HOST="localhost"
DATABASE_CONNECTIONS_MASTER_PGSQL_SCHEMA="foodorder"
DATABASE_CONNECTIONS_MASTER_PGSQL_DATABASE="foodorder"
DATABASE_CONNECTIONS_MASTER_PGSQL_PORT="3306"
DATABASE_CONNECTIONS_MASTER_PGSQL_USERNAME="foodorder"
DATABASE_CONNECTIONS_MASTER_PGSQL_PASSWORD="123123"
And finally, in my database.php,
'default' => env('DB_CONNECTION', 'pgsql'),
'pgsql' => [
'driver' => 'pgsql',
'host' => env('DATABASE_CONNECTIONS_MASTER_PGSQL_HOST'),
'port' => env('DATABASE_CONNECTIONS_MASTER_PGSQL_PORT'),
'database' => env('DATABASE_CONNECTIONS_MASTER_PGSQL_DATABASE'),
'username' => env('DATABASE_CONNECTIONS_MASTER_PGSQL_USERNAME'),
'password' => env('DATABASE_CONNECTIONS_MASTER_PGSQL_PASSWORD'),
'charset' => 'utf8',
'prefix' => '',
'schema' => env('DATABASE_CONNECTIONS_MASTER_PGSQL_SCHEMA'),
'sslmode' => 'prefer',
],
Upvotes: 2
Views: 3215
Reputation:
Check that the database user has access on both localhost
and 127.0.0.1
. It sounds like you're trying to connect to localhost
but access has only been granted for 127.0.0.1
, or vice versa.
Upvotes: 1