code-8
code-8

Reputation: 58632

Connection refused during migration inside the Docker in Laravel 5.8

I cannot seem to be able to make a migration while during my docker build.

I've tried

docker-compose.yml

version: '3'
services:
  portalmodules:
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - 8011:8000
    links:
      - database
  database:
    image: postgres:11.2
    ports:
    - "5432:5432"
    expose:
    - "5432"
    environment:
      - "POSTGRES_PASSWORD=12345"
      - "POSTGRES_USER=john"
      - "POSTGRES_DB=api"

Dockerfile

FROM composer:1.8.5 as build_stage

COPY . /src
WORKDIR /src
RUN composer install

FROM alpine:3.8
RUN apk --no-cache add \
php7 \
php7-mbstring \
php7-session \
php7-openssl \
php7-tokenizer \
php7-json \
php7-pdo \
php7-pdo_pgsql \
php7-pgsql

COPY --from=build_stage /src  /src
RUN ls -al
RUN set -x \
addgroup -g 82 -S www-data \
adduser -u 82 -D -S -G www-data www-data

WORKDIR /src
RUN ls -al
RUN chmod -R 777 storage
RUN chmod +x run.sh
RUN cp run.sh /tmp
ENTRYPOINT ["/tmp/run.sh"]

run.sh

#!/bin/sh

php artisan migrate:fresh --seed
php artisan serve --host=0.0.0.0

.env

APP_NAME=API
APP_ENV=local
APP_KEY=base64:Qa3U2oP5IQ93MGEJu61MrcQFRSsS5vQRWUrqYwIplEo=
APP_DEBUG=true
APP_URL=http://1.1.1.1
#---------------------------------------------- DATABASE
DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5432
DB_DATABASE=api
DB_USERNAME=john
DB_PASSWORD=12345

I've tried 3 diff values of DB_HOST localhost, 127.0.0.1, database

I kept getting

enter image description here

How would one go about and debug this further?

Upvotes: 0

Views: 807

Answers (1)

codestation
codestation

Reputation: 3498

The correct DB_HOST is database because every container has their own IP address so your database isn't located on the localhost of the application.

Note that you are starting the database and the laravel application at the same time so the database could be still initializing then the migration runs, and it fails to connect because is too early to connect to the database.

You have some options: wait until the database is ready before running the migration, retry the migration until it succeds or run the migration command from a different service using the same image as the laravel application (and setting restart: on-failure so the migration container restarts until it does a successful migration).

Upvotes: 1

Related Questions