Cannot connect to database using docker-compose with mysql and php 7

I am having problems connecting to the linked mysql container from my php 7.0.1-apache container.

The contents of the container in the PHP container:

FROM php:7.0.1-apache

# Initialize html and php.ini
COPY src/ /var/www/html/
COPY config/php.ini /usr/local/etc/php/

# Update modules.
RUN apt-get update

docker-compose.yml:

web:
  build: .
  ports:
   - "80:80"
  links:
   - "db"
  volumes:
   - "./src/:/var/www/html/"

db:
  image: "mysql"
  ports:
   - "3306:3306"
  environment:
   - "MYSQL_ROOT_PASSWORD=somepword"

index.php:

<?php
$servername = "127.0.0.1";
$username = "root";
$password = "somepword";
$db = "test_db";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";

Error Log:

PHP Fatal error:  Uncaught Error: Class 'mysqli' not found in /var/www/html/index.php:8\nStack trace:\n#0 {main}\n  thrown in /var/www/html/index.php on line 8

I'm not sure where I am going wrong, basically it looks like mysql is not configured correctly in my PHP container. Any suggestions?

+4
source share
1 answer

Yes, as you said, your installation does not include the Mysqli extension, which you need to install manually.

Add the MySQLi installation to your Docker file, just like you, and you should be good:

FROM php:7.0.1-apache

RUN apt-get update && apt-get install -y mysql-client libmysqlclient-dev \ 
      && docker-php-ext-install mysqli
    # Initialize html and php.ini
COPY src/ /var/www/html/
COPY config/php.ini /usr/local/etc/php/

apt-get . - apt-get update && apt-get upgrade . , . , Docker , , , Docker, ?:)

+4

Source: https://habr.com/ru/post/1621549/


All Articles