简体   繁体   中英

How do I get php to talk to mysql using docker?

Here is my docker-compose.yml file:

# ./docker-compose.yml

version: '3'
services:
  db:
    image: mysql:5.7
    environment:
      MYSQL_ROOT_PASSWORD: xxx
      MYSQL_DATABASE: test_db
      MYSQL_USER: abc
      MYSQL_PASSWORD: xyz
    ports:
      - "9906:3306"
  web:
    build:
      context: .
      dockerfile: Dockerfile
    image: php:7.2.2-apache
    container_name: php_web
    depends_on:
      - db
    volumes:
      - ./php/:/var/www/html/
    ports:
      - "8100:80"
    stdin_open: true
    tty: true

Then I run docker-compose up --build and access http://localhost:8100 and I get connection refused error from mysqli.

$mysqli->connect('db', 'abc', 'xyz', 'test_db', 9906);

Your docker-compose.yml file looks correct. Change your PHP connection info to connect to port 3306 (container) instead of 9906 (host).

<?php
// Use either 3306 or blank.
$link = mysqli_connect("db", "devuser", "devpass", "test_db", 3306);

if (!$link) {
    echo "Error: Unable to connect to MySQL." . PHP_EOL;
    echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
    echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
    exit;
}

echo "Success: A proper connection to MySQL was made! The my_db database is great." . PHP_EOL;
echo "Host information: " . mysqli_get_host_info($link) . PHP_EOL;

mysqli_close($link);

// Output: Success: A proper connection to MySQL was made! The my_db database is great. Host information: db via TCP/IP

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