从 Homestead 迁移到 Sail 后无法访问 mysql 数据库

Cannot access mysql database after migrating from Homestead to Sail

我正在尝试将 Laravel 8 项目从 Homestead 迁移到 Sail。 Sail 似乎设置正确,因为我可以在本地访问我的项目网站。但是我无法进入 mysql 来查看数据库:

➜  myproject git:(master) ✗ sail mysql
ERROR 1045 (28000): Access denied for user 'myproject'@'localhost' (using password: YES)

我已经尝试重新启动 Docker,并重新启动我的终端和 运行 sail build --no-cache && sail up 都无济于事。

这是我的 .env 文件的相关部分:

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=myproject
DB_USERNAME=myproject
DB_PASSWORD=secret

这里是 docker-compose.yml 文件:

# For more information: https://laravel.com/docs/sail
version: '3'
services:
    laravel.test:
        build:
            context: ./vendor/laravel/sail/runtimes/8.1
            dockerfile: Dockerfile
            args:
                WWWGROUP: '${WWWGROUP}'
        image: sail-8.1/app
        extra_hosts:
            - 'host.docker.internal:host-gateway'
        ports:
            - '${APP_PORT:-80}:80'
            - '${HMR_PORT:-8080}:8080'
        environment:
            WWWUSER: '${WWWUSER}'
            LARAVEL_SAIL: 1
            XDEBUG_MODE: '${SAIL_XDEBUG_MODE:-off}'
            XDEBUG_CONFIG: '${SAIL_XDEBUG_CONFIG:-client_host=host.docker.internal}'
        volumes:
            - '.:/var/www/html'
        networks:
            - sail
        depends_on:
            - mysql
    mysql:
        image: 'mysql/mysql-server:8.0'
        ports:
            - '${FORWARD_DB_PORT:-3306}:3306'
        environment:
            MYSQL_ROOT_PASSWORD: '${DB_PASSWORD}'
            MYSQL_ROOT_HOST: "%"
            MYSQL_DATABASE: '${DB_DATABASE}'
            MYSQL_USER: '${DB_USERNAME}'
            MYSQL_PASSWORD: '${DB_PASSWORD}'
            MYSQL_ALLOW_EMPTY_PASSWORD: 1
        volumes:
            - 'sail-mysql:/var/lib/mysql'
            - './vendor/laravel/sail/database/mysql/create-testing-database.sh:/docker-entrypoint-initdb.d/10-create-testing-database.sh'
        networks:
            - sail
        healthcheck:
            test: ["CMD", "mysqladmin", "ping", "-p${DB_PASSWORD}"]
            retries: 3
            timeout: 5s
networks:
    sail:
        driver: bridge
volumes:
    sail-mysql:
        driver: local

编辑: 当我将 .env 更改为

DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=myproject
DB_USERNAME=sail
DB_PASSWORD=password

那么错误就是

➜  myproject git:(master) ✗ sail mysql
ERROR 1044 (42000): Access denied for user 'sail'@'%' to database 'myproject'

我刚刚尝试连接到一个新的 laravel 9 应用程序,我认为您只需更改几行即可连接到 Sail 的 Mysql:

.env

DB_CONNECTION=mysql 
DB_HOST=host.docker.internal
DB_PORT=3306
DB_DATABASE=myproject 
DB_USERNAME=sail # <-- "sail" as default user name
DB_PASSWORD=password # <-- "password" as default password

这是必需的,因为 "mysql" 是 docker 容器中数据库部分实例的名称, sail 使用 与数据库交互。

所有其他设置仍然相同。

然后和之前一样sail build --no-cache && sail up