无法通过docker-compose与mysql和php 7连接到数据库

时间:2015-12-24 00:36:26

标签: php mysql docker docker-compose

我从php 7.0.1-apache容器连接到我链接的mysql容器时遇到问题。

PHP容器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

搬运工-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";

错误日志:

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

我不知道我哪里出错了,基本上看起来我的PHP容器中没有正确配置mysql。有什么建议吗?

1 个答案:

答案 0 :(得分:4)

是的,正如您所说的设置不包含Mysqli扩展,您需要手动安装。

将MySQLi的安装添加到你的Dockerfile中,你应该做得很好:

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以实际更新模块的内容。老实说,你不应该这样做。这将导致您的Dockerfile在几周内不会生成相同的构建,只是因为依赖关系已经改变了哪种类型的Docker部分无法解决它? :)