Cannot not connect to database server within docker-compose (php and MariaDB) - php

I've built a docker-compose file that creates 2 services (PHP and MariaDB). Somehow I cannot connect to the database from the PHP service: Within the PHP service, a Laravel-app is running.
The error message (redirect is a table within the database):
SQLSTATE[HY000] [2002] Connection refused (SQL: select * from redirects)
All env-variables should be correct.
Here is my docker-compose.yml:
version: "3.7"
services:
faaren_backend:
image: php:alpine
container_name: FAA-Backend
volumes:
- "./:/faaren_backend"
working_dir: /faaren_backend
command: "php artisan serve --host=0.0.0.0 --port=8000"
ports:
- 8000:8000
build:
context: docker/php
dockerfile: dev.Dockerfile
faaren_database:
image: mariadb
container_name: FAA-Database
ports:
- "3306:3306"
environment:
MYSQL_ALLOW_EMPTY_PASSWORD: 1
MYSQL_DATABASE: ${DB_DATABASE}
volumes:
- "faa-db-data:/var/lib/mysql/data"
volumes:
faa-db-data: {}
My dev.Dockerfile
FROM php:7.3-fpm
RUN apt-get update
RUN apt-get update && apt-get install -y libzip-dev \
&& docker-php-ext-install zip
RUN apt-get update && apt-get install -y libmagickwand-dev --no-install-recommends && rm -rf /var/lib/apt/lists/*
RUN pecl install imagick
RUN docker-php-ext-enable imagick
RUN apt-get install $PHPIZE_DEPS && \
pecl install xdebug && docker-php-ext-enable xdebug && \
docker-php-ext-install pdo_mysql pcntl
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
VOLUME /faaren_backend
And finally my .env-file:
DB_CONNECTION=mysql
DB_HOST=faaren_backend
DB_PORT=3306
DB_DATABASE=faaren_db
DB_USERNAME=root
DB_PASSWORD=
Mostly I've followed this tutorial: https://medium.com/swlh/laravel-with-docker-compose-de2190569084

You need change your docker database host:
DB_CONNECTION=mysql
DB_HOST=faaren_database <-- edit
DB_PORT=3306
DB_DATABASE=faaren_db
DB_USERNAME=root
DB_PASSWORD=
And in docker-compose.yml faaren_backend section add:
depends_on:
- faaren_database
Hope it's help.

Looks like you deal with a race condition. You need to use depends_on directive to control startup order and use wait script to make sure that service ready to accept connections:
version: "3.7"
services:
faaren_backend:
image: php:alpine
container_name: FAA-Backend
volumes:
- "./:/faaren_backend"
working_dir: /faaren_backend
command: entrypoint.sh
ports:
- 8000:8000
depends_on:
- faaren_database
build:
context: docker/php
dockerfile: dev.Dockerfile
faaren_database:
image: mariadb
container_name: FAA-Database
ports:
- "3306:3306"
environment:
MYSQL_ALLOW_EMPTY_PASSWORD: 1
MYSQL_DATABASE: ${DB_DATABASE}
volumes:
- "faa-db-data:/var/lib/mysql/data"
volumes:
faa-db-data: {}
There are a bunch of ways to check service availability, sometimes wait-for-it can be really handy. In the example below used netcat(you need to install it into the container).
Also, it'a good idea to put a script into a separated file:
entrypoint.sh
#!/usr/bin/env bash
until nc -w 1 -z faaren_database 3306; do
>&2 echo "Mysql is unavailable - sleeping"
sleep 1
done
sleep 10
>&2 echo "Mysql is up - executing command"
php artisan serve --host=0.0.0.0 --port=8000
UPDATE: Specify correct DB_HOST how Dmitry suggested as well.

Related

PHP Pest (with Laravel) tests running very slow in OSX Docker

I was developing an app locally using Laravel. For testing I was using Pest and tests were running fast, really fast. That was until I decided to Dockerize my app, now tests are running pretty slow.
What it used to run in 3 seconds now it's running in over a minute.
Here's my Dockerfile:
FROM php:8.1.12-fpm
ARG uid=1000
ARG user=macgiver
RUN apt-get update && apt-get install -y \
git \
curl \
libpng-dev \
libonig-dev \
libxml2-dev \
zip \
unzip
# Install and enable xDebug
RUN pecl install xdebug \
&& docker-php-ext-enable xdebug
RUN apt-get clean && rm -rf /var/lib/apt/lists/*
# Install php modules required by laravel.
RUN docker-php-ext-install pdo_mysql mbstring exif pcntl bcmath gd
# Create system user to run Composer and Artisan commands.
RUN useradd -G www-data,root -u $uid -d /home/$user $user
RUN mkdir -p /home/$user/.composer && \
chown -R $user:$user /home/$user
# Install composer
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer
# Set working directory
WORKDIR /var/www
USER $user
and this is my docker-compose:
version: "3.9"
services:
app:
build:
context: ./
dockerfile: Dockerfile
image: dmc
container_name: dmc-app
restart: unless-stopped
working_dir: /var/www/
depends_on:
- db
- nginx
volumes:
- ./:/var/www/
- ./docker/php/conf.d/xdebug.ini:/usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini
- ./docker/php/conf.d/error_reporting.ini:/usr/local/etc/php/conf.d/error_reporting.ini
expose:
- "9003"
networks:
- dmc-net
nginx:
image: nginx:1.23.2-alpine
container_name: dmc-nginx
restart: unless-stopped
ports:
- "8000:80"
volumes:
- ./:/var/www
- ./docker-compose/nginx:/etc/nginx/conf.d
networks:
- dmc-net
db:
image: mysql:8.0.31
container_name: dmc-db
restart: unless-stopped
# using 3307 on the host machine to avoid collisions in case there's a local MySQL instance installed already.
ports:
- "3307:3306"
# use the variables declared in .env file
environment:
MYSQL_HOST: ${DB_HOST}
MYSQL_DATABASE: ${DB_DATABASE}
MYSQL_PASSWORD: ${DB_PASSWORD}
MYSQL_ROOT_PASSWORD: abcd1234
MYSQL_USER: ${DB_USERNAME}
SERVICE_TAGS: dev
SERVICE_NAME: mysql
volumes:
- ./docker-compose/mysql:/docker-entrypoint-initdb.d
- mysql-data:/var/lib/mysql
networks:
- dmc-net
networks:
dmc-net:
driver: bridge
volumes:
mysql-data:
Any ideas?

How to solve Laravel cant connect with mysql through docker

Im trying to deploy my laravel app using docker. Then I created docker-compose.yml file and Dockerfile like below.
docker-compose.yml
version: "3.7"
services:
app:
build:
args:
user: sammy
uid: 1000
context: ./
dockerfile: Dockerfile
image: travellist
container_name: travellist-app
restart: unless-stopped
working_dir: /var/www/
volumes:
- ./:/var/www
networks:
- travellist
db:
image: mysql:8.0
container_name: travellist-db
restart: unless-stopped
environment:
MYSQL_DATABASE: '${DB_DATABASE}'
MYSQL_ROOT_PASSWORD: '${DB_PASSWORD}'
MYSQL_PASSWORD: '${DB_PASSWORD}'
MYSQL_ALLOW_EMPTY_PASSWORD: 1
SERVICE_TAGS: dev
SERVICE_NAME: mysql
volumes:
- ./docker-compose/mysql:/docker-entrypoint-initdb.d
networks:
- travellist
nginx:
image: nginx:alpine
container_name: travellist-nginx
restart: unless-stopped
ports:
- 8000:80
volumes:
- ./:/var/www
- ./docker-compose/nginx:/etc/nginx/conf.d/
networks:
- travellist
networks:
travellist:
driver: bridge
Dockerfile
FROM php:7.4-fpm
# Arguments defined in docker-compose.yml
ARG user
ARG uid
# Install system dependencies
RUN apt-get update && apt-get install -y \
git \
curl \
libpng-dev \
libonig-dev \
libxml2-dev \
zip \
unzip
# Clear cache
RUN apt-get clean && rm -rf /var/lib/apt/lists/*
# Install PHP extensions
RUN docker-php-ext-install pdo_mysql mbstring exif pcntl bcmath gd
# Get latest Composer
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer
# Create system user to run Composer and Artisan Commands
RUN useradd -G www-data,root -u $uid -d /home/$user $user
RUN mkdir -p /home/$user/.composer && \
chown -R $user:$user /home/$user
# Set working directory
WORKDIR /var/www
USER $user
And when I try docker-compose up, all the containers run with a any error. And also when I run docker-compose ps, it shows like this,
Name Command State Ports
------------------------------------------------------------------------------------------------
travellist-app docker-php-entrypoint php-fpm Up 9000/tcp
travellist-db docker-entrypoint.sh mysqld Up 3306/tcp, 33060/tcp
travellist-nginx /docker-entrypoint.sh ngin ... Up 0.0.0.0:8000->80/tcp,:::8000->80/tcp
But, when laravel application, tries to connect with mysql, it doesnt happens. And even I cant connect using TablePlus, it shows this.
Lost connection to MySQL server at 'waiting for initial communication packet', system error: 10060
And sometimes, I get like below,
SQLSTATE[HY000] [1045] Access denied for user 'root'#'192.168.48.3' (using password: YES)
How can I fix this ??
Since you're networking the services, you only need to expose the port 3306/tcp (this is the default port mysql serves). This makes it inaccessible from 0.0.0.0 but accessible from your nginx and app container.
I have also added the correct volume to persist data (which I am assuming is what you're trying to do). I moved mysql to latest - feel free to rollback or stick to 8 if you really? need too.
db:
image: 'mysql:latest'
restart: 'unless-stopped'
expose:
- '3306'
environment:
- 'MYSQL_RANDOM_ROOT_PASSWORD=true'
- 'MYSQL_DATABASE=${DB_DATABASE}'
- 'MYSQL_USER=${DB_USER}'
- 'MYSQL_PASSWORD=${DB_PASSWORD}'
- 'MYSQL_ALLOW_EMPTY_PASSWORD=true'
volumes:
- 'laravel-database:/var/lib/mysql/'
networks:
- 'travellist'
volumes:
laravel-database:
Further reading can be found on the Docker hub under mysql.
Inside your Laravel .env, you should connect to the container via its DNS.
DB_HOST=db
If you want to connect to this container externally, you'll need to bind the port to the server. Do so by replacing expose with the following:
ports:
- '3306:3306'

How to solve Laravel with sail "start-container": executable file not found

Im trying to deploy my laravel app using docker with laravel sail. Then I created docker-compose.yml file and Dockerfile like below.
docker-compose.yml
# For more information: https://laravel.com/docs/sail
version: '3'
services:
laravel.test:
build:
context: ./vendor/laravel/sail/runtimes/8.1
dockerfile: Dockerfile
args:
WWWGROUP: '${WWWGROUP}'
image: sail-8.1/app
extra_hosts:
- 'host.docker.internal:host-gateway'
ports:
- '${APP_PORT:-80}:80'
- '${HMR_PORT:-8080}:8080'
environment:
WWWUSER: '${WWWUSER}'
LARAVEL_SAIL: 1
XDEBUG_MODE: '${SAIL_XDEBUG_MODE:-off}'
XDEBUG_CONFIG: '${SAIL_XDEBUG_CONFIG:-client_host=host.docker.internal}'
volumes:
- '.:/var/www/html'
networks:
- sail
depends_on:
- mysql
mysql:
image: 'mysql/mysql-server:8.0'
ports:
- '${FORWARD_DB_PORT:-3306}:3306'
environment:
MYSQL_ROOT_PASSWORD: '${DB_PASSWORD}'
MYSQL_ROOT_HOST: '${DB_HOST}'
MYSQL_DATABASE: '${DB_DATABASE}'
MYSQL_USER: '${DB_USERNAME}'
MYSQL_PASSWORD: '${DB_PASSWORD}'
MYSQL_ALLOW_EMPTY_PASSWORD: 1
volumes:
- 'sail-mysql:/var/lib/mysql'
- './vendor/laravel/sail/database/mysql/create-testing-database.sh:/docker-entrypoint-initdb.d/10-create-testing-database.sh'
networks:
- sail
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-p${DB_PASSWORD}"]
retries: 3
timeout: 5s
networks:
sail:
driver: bridge
volumes:
sail-mysql:
driver: local
Dockerfile
FROM php:7.4-fpm
# Arguments defined in docker-compose.yml
ARG user
ARG uid
# Install system dependencies
RUN apt-get update && apt-get install -y \
git \
curl \
libpng-dev \
libonig-dev \
libxml2-dev \
zip \
unzip
# Clear cache
RUN apt-get clean && rm -rf /var/lib/apt/lists/*
# Install PHP extensions
RUN docker-php-ext-install pdo_mysql mbstring exif pcntl bcmath gd
# Get latest Composer
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer
# Create system user to run Composer and Artisan Commands
RUN useradd -G www-data,root -u $uid -d /home/$user $user
RUN mkdir -p /home/$user/.composer && \
chown -R $user:$user /home/$user
# Set working directory
WORKDIR /var/www
USER $user
But, when I try to run docker-compose up, I get this below error. I have been trying this for now 2 days. I installed sail properly.
ERROR: for 7fd8f64d5ed1_proj_laravel.test_1 Cannot start service laravel.test: OCI runtime create failed: container_linux.go:380: starting container process caused: exec: "start-container": executable file not found in $PATH: unknown
ERROR: for laravel.test Cannot start service laravel.test: OCI runtime create failed: container_linux.go:380: starting container process caused: exec: "start-container": executable file not found in $PATH: unknown
ERROR: Encountered errors while bringing up the project.
Here is my .env
DB_CONNECTION=mysql
DB_HOST=db
DB_PORT=3306
DB_DATABASE=here_goes_db_name
DB_USERNAME=sail
DB_PASSWORD=tyutyu
How can I fix this ??
The default docker container should copy a bash script called start-container from your project root to the container during build. If you for example removed it from your project root, it can not copy it and run it later. So the steps to fix it are:
Restore the start-container script to your project root, you can find it here
Rebuild the image with docker-compose build
And everything should work again. I suspect step 2 is even optional as the entire project gets mounted as a volume.

Problem in docker images it is not starting

I made in my project nginx, mysql, phpMyadmin, encore and php images.
Just php and encore dosent work, they are successed built, but the are with red color.
The directory of the project:
that is my docker-compose.yml:
version: '3.3'
services:
database:
container_name: database
image: mysql:8.0
restart: always
command: --default-authentication-plugin=mysql_native_password
environment:
MYSQL_ROOT_PASSWORD: alsbls
MYSQL_DATABASE: infoSystem
MYSQL_USER: alsbls
MYSQL_PASSWORD: alsbls
ports:
- '4306:3306'
volumes:
- ./mysql:/var/lib/mysql
php:
container_name: php
restart: always
build:
context: ./php
ports:
- '9000:9000'
volumes:
- ./app:/var/www/infoSystem
depends_on:
- database
nginx:
container_name: nginx
image: nginx:stable-alpine
restart: always
ports:
- '8080:80'
volumes:
- ./app:/var/www/infoSystem
- ./nginx/default.conf:/etc/nginx/conf.d/default.conf
depends_on:
- php
- database
phpmyadmin:
image: phpmyadmin/phpmyadmin:latest
restart: always
environment:
PMA_HOST: database
PMA_USER: alsbls_root
PMA_PASSWORD: alsbls_root
ports:
- "8081:81"
encore:
container_name: encore
restart: always
build:
context: ./php
volumes:
- ./:/var/www/html
That is my Dockerfile:
FROM php:8.0-fpm
RUN apt update \
&& apt install -y zlib1g-dev g++ git libicu-dev zip libzip-dev zip \
&& docker-php-ext-install intl opcache pdo pdo_mysql \
&& pecl install apcu \
&& docker-php-ext-enable apcu \
&& docker-php-ext-configure zip \
&& docker-php-ext-install zip
WORKDIR /var/www/infoSystem
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
RUN curl -sS https://get.symfony.com/cli/installer | bash
RUN mv /root/.symfony/bin/symfony /usr/local/bin/symfony
RUN git config --global user.email "devojob97#gmail.com" \
&& git config --global user.name "alsbls"
FROM node:12.10.0
WORKDIR /var/www/html
COPY entrypoint.sh /usr/local/bin/entrypoint
RUN ["chmod", "+x", "/usr/local/bin/entrypoint"]
ENTRYPOINT ["/usr/local/bin/entrypoint"]
USER node
that is the entrypoint.sh in the same dir of Dockerfile:
#!/bin/bash
# Prevent container from shutting down
while true; do sleep 3600; done
I didn't receive any error message on the terminal.
Maybe some one now the issues.
Best regards
I saw in the docker log of the encore image the following error:
standard_init_linux.go:190: exec user process caused "no such file or directory" - Docker
And then I tried to use the following command outside of the container:
dos2unix your-file.sh
This tutorial helped me to solve it:

'mysql: not found', trying to connect a laravel, mysql and nginx in docker container

Ubuntu 20.04
Docker version 19.03.14
docker-compose version 1.25.0
I'm trying to figure out why i'm getting an error related to mysql. The steps i did:
Clone my laravel project
docker-compose build
docker-compose up -d
docker-compose exec app php artisan key:generate
docker-compose exec app php artisan config:cache
docker-compose exec app php artisan migrate
in the last one i get the following error:
Migration table created successfully.
Loading stored database schema: /var/www/database/schema/mysql-schema.dump
Symfony\Component\Process\Exception\ProcessFailedException
The command "mysql --user="${:LARAVEL_LOAD_USER}" --password="${:LARAVEL_LOAD_PASSWORD}" --host="${:LARAVEL_LOAD_HOST}" --port="${:LARAVEL_LOAD_PORT}" --database="${:LARAVEL_LOAD_DATABASE}" < "${:LARAVEL_LOAD_PATH}"" failed.
Exit Code: 127(Command not found)
Working directory: /var/www
Output:
================
Error Output:
================
sh: 1: mysql: not found
at vendor/symfony/process/Process.php:257
253▕ */
254▕ public function mustRun(callable $callback = null, array $env = []): self
255▕ {
256▕ if (0 !== $this->run($callback, $env)) {
➜ 257▕ throw new ProcessFailedException($this);
258▕ }
259▕
260▕ return $this;
261▕ }
+19 vendor frames
20 artisan:37
Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
My files:
docker-compose.yml
version: '3.7'
services:
# The Application
app:
build:
context: .
dockerfile: docker-files/app.dockerfile
container_name: app
restart: unless-stopped
tty: true
environment:
SERVICE_NAME: app
SERVICE_TAGS: dev
volumes:
- ./:/var/www
- ./docker-files/php/local.ini:/usr/local/etc/php/conf.d/local.ini
env_file: '.env'
networks:
- app-network
# The Web Server
nginx:
container_name: nginx
restart: unless-stopped
tty: true
build:
context: .
dockerfile: docker-files/web.dockerfile
volumes:
- ./:/var/www
- ./docker-files/nginx/conf.d/:/etc/nginx/conf.d/
ports:
- "8990:80"
- "443:443"
networks:
- app-network
# The Database
db:
container_name: db
restart: unless-stopped
tty: true
image: mysql:5.7
volumes:
- dbdata:/var/lib/mysql/
- ./docker-files/mysql/my.cnf:/etc/mysql/my.cnf
environment:
MYSQL_DATABASE: maindbs
MYSQL_USER: root
MYSQL_PASSWORD: 123456
MYSQL_ROOT_PASSWORD: 123456
ports:
- "3306:3306"
networks:
- app-network
#Volumes
volumes:
dbdata:
driver: local
#Docker Networks
networks:
app-network:
driver: bridge
app.dockerfile
FROM php:7.4-fpm
COPY composer.lock composer.json /var/www/
COPY database /var/www/database
WORKDIR /var/www
# Install dependencies
RUN apt-get update && apt-get install -y \
build-essential \
libpng-dev \
libzip-dev \
libjpeg62-turbo-dev \
libfreetype6-dev \
locales \
zip \
jpegoptim optipng pngquant gifsicle \
vim \
unzip \
git \
curl
# Clear cache
RUN apt-get clean && rm -rf /var/lib/apt/lists/*
# Install extensions
RUN docker-php-ext-install pdo_mysql zip exif pcntl
RUN docker-php-ext-configure gd --with-freetype --with-jpeg
RUN docker-php-ext-install gd
# Install composer
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
# Copy application folder
COPY . /var/www
RUN chown -R www-data:www-data \
/var/www/storage \
/var/www/bootstrap/cache
RUN php artisan optimize
EXPOSE 9000
CMD ["php-fpm"]
web.dockerfile
FROM nginx:alpine
ADD docker-files/nginx/conf.d/app.conf /etc/nginx/conf.d/default.conf
COPY public /var/www/public
.env
DB_CONNECTION=mysql
DB_HOST=db
DB_PORT=3306
DB_DATABASE=maindbs
DB_USERNAME=root
DB_PASSWORD=123456
I can connect to laravel app using 127.0.0.1:8990
You don't have mysql client in the container that tries to execute mysql command.
Add mysql via the Dockerfile.
RUN apt-get update && apt-get install -y mysql-client && rm -rf /var/lib/apt

Categories