简体   繁体   English

Docker Mysql 与 Laravel 的连接被拒绝

[英]Connection refused on Docker Mysql with Laravel

I'm having trouble connecting to the mysql database from my php/laravel container.我无法从我的 php/laravel 容器连接到 mysql 数据库。 I'm getting a connection refused all the time.我的连接一直被拒绝。 The connection works just fine with Mysql Workbench though.不过,该连接在 Mysql Workbench 上工作得很好。

My docker-compose looks like this:我的 docker-compose 看起来像这样:

services:
  nginx:
    image: nginx:stable-alpine
    container_name: nginx
    ports:
      - "8080:80"
    volumes:
      - ./src:/var/www
      - ./nginx/default.conf:/etc/nginx/conf.d/default.conf
    depends_on:
      - php
      - mysql
    networks:
      - laravel

  mysql:
    image: mysql:5.7.22
    container_name: mysql
    restart: unless-stopped
    tty: true
    ports:
      - "3306:3306"
    environment:
      MYSQL_DATABASE: project_db
      MYSQL_USER: dev
      MYSQL_PASSWORD: dev
      MYSQL_ROOT_PASSWORD: dev
      SERVICE_TAGS: dev
    networks:
      - laravel
  php:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: php_node
    volumes:
      - ./src:/var/www
    ports:
      - "9000:9000"
    networks:
      - laravel

And the relevant part of my.env looks like this: my.env 的相关部分如下所示:

DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=project_db
DB_USERNAME=root
DB_PASSWORD=dev

I have tried removing everything and building the image again, but to no avail.我尝试删除所有内容并再次构建图像,但无济于事。

Can you guys spot my error?你们能看出我的错误吗?

Thanks in advance提前致谢

On Docker for windows you can use host.docker.internal to access the host IP.在 Docker for windows 上,您可以使用 host.docker.internal 访问主机 ZA12A3079E14CED0926EAZ9。

I answered this in the comments but I thought I'd duplicate it as a proper answer to help anyone who finds this in the future and save them reading all the comments我在评论中回答了这个问题,但我想我会把它复制为一个正确的答案,以帮助将来发现这个问题的任何人,并让他们阅读所有评论

For extracting docker container names and their IPs use below command in your terminal:要提取 docker 容器名称及其 IP,请在终端中使用以下命令:

docker inspect -f '{{.Name}} - {{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $(docker ps -aq)

It will show you something like:它会向您显示类似的内容:

/nginx - 172.18.0.4
/php - 172.18.0.3
/mysql - 172.18.0.2

Then use mysql container ip in your.env file然后在 your.env 文件中使用 mysql 容器 ip

DB_HOST=172.18.0.2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM