![SQLSTATE[HY000] [2002] 连接被拒绝 - docker-compose exec app php artisan migrate](https://linux22.com/image/167333/SQLSTATE%5BHY000%5D%20%5B2002%5D%20%E8%BF%9E%E6%8E%A5%E8%A2%AB%E6%8B%92%E7%BB%9D%20-%20docker-compose%20exec%20app%20php%20artisan%20migrate.png)
Docker 容器已启动并正在运行:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
bf78987a0f5d hakase-labs/laravel "docker-php-entrypoi…" 56 minutes ago Up 56 minutes 9000/tcp app
d1fe2f9171bd mysql:5.7 "docker-entrypoint.s…" 56 minutes ago Up 56 minutes 33060/tcp, 0.0.0.0:3312->3306/tcp db
43f1025c1a59 nginx:alpine "nginx -g 'daemon of…" 56 minutes ago Restarting (1) 54 seconds ago nginx
docker
这是一个带有,mysql
和 的Laravel 安装nginx
。我想在 docker 容器内运行迁移,即
docker-compose exec app php artisan migrate
我的数据库服务非常简单;docker-compose.yml
:
#MySQL Service
db:
image: mysql:5.7
container_name: db
restart: unless-stopped
tty: true
ports:
- "3312:3306"
environment:
MYSQL_DATABASE: laravel
MYSQL_USER: laravel
MYSQL_PASSWORD: password
MYSQL_ROOT_PASSWORD: password
volumes:
- mysqldata:/var/lib/mysql/
networks:
- mynet
.env
:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3312
DB_DATABASE=laravel
DB_USERNAME=laravel
DB_PASSWORD=password
我尝试过的事情;
DB_HOST=mysql
并更改数据库端口号
docker-compose exec app php artisan config:clear
和docker-compose exec app php artisan cache:clear
登录容器;docker-compose exec app ash
并尝试从那里运行迁移 - 同样的错误消息适用。
但没有骰子。容器artisan migrate
内有什么问题docker
?
编辑:我正在.env
容器内进行编辑;
docker-compose exec app vim .env
APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:TWmjLcVOQFMIiKOKvtKQoFS/LMoH05ry/DF6148izL8=
APP_DEBUG=true
APP_URL=http://localhost
LOG_CHANNEL=stack
DB_CONNECTION=mysql
DB_HOST=db
DB_PORT=3307
DB_DATABASE=laravel
DB_USERNAME=laravel
DB_PASSWORD=password
从而传播到我的本地副本。
DB_CONNECTION=mysql
DB_HOST=db
DB_PORT=3307
DB_DATABASE=laravel
DB_USERNAME=laravel
DB_PASSWORD=password
再次运行,仍然没有迁移;
$ docker-compose exec app php artisan cache:clear
Application cache cleared!
$ docker-compose exec app php artisan config:clear
Configuration cache cleared!
$ docker-compose exec app php artisan migrate
Illuminate\Database\QueryException : SQLSTATE[HY000] [2002]
Connection refused (SQL: select *
答案1
我猜您已经遵循了本教程dockerizing-laravel-with-nginx-mysql-and-docker-compose
DB_HOST
必须是您在 中指定的服务名称docker-compose.yml
,并且DB_PORT
需要具有您在端口映射中指定的端口。
当我编辑.env
文件时:
DB_CONNECTION=mysql
DB_HOST=db # <= service-name of db
DB_PORT=3306 # <= port-mapping from service: db
DB_DATABASE=laravel
DB_USERNAME=laravel
DB_PASSWORD=password
./artisan migrate
获取到数据库的连接。
答案2
这对我有用。我认为您可能需要使用 重建容器docker-compose up --build
。它可能对其他人有用。
DB_CONNECTION=mysql
DB_HOST=db
DB_PORT=3306