gpt4 book ai didi

laravel - Laravel在Docker上:[2002]连接被拒绝

转载 作者:行者123 更新时间:2023-12-02 20:00:01 25 4
gpt4 key购买 nike

我试图在Docker上安装Laravel应用,但是数据库容器给我带来了麻烦。

具体来说,当我尝试在浏览器中打开应用程序时出现此错误:

SQLSTATE[HY000] [2002] Connection refused

但是,据我所知,所有用户凭据都是正确的。也许我缺少什么?请看下面。

docker-compose.yml:
version: '3'
services:
app:
build:
context: ./
dockerfile: app.dockerfile
working_dir: /var/www
volumes:
- ./yoga/:/var/www
environment:
- "DB_PORT=33061"
- "DB_HOST=database"
web:
build:
context: ./
dockerfile: web.dockerfile
working_dir: /var/www
volumes:
- ./:/var/www
ports:
- 8080:80
database:
image: mysql:5.7
container_name: database
volumes:
- dbdata:/var/lib/mysql
environment:
- "MYSQL_DATABASE=yogadb"
- "MYSQL_USER=yogi"
- "MYSQL_PASSWORD=mypasshere"
- "MYSQL_ROOT_PASSWORD="
ports:
- "33061:3306"

volumes:
dbdata:

.env:
DB_CONNECTION=mysql
DB_HOST=database
DB_PORT=3306
DB_DATABASE=yogadb
DB_USERNAME=yogi
DB_PASSWORD=mypasshere

当我在docker外部运行应用程序时,一切正常,我只是将 DB_HOST=database替换为 DB_HOST=127.0.0.1
我该怎么做才能解决此问题?

docker ps输出为:
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                                NAMES
2da7283f7a65 docker_app "docker-php-entrypoi…" 19 minutes ago Up 7 seconds 9000/tcp docker_app_1
4801fe3312c1 mysql:5.7 "docker-entrypoint.s…" 2 hours ago Up 7 seconds 33060/tcp, 0.0.0.0:33061->3306/tcp 4801fe3312c1_database
ab370ae1d155 docker_web "nginx -g 'daemon of…" 25 hours ago Up 7 seconds 443/tcp, 0.0.0.0:8080->80/tcp docker_web_1

最佳答案

如@prd所述,您需要为容器[1]创建桥接网络,然后将容器添加到网络[2]。

容器的主机名由docker-compose.yml中的服务名称确定。在您的情况下,如果app服务将通过主机名database和端口database连接到3306服务。

因此docker-compose.yml变为:

version: '3'
services:
app:
build:
context: ./
dockerfile: app.dockerfile
working_dir: /var/www
volumes:
- ./yoga/:/var/www
environment:
- "DB_PORT=3306" # Port of database container is 3306
- "DB_HOST=database"
networks:
- name_of_network # [2] add container to network
web:
build:
context: ./
dockerfile: web.dockerfile
working_dir: /var/www
volumes:
- ./:/var/www
ports:
- 8080:80
database: # Name of service, which determines hostname of container
image: mysql:5.7
container_name: database
volumes:
- dbdata:/var/lib/mysql
environment:
- "MYSQL_DATABASE=yogadb"
- "MYSQL_USER=yogi"
- "MYSQL_PASSWORD=mypasshere"
- "MYSQL_ROOT_PASSWORD="
ports:
- "33061:3306"
networks:
- name_of_network # [2] add container to network

volumes:
dbdata:

networks:
name_of_network: # [1] create bridged network

关于laravel - Laravel在Docker上:[2002]连接被拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54572960/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com