简体   繁体   中英

“Connection refused”, when trying to connect to DB from inside the Docker container

I'm having some problems with the following Dockerfile:

FROM php:7.0-apache

RUN a2enmod rewrite

RUN docker-php-ext-install pdo pdo_mysql

COPY php.ini /usr/local/etc/php/
COPY . /var/www/html/

I'm using the Slim PHP framework and trying to connect to the database, but is returning the following error:

HTTP/1.1 500 Internal Server Error Content-Type: text/html {"error": {"text": SQLSTATE[HY000] [2002] Connection refused}

Here's the code where the exception is raised:

// Instantiate a database connection
$container['db'] = function ($c) {
    try {
        $db = $c['settings']['db'];

        $pdo = new PDO("mysql:host=" . $db['host'], $db['user'], $db['pass']);  

        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

        //Create database if not exists
        $dbname = "`".str_replace("`","``",$db['dbname'])."`";
        $pdo->query("CREATE DATABASE IF NOT EXISTS $dbname");
        $pdo->query("use $dbname");

        //Create tables if not exists
        $pdo->query(
            "CREATE TABLE IF NOT EXISTS `Assets` (
                `id` INT AUTO_INCREMENT NOT NULL,
                `first_property` varchar(50),
                `second_property` varchar(50),
                PRIMARY KEY (`id`))"
        );   

        return $pdo;
    } catch (PDOException $e) {
        return $c['response']
            ->withStatus(500)
            ->withHeader('Content-Type', 'text/html')
            ->write('{"error": {"text": ' . $e->getMessage() . '}');
    }
};

Does anyone know where the problem could be?

Thank you in advance!

You can create a docker container for MySQL using something like...

docker run --name MySQLDB -v /var/lib/mysql -e MYSQL_ROOT_PASSWORD=rootpwd -d mysql:5.7

then (assuming linux)

docker inspect MySQLDB | grep IPA

to get the IP address to use for the connection.

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