简体   繁体   中英

Can't connect to database with docker-compose with mysql and php 7

I'm having problems connecting to my linked mysql container from my php 7.0.1-apache container.

PHP container Dockerfile:

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'm going wrong, basically it looks like mysql isn't configured correctly in my PHP container. Any suggestions?

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

Add the installation of the MySQLi to your Dockerfile like so 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/

Also lose the apt-get update in the end. If anything you might want to run apt-get update && apt-get upgrade to actually update the modules. Honestly though, you shouldn't be doing this. This will cause your Dockerfile to not produce the same build in a few weeks, simply because the dependencies have changed which kind of defies the part of the point of Docker doesn't it ? :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM