Symfony 4“连接被拒绝"尝试连接到 docker mysql 容器时 [英] Symfony 4 "Connection refused" while trying to connect to docker mysql container

查看:37
本文介绍了Symfony 4“连接被拒绝"尝试连接到 docker mysql 容器时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是如何配置到mysql容器的连接.

My question is how to configure connection to mysql container.

这是我的docker-compose.yml

version: '3'
services:
php:
    build: ./php-fpm
    volumes:
        - ./iym:/var/www/iym
        - ./php-fpm/php.ini:/usr/local/etc/php/php.ini
    depends_on:
        - mysql
web:
    build: ./nginx
    ports:
        - "8888:80"
    volumes:
        - ./iym:/var/www/iym
        - ./nginx/iym.conf:/etc/nginx/conf.d/default.conf
    depends_on:
        - php
mysql:
    image: mysql:5.6
    restart: always
    command: --default-authentication-plugin=mysql_native_password
    volumes:
        - ${DB_PATH_HOST}:/var/lib/mysql
    environment:
        MYSQL_ROOT_PASSWORD: "symf0ny"
    ports:
        - "3306:3306"

这是我在 .env 文件中的 DATABASE_URL

And here is my DATABASE_URL in .env file

DATABASE_URL=mysql://root:symf0ny@127.0.0.1:3306/iym

当我尝试运行 php bin/console algorithm:database:create 时,我收到类似SQLSTATE[HY000] [2002] Connection denied"的错误消息.操作系统 - ubuntu 18.04.我应该怎么做才能连接到数据库?非常感谢!

When i try to run php bin/console doctrine:database:create i get an error like "SQLSTATE[HY000] [2002] Connection refused". OS - ubuntu 18.04. What should i do to connect to DB? Many thanks!

推荐答案

我假设您正在尝试从 docker-compose 中定义的另一个容器/服务进行连接,并且您正在使用当前版本的 docker-compose(2.4 或3.7)

你需要改变

DATABASE_URL=mysql://root:symf0ny@127.0.0.1:3306/iym

DATABASE_URL=mysql://root:symf0ny@mysql:3306/iym

原因是 127.0.0.1 指的是运行 php 的机器的本地主机.在这种情况下,它是 php 的容器 localhost.但是数据库不在那里运行.它运行在另一个 docker 容器中,可以在服务名称下访问,在本例中为 mysql.

The reason is that 127.0.0.1 is refering to the localhost of the machine on which php runs. In this case it's the php's container localhost. But the db doesn't run there. It runs in another docker container, which can be reached under the service name, mysql in this case.

docker-compose 网络文档 中写道:

默认情况下,Compose 会为您的应用设置单个网络.服务的每个容器都加入默认网络,并且可以被该网络上的其他容器访问,并且可以在与容器名称相同的主机名上被它们发现.

By default Compose sets up a single network for your app. Each container for a service joins the default network and is both reachable by other containers on that network, and discoverable by them at a hostname identical to the container name.

但是,可以在容器名称下发现服务(自动生成到 projectName_serviceName_1(项目名称以默认文件夹名称开头),但也可以在服务名称下发现,link服务别名(如果已定义).我建议尽可能使用服务名称.

but, the service is discoverable under the container name (which is automatically generated to projectName_serviceName_1 (project name begin by default folder name), but also under service name, link and service alias if defined. I would recommend using service name wherever possible.

更多文档:https://docs.docker.com/compose/networking/

这篇关于Symfony 4“连接被拒绝"尝试连接到 docker mysql 容器时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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