The problem that I am experiencing is that when I try to connect to the database that is in a docker container, I keep getting the error SQLSTATE[HY000] [2002] Connection refused
through PDO. I have tried the methods mentioned here as well as some other posts that say very similar things, to no avail. MySQL is currently active, and ready to accept connections. I am running Docker Engine 19.03.12
Compose 1.26.2
Docker Desktop 2.3.0.4 (46911)
with Compose File version 3.8
. Below is my docker-compose.yml:
version: "3.8"
services:
web:
build:
context: ./php
dockerfile: Dockerfile
container_name: php74
depends_on:
- database
ports:
- "8000:80"
volumes:
- "./php:/var/www/html"
database:
command: "--default-authentication-plugin=mysql_native_password"
container_name: mysql8
environment:
MYSQL_DATABASE: quizzane
MYSQL_ROOT_PASSWORD: root
MYSQL_USER: quizzane
MYSQL_PASSWORD: "QFtdFZk2wC-c4skfJ?5#TPLrXyeZVTJ99=s*GEBVR_!XQ9B?_?NE+Dwc7pL!2fzb"
image: "mysql:8.0.21"
ports:
- "6033:3306"
restart: always
and then my Dockerfile:
FROM php:7.4.9-apache
RUN apt-get update && apt-get upgrade -y
RUN apt-get install openssl curl zlib1g-dev enchant libsodium-dev libzip-dev bzip2 libcurl4-openssl-dev libssl-dev libpng-dev libgmp-dev libxml2-dev libenchant-dev libc-client2007e-dev libc-client-dev libkrb5-dev libonig-dev libedit-dev libtidy-dev libxslt-dev libgd2-xpm-dev -y
RUN docker-php-ext-configure imap --with-kerberos --with-imap-ssl
RUN docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/
RUN docker-php-ext-install bcmath calendar ctype curl enchant exif ffi ftp gd gmp iconv imap intl mbstring pcntl pdo pdo_mysql readline shmop soap sockets sodium sysvmsg sysvsem sysvshm tidy tokenizer xsl zip -j$(nproc)
RUN ls /usr/local/lib/php/extensions/no-debug-non-zts-20190902/
EXPOSE 80
and my PDO connection file:
try {
$datasource = 'mysql:host=127.18.0.2;port=6033;dbname=quizzane';
$username = 'quizzane';
$password = 'QFtdFZk2wC-c4skfJ?5#TPLrXyeZVTJ99=s*GEBVR_!XQ9B?_?NE+Dwc7pL!2fzb';
$pdo = new PDO($datasource, $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
The IP that is not localhost is the IP of the docker container. Here is part of what MySQL shows when starting up:
mysql8 | 2020-08-30T17:19:08.484523Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.21' socket: '/var/run/mysqld/mysqld.sock' port: 3306 MySQL Community Server - GPL.