mysql SQLSTATE[HY000] [2002] Docker中的laravel发生连接被拒绝错误

oxf4rvwz  于 2023-01-08  发布在  Mysql
关注(0)|答案(1)|浏览(245)

这是我第一次使用docker所以很抱歉如果我犯了愚蠢的错误。我试图设置一个docker容器为laravel开发。这些是我的文件:

停靠文件

FROM php:8-fpm

COPY . /app
WORKDIR /app

COPY composer.lock composer.json ./
RUN apt-get update -y && apt-get install -y sendmail libpng-dev

RUN apt-get update && apt-get install -y \
    build-essential \
    curl

RUN curl -sSL https://github.com/mlocati/docker-php-extension-installer/releases/latest/download/install-php-extensions -o - | sh -s \
      gd \
      zip 
RUN docker-php-ext-install mysqli pdo pdo_mysql
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
RUN composer update
RUN composer install

停靠-组合。yaml:

version: '3.9'
name: caas-portal
services:
      
  front:
    build:
      context: ./webapp
      target: builder
    ports:
      - 4200:4200
    volumes:
      - ./webapp:/project
      - /project/node_modules

  mysql:
    container_name: mysql
    image: mysql:latest
    environment:
      - MYSQL_ROOT_PASSWORD=password
      - MYSQL_DATABASE=db
    ports:
      - 3307:3306/tcp
    networks:
      - laravel

  elasticsearch:
    container_name: elasticsearch
    image: docker.elastic.co/elasticsearch/elasticsearch:7.17.7
    environment:
      - discovery.type=single-node
    ports:
      - 9200:9200/tcp
      - 9300:9300/tcp
    volumes:
        - 'elasticsearch:/usr/share/elasticsearch/data'
    networks:
      - laravel

  app:
    container_name: back
    build: .
    ports:
      - 8000:80
    networks:
      - laravel
      
networks:
  laravel:
    driver: bridge

volumes:
    elasticsearch:
        driver: local

这是我的**.env的相关部分:**

DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3307
DB_DATABASE=db
DB_USERNAME=root
DB_PASSWORD=password

当我运行docker exec -it <container> sh并在shell中运行php artisan migrate时,我得到以下错误:
SQLSTATE[HY000] [2002] Connection refused (SQL: select * from information_schema.tables where table_schema = db and table_name = migrations and table_type = 'BASE TABLE')
我看过类似的帖子,也试着按照给出的答案去做,但还是没有运气。错误在哪里,如何纠正?

1qczuiv0

1qczuiv01#

在**.env中,尝试DB_PORT=3306
根据Networking in Compose上的Docker
注意HOST_PORTCONTAINER_PORT之间的区别是很重要的。[...]网络化的服务到服务通信使用CONTAINER_PORT
如果我们将这个概念应用于
docker-compose.yaml**,我们知道mysql服务有一个主机端口3307,同时有一个容器端口3306
现在,如果希望app服务连接到mysql服务(服务到服务通信),那么在app容器中,应该使用mysql容器端口3306进行连接,而不是3307

相关问题