Skip to content
Advertisement

Can’t connect to database in docker-compose

This is my docker-compose.yaml

version: "3.1"
services:
  mysql:
    image: mysql:8.0.13
    container_name: project-mysql
    volumes:
      - ./docker/data/mysql:/var/lib/mysql
    environment:
      MYSQL_ROOT_PASSWORD: secret
      MYSQL_DATABASE: db
      MYSQL_USER: dbuser
      MYSQL_PASSWORD: secret
    ports:
      - "3306:3306"

  webserver:
    image: nginx:alpine
    container_name: project-webserver
    working_dir: /var/www
    volumes:
      - .:/var/www
      - ./docker/config/nginx/nginx.conf:/etc/nginx/conf.d/default.conf
    ports:
      - "8080:80"

  php-fpm:
    build: ./docker/config/php
    container_name: project-php-fpm
    working_dir: /var/www
    volumes:
      - .:/var/www
    environment:
      XDEBUG_CONFIG: remote_host=172.17.0.1
      PHP_IDE_CONFIG: serverName=docker

The problem is that php container can’t connect to mysql. Although from host I can connect with mycli -h 127.0.0.1 -P 3306 -u root. But when I exec in php container and try it, get ‘Connection refused’

Advertisement

Answer

Your mysql service binds mysql server’s port 3306 to 3306 of the host machine. Thus is it normal that you can connect from host.

From inside php container, localhost is referring to that particular container as @David Maze said in the comments.

Since you are using docker-compose containers are in the same network, so you should use the service name in order to connect to the mysql server.

Try this from php container:

mycli -h mysql -P 3306 -u root

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement