Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

quickee's avatar

Laravel 10 / Docker getting app to connect to MySQL

I CAN connect to the database with mysql workbench and through docker terminal but not through the app. Get error. Any thoughts?

SQLSTATE[HY000] [2002] No such file or directory (Connection: mysql, SQL: select * from `users` where `users`.`id` = 1 limit 1)

what i use for workbench - works

127.0.0.1:8001
username:root password:password

docker term - works

mysql -u root -password

my docker config

    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

docker container ps

612aadd5ed17   sail-8.2/app             "start-container"        3 weeks ago   Up 8 minutes             0.0.0.0:80->80/tcp, 0.0.0.0:5173->5173/tcp, 8000/tcp   app-laravel.test-1
7a4b309782e6   redis:alpine             "docker-entrypoint.s…"   3 weeks ago   Up 3 days (healthy)      0.0.0.0:6379->6379/tcp                                 app-redis-1
a521cd0d43df   mysql/mysql-server:8.0   "/entrypoint.sh mysq…"   3 weeks ago   Up 8 minutes (healthy)   33060-33061/tcp, 0.0.0.0:8001->3306/tcp                app-mysql-1

docker output inspected by the container id


[
    {
        "Id": "a521cd0d43dff06c8fd21312b3e00cf984178be474aa4dfaaf59318bef732a68",
        "Created": "2023-04-26T15:46:59.686534025Z",
        "Path": "/entrypoint.sh",
        "Args": [
            "mysqld"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 10478,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2023-05-22T21:27:01.994243831Z",
            "FinishedAt": "2023-05-22T21:26:55.451580726Z",
            "Health": {
                "Status": "healthy",
                "FailingStreak": 0,
                "Log": [
                    {
                        "Start": "2023-05-22T21:36:34.093396017Z",
                        "End": "2023-05-22T21:36:34.224810341Z",
                        "ExitCode": 0,
                        "Output": "mysqladmin: [Warning] Using a password on the command line interface can be insecure.\nmysqld is alive\n"
                    },
                    {
                        "Start": "2023-05-22T21:37:04.236046338Z",
                        "End": "2023-05-22T21:37:04.348676238Z",
                        "ExitCode": 0,
                        "Output": "mysqladmin: [Warning] Using a password on the command line interface can be insecure.\nmysqld is alive\n"
                    },
                    {
                        "Start": "2023-05-22T21:37:34.360587772Z",
                        "End": "2023-05-22T21:37:34.485958493Z",
                        "ExitCode": 0,
                        "Output": "mysqladmin: [Warning] Using a password on the command line interface can be insecure.\nmysqld is alive\n"
                    },
                    {
                        "Start": "2023-05-22T21:38:04.498950401Z",
                        "End": "2023-05-22T21:38:04.61098596Z",
                        "ExitCode": 0,
                        "Output": "mysqladmin: [Warning] Using a password on the command line interface can be insecure.\nmysqld is alive\n"
                    },
                    {
                        "Start": "2023-05-22T21:38:34.622147299Z",
                        "End": "2023-05-22T21:38:34.742680859Z",
                        "ExitCode": 0,
                        "Output": "mysqladmin: [Warning] Using a password on the command line interface can be insecure.\nmysqld is alive\n"
                    }
                ]
            }
        },
        "Image": "sha256:1d9c2219ff69238d2f8e576dba546bcd16baaef710babbb1f89e67bbd3530267",
        "ResolvConfPath": "/var/lib/docker/containers/a521cd0d43dff06c8fd21312b3e00cf984178be474aa4dfaaf59318bef732a68/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/a521cd0d43dff06c8fd21312b3e00cf984178be474aa4dfaaf59318bef732a68/hostname",
        "HostsPath": "/var/lib/docker/containers/a521cd0d43dff06c8fd21312b3e00cf984178be474aa4dfaaf59318bef732a68/hosts",
        "LogPath": "/var/lib/docker/containers/a521cd0d43dff06c8fd21312b3e00cf984178be474aa4dfaaf59318bef732a68/a521cd0d43dff06c8fd21312b3e00cf984178be474aa4dfaaf59318bef732a68-json.log",
        "Name": "/app-mysql-1",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "",
        "ExecIDs": null,
        "HostConfig": {
            "Binds": [
                "/home/legitadmin/code/decaf/app/vendor/laravel/sail/database/mysql/create-testing-database.sh:/docker-entrypoint-initdb.d/10-create-testing-database.sh:rw"
            ],
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "app_sail",
            "PortBindings": {
                "3306/tcp": [
                    {
                        "HostIp": "",
                        "HostPort": "8001"
                    }
                ]
            },
            "RestartPolicy": {
                "Name": "",
                "MaximumRetryCount": 0
            },
            "AutoRemove": false,
            "VolumeDriver": "",
            "VolumesFrom": null,
            "CapAdd": null,
            "CapDrop": null,
            "CgroupnsMode": "private",
            "Dns": [],
            "DnsOptions": [],
            "DnsSearch": [],
            "ExtraHosts": [],
            "GroupAdd": null,
            "IpcMode": "private",
            "Cgroup": "",
            "Links": null,
            "OomScoreAdj": 0,
            "PidMode": "",
            "Privileged": false,
            "PublishAllPorts": false,
            "ReadonlyRootfs": false,
            "SecurityOpt": null,
            "UTSMode": "",
            "UsernsMode": "",
            "ShmSize": 67108864,
            "Runtime": "runc",
            "ConsoleSize": [
                0,
                0
            ],
            "Isolation": "",
            "CpuShares": 0,
            "Memory": 0,
            "NanoCpus": 0,
            "CgroupParent": "",
            "BlkioWeight": 0,
            "BlkioWeightDevice": null,
            "BlkioDeviceReadBps": null,
            "BlkioDeviceWriteBps": null,
            "BlkioDeviceReadIOps": null,
            "BlkioDeviceWriteIOps": null,
            "CpuPeriod": 0,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": null,
            "DeviceCgroupRules": null,
            "DeviceRequests": null,
            "KernelMemory": 0,
            "KernelMemoryTCP": 0,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": null,
            "OomKillDisable": null,
            "PidsLimit": null,
            "Ulimits": null,
            "CpuCount": 0,
            "CpuPercent": 0,
            "IOMaximumIOps": 0,
            "IOMaximumBandwidth": 0,
            "Mounts": [
                {
                    "Type": "volume",
                    "Source": "app_sail-mysql",
                    "Target": "/var/lib/mysql",
                    "VolumeOptions": {}
                }
            ],
            "MaskedPaths": [
                "/proc/asound",
                "/proc/acpi",
                "/proc/kcore",
                "/proc/keys",
                "/proc/latency_stats",
                "/proc/timer_list",
                "/proc/timer_stats",
                "/proc/sched_debug",
                "/proc/scsi",
                "/sys/firmware"
            ],
            "ReadonlyPaths": [
                "/proc/bus",
                "/proc/fs",
                "/proc/irq",
                "/proc/sys",
                "/proc/sysrq-trigger"
            ]
        },
        "GraphDriver": {
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/683b4e4e3210146ef3dc1a259c6bf8a0d80be8595484f231889fb20632ba49e7-init/diff:/var/lib/docker/overlay2/befd759c747cacef43b8bcb90eecff0b13b24183e3b81dfbb1effe08ba6dac86/diff:/var/lib/docker/overlay2/f8dae6810eceaa1dccadac16dbe7c521606f437939b2467fc98fd254a30e9877/diff:/var/lib/docker/overlay2/a7770f3aabde1571e4ba2aa5e2fce7646429f42387b6d1913442cafbb281f5ea/diff:/var/lib/docker/overlay2/ec2fa8179569dc852c670247d5791b9e3734110ebe2a7f626e96481a368e096e/diff:/var/lib/docker/overlay2/081150d30b90d18d9b7b0f2eb32fca5ab14e831a3a483b6c821ccc1e632f68bd/diff:/var/lib/docker/overlay2/89f4a71653bea24ba81e043bf4b02a0fee8ee4fb75193f53a3d6db2ffb1bb812/diff:/var/lib/docker/overlay2/0fdf6e272e397668ace14cc7490e0ac0ddad4d33bb6f5a99d30c14353a6585c6/diff",
                "MergedDir": "/var/lib/docker/overlay2/683b4e4e3210146ef3dc1a259c6bf8a0d80be8595484f231889fb20632ba49e7/merged",
                "UpperDir": "/var/lib/docker/overlay2/683b4e4e3210146ef3dc1a259c6bf8a0d80be8595484f231889fb20632ba49e7/diff",
                "WorkDir": "/var/lib/docker/overlay2/683b4e4e3210146ef3dc1a259c6bf8a0d80be8595484f231889fb20632ba49e7/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [
            {
                "Type": "bind",
                "Source": "/home/legitadmin/code/decaf/app/vendor/laravel/sail/database/mysql/create-testing-database.sh",
                "Destination": "/docker-entrypoint-initdb.d/10-create-testing-database.sh",
                "Mode": "rw",
                "RW": true,
                "Propagation": "rprivate"
            },
            {
                "Type": "volume",
                "Name": "app_sail-mysql",
                "Source": "/var/lib/docker/volumes/app_sail-mysql/_data",
                "Destination": "/var/lib/mysql",
                "Driver": "local",
                "Mode": "z",
                "RW": true,
                "Propagation": ""
            }
        ],
        "Config": {
            "Hostname": "a521cd0d43df",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": true,
            "AttachStderr": true,
            "ExposedPorts": {
                "3306/tcp": {},
                "33060/tcp": {},
                "33061/tcp": {}
            },
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "MYSQL_DATABASE=app",
                "MYSQL_USER=root",
                "MYSQL_PASSWORD=password",
                "MYSQL_ALLOW_EMPTY_PASSWORD=1",
                "MYSQL_ROOT_PASSWORD=password",
                "MYSQL_ROOT_HOST=%",
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "MYSQL_UNIX_PORT=/var/lib/mysql/mysql.sock"
            ],
            "Cmd": [
                "mysqld"
            ],
            "Healthcheck": {
                "Test": [
                    "CMD",
                    "mysqladmin",
                    "ping",
                    "-ppassword"
                ],
                "Timeout": 5000000000,
                "Retries": 3
            },
            "Image": "mysql/mysql-server:8.0",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": [
                "/entrypoint.sh"
            ],
            "OnBuild": null,
            "Labels": {
                "com.docker.compose.config-hash": "b8b9d233eba0d005141d1c85a34a66ca823fd34e1b897e49fea458f59d40288b",
                "com.docker.compose.container-number": "1",
                "com.docker.compose.depends_on": "",
                "com.docker.compose.image": "sha256:1d9c2219ff69238d2f8e576dba546bcd16baaef710babbb1f89e67bbd3530267",
                "com.docker.compose.oneoff": "False",
                "com.docker.compose.project": "app",
                "com.docker.compose.project.config_files": "/home/legitadmin/code/decaf/app/docker-compose.yml",
                "com.docker.compose.project.working_dir": "/home/legitadmin/code/decaf/app",
                "com.docker.compose.service": "mysql",
                "com.docker.compose.version": "2.17.2",
                "desktop.docker.io/wsl-distro": "Ubuntu"
            }
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "d6384745d5f0ac93259f1dcf802a4212458dea041674f55bd0d9f19191a237a7",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {
                "3306/tcp": [
                    {
                        "HostIp": "0.0.0.0",
                        "HostPort": "8001"
                    }
                ],
                "33060/tcp": null,
                "33061/tcp": null
            },
            "SandboxKey": "/var/run/docker/netns/d6384745d5f0",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "",
            "Gateway": "",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "",
            "IPPrefixLen": 0,
            "IPv6Gateway": "",
            "MacAddress": "",
            "Networks": {
                "app_sail": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": [
                        "app-mysql-1",
                        "mysql",
                        "a521cd0d43df"
                    ],
                    "NetworkID": "e31152f59c50054145cbe8ef4b171480159986b8ca9950f564aa31f8897f55e3",
                    "EndpointID": "1f800a77af6b8edb2733505064e7e234e3b8986c3fc7b4bcf19ba081cf984379",
                    "Gateway": "172.18.0.1",
                    "IPAddress": "172.18.0.4",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:12:00:04",
                    "DriverOpts": null
                }
            }
        }
    }
]

database.php

 'mysql' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '8001'),
            'database' => env('DB_DATABASE', 'app'),
            'username' => env('DB_USERNAME', 'root'),
            'password' => env('DB_PASSWORD', 'password'),
            'unix_socket' => env('DB_SOCKET', '/var/lib/mysql/mysql.sock'),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=8001
DB_DATABASE=app
DB_USERNAME=root
DB_PASSWORD=password

FORWARD_DB_PORT= 8001

maybe this matters.

  'unix_socket' => env('DB_SOCKET', '/var/lib/mysql/mysql.sock'),
if i run // php artisan migrate with the socet as above then i get 
  SQLSTATE[HY000] [2002] Permission denied (Connection: mysql, SQL: select * from information_schema.tables where table_schema = app and table_name = migrations and table_type = 'BASE TABLE')

 but if i run //php artisan migrate with the socket as..
  'unix_socket' => env('DB_SOCKET', ''),
i get nothing to migrate

edit tried to update the docker config container name of mysql - that did not work either and change DB

 mysql:
        container_name: mysqltest
        image: 'mysql/mysql-server:8.0'
        ports:
            - '${FORWARD_DB_PORT:-3306}:3306'
        environment: ...

DB_CONNECTION=mysql
DB_HOST=mysqltest
DB_PORT=3006
DB_DATABASE=app
DB_USERNAME=admin
DB_PASSWORD=password

0 likes
5 replies
quickee's avatar
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=app
DB_USERNAME=root
DB_PASSWORD=password

'mysql' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', 'mysql'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'app'),
            'username' => env('DB_USERNAME', 'root'),
            'password' => env('DB_PASSWORD', 'password'),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],

@subuh this did work. im still a bit confused as to why though. Why does it not use the container name set?

EDIT:

//so. It works for the app accessing. but if i try to use it in terminal with php aritsan migrate. I get that error blow. If i change it all back to 127.0.0.1 / 8001 then the migrate works but App referencing doesnt again

 SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo for mysql failed: Name or service not known (Connection: mysql, SQL: select * from information_schema.tables where table_schema = app and table_name = migrations and table_type = 'BASE TABLE')
quickee's avatar

bumping - still having issues with this

esorone's avatar

Hey, Not sure about your setup, but you can try to give remote permissions to the user.

GRANT ALL PRIVILEGES ON <database_name>.* TO '<username>'@'<remote_ip>' IDENTIFIED BY '<password>';

After this you have to enter FLUSH PRIVILEGES; but the bind-address should be changed to 0.0.0.0

It is worth trying. And if this works, let see if you can restrict the access to local.

quickee's avatar
quickee
OP
Best Answer
Level 1

Changing host to 'host.docker.internal' fixes it. I have no idea why, came across this on stackoverflow.

Note - different from above:

  • removed port forwarding and just used 3306
  • change the image to mysql:8.0 from 'mysql/mysql-server:8.0' I strongly believe these two things will not change the outcome but it FINALLY works right after 2 months so its not even worth testing lol.
DB_HOST=host.docker.internal
DB_PORT=3306
DB_DATABASE=app
DB_USERNAME=root
DB_PASSWORD=password

I don't think this will fix it for everyone, seems others had to use the docker container_name they entered on their docker-composer - but there is nothing different or special about my build compare to others when looking at their examples.

Please or to participate in this conversation.