无法在docker-compose中连接到数据库 [英] Can't connect to database in docker-compose

查看:229
本文介绍了无法在docker-compose中连接到数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的docker-compose.yaml

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

问题是php容器无法连接到mysql.虽然可以从主机连接 mycli -h 127.0.0.1 -P 3306 -u root .但是当我在php容器中执行并尝试时,得到连接被拒绝"

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'

推荐答案

您的mysql服务将mysql服务器的端口3306绑定到主机的3306.因此,可以从主机进行连接是正常的.

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.

在php容器内部, localhost 指的是@David Maze在评论中所说的特定容器.

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

由于使用的 docker-compose 容器位于同一网络中,因此应使用服务名称以连接到mysql服务器.

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.

从php容器中尝试一下:

Try this from php container:

mycli -h mysql -P 3306 -u root

这篇关于无法在docker-compose中连接到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆