Docker Compose php/mysql can't connect to mysql

180 views Asked by At

I try to create a simple multi container app according to the documentation with docker compose and deploy it on azure.

Folder structure:

-rootfolder:
   docker-compose.yml
   -webapp:
        index.php
        Dockerfile

./docker-compose.yml:

version: '3.3'

services:
  php:
    build:
      context: ./webapp
      dockerfile: Dockerfile
    image: php:7.2-apache
    volumes:
      - ./webapp:/var/www/html/
    depends_on:
      - db
    ports:
      - 80:80
    environment:
      DB_HOST: db:3306
      DB_USER: dbuser
      DB_PASSWORD: dbpassword
  db:
     image: mysql:5.7
     volumes:
       - db_data:/var/lib/mysql
     restart: always
     ports:
      - 3306:3306
     environment:
       MYSQL_ROOT_PASSWORD: somerootpw
       MYSQL_DATABASE: dbname
       MYSQL_USER: dbuser
       MYSQL_PASSWORD: dbpassword

volumes: 
  db_data: #like in the official documentation empty 

./webapp/Dockerfile:

FROM php:7.2-apache
COPY . /var/www/html/
EXPOSE 80

./webapp/index.php:

<?php 
require 'rb.php';
R::setup( 'mysql:host=db:3306;dbname=dbname', 'dbuser', 'dbpassword' );
$post = R::dispense( 'post' );
$post->title = 'My holiday';
$id = R::store( $post );
$post = R::load( 'post', $id );
print_r($post);
?>

Now I do $ docker compose up and visit http://localhost:

Fatal error: Uncaught PDOException: Could not connect to database (dbname).

  • What am I missing to first make this run locally? and second, do I need to change anything so it works on azure right away?
1

There are 1 answers

1
filoumouton On

please try authenticate with root password?

if you also try to connect on the DB container, I think you will have the same error, unless o chmod 755 /var/lib/mysql

this is explained here in this post https://doc4dev.com/en/create-a-web-site-php-apache-mysql-in-5-minutes-with-docker/

I think if you try to use root:somerootpw it shall work. At least you can give it a try :)

also you can maybe try to do a dockerfile for mysql image:

FROM mysql:latest
USER root
RUN chmod 755 /var/lib/mysql