Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Bug]: Issue with Database Connection in Laravel Sail #153

Open
whoisnegrello opened this issue Jan 6, 2025 · 12 comments
Open

[Bug]: Issue with Database Connection in Laravel Sail #153

whoisnegrello opened this issue Jan 6, 2025 · 12 comments
Assignees
Labels

Comments

@whoisnegrello
Copy link

whoisnegrello commented Jan 6, 2025

Extension Version

0.1.14

PHP Binary

Sail

Operating System

macOS

What happened?

Hi,

I believe the extension is having trouble connecting to the database when using Laravel Sail.

Here is my .env configuration for the database:

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

Despite this setup, the extension cannot connect to the database. The database is running within a Docker container as part of Sail, and Laravel itself can connect without issues when running commands like php artisan migrate.

Could you please confirm if the extension supports Laravel Sail, or provide guidance on how to configure it properly?

Thank you for your help!

Mimimal Code Sample

2025-01-06 09:54:53.537 [error] Parse Error:
 Eloquent Attributes and Relations


   Illuminate\Database\QueryException 

  SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo for mysql failed: nodename nor servname provided, or not known (Connection: mysql, SQL: select exists (select 1 from information_schema.tables where table_schema = 'online_speaking' and table_name = 'settings' and table_type in ('BASE TABLE', 'SYSTEM VERSIONED')) as `exists`)

at vendor/laravel/framework/src/Illuminate/Database/Connection.php:825
@whoisnegrello
Copy link
Author

Additional information: If I run the extension with a devcontainer configuration, it works without any issues.

@francoism90
Copy link

@whoisnegrello I think that's normal, because the sail network is injected.

Could you post the devcontainer.json you are using? :)

@whoisnegrello
Copy link
Author

whoisnegrello commented Jan 6, 2025

Yes, this is my devcontainer

// https://aka.ms/devcontainer.json
{
	"name": "Existing Docker Compose (Extend)",
	"dockerComposeFile": [
		"../docker-compose.yml"
	],
	"service": "laravel.test",
	"workspaceFolder": "/var/www/html",
	"customizations": {
		"vscode": {
			"extensions": [
				"laravel.vscode-laravel",
				"formulahendry.auto-close-tag",
				"formulahendry.auto-rename-tag",
				"adpyke.codesnap",
				"naumovs.color-highlight",
				"dotenv.dotenv-vscode",
				"dbaeumer.vscode-eslint",
				"mhutchie.git-graph",
				"GitHub.copilot",
				"GitHub.copilot-chat",
				"oderwat.indent-rainbow",
				"shufo.vscode-blade-formatter",
				"PKief.material-icon-theme",
				"csstools.postcss",
				"vunguyentuan.vscode-postcss",
				"esbenp.prettier-vscode",
				"MS-CEINTL.vscode-language-pack-es",
				"mrmlnc.vscode-scss",
				"RobbOwen.synthwave-vscode",
				"bradlc.vscode-tailwindcss",
				"shardulm94.trailing-spaces",
				"WakaTime.vscode-wakatime",
				"redhat.vscode-yaml",
				"xdebug.php-pack",
				"bmewburn.vscode-intelephense-client",
				"redhat.vscode-xml",
				"MehediDracula.php-namespace-resolver"
			],
			"settings": {}
		}
	},
	"remoteUser": "sail",
	"postCreateCommand": "chown -R 1000:1000 /var/www/html 2>/dev/null || true"
}

But the problem arises when I don't use the devcontainer.
In other words, if VS Code connects to the container, it works without any issues, but if I use it without connecting to the container, I encounter the error.
My theory is that the extension has trouble identifying that the MySQL connection is in the Sail environment. It tries to connect locally, but for some reason, it doesn't detect the exposed port.

@francoism90
Copy link

@whoisnegrello Yeah, that's normal, because when you use a devcontainer, it uses the Docker socket and is able to communicate with the Laravel Sail network bridge.

I'm also moving to devcontainers, because it's more flexible and easier to add custom extensions.

So I think you're good. :)

@whoisnegrello
Copy link
Author

It is indeed an excellent tool, but it’s causing me some performance issues, not to mention that every time the environment starts, it has to reinstall all extensions and remap the files for suggestions.
That’s why I’d like to make it work without that extra layer of virtualization.

@whoisnegrello
Copy link
Author

What I don’t understand is why I can connect using the host 127.0.0.1 from the database manager, but if I set the same in the .env file, it doesn’t work. There’s something about the configuration I’m not fully grasping, especially since the port is exposed in the docker-compose.yml.

@francoism90
Copy link

francoism90 commented Jan 6, 2025

Could you please define the performance issues? I'm new to devcontainers, so I'm maybe not much help.

I think you could go for an independed devcontainer (e.g. not extending), or limit the resources with runArgs (--cpus=1, --memory=1g, etc.).

I think you cannot access localhost, since macOS runs this in it's own sandbox. Can you ping and run curl without any issues with the vscode terminal?

For context, I'm building an own devcontainer instead of extending on Laravel itself, which is indeed quite heavy and you cannot limit the resources:

{
    "name": "myproject-devcontainer",
    "build": {
        "dockerfile": "./Dockerfile",
        "context": "."
    },
    "features": {
        "ghcr.io/devcontainers/features/common-utils:2": {
            "username": "vscode",
            "userUid": "501", // Change this to your user UID (id -u)
            "userGid": "501", // Change this to your user GID (id -g)
            "upgradePackages": "true"
        }
    },
    "customizations": {
        "vscode": {
            "settings": {
                "Laravel.phpCommand": "/usr/local/bin/php",
                "php.validate.executablePath": "/usr/local/bin/php",
                "php.executablePath": "/usr/local/bin/php"
            },
            "extensions": [
                "aaron-bond.better-comments",
                "bmewburn.vscode-intelephense-client",
                "bradlc.vscode-tailwindcss",
                "christian-kohler.npm-intellisense",
                "christian-kohler.path-intellisense",
                "davidanson.vscode-markdownlint",
                "dbaeumer.vscode-eslint",
                "devsense.composer-php-vscode",
                "editorconfig.editorconfig",
                "esbenp.prettier-vscode",
                "laravel.vscode-laravel",
                "stylelint.vscode-stylelint"
            ]
        }
    },
    "remoteUser": "vscode",
    "containerUser": "vscode",
    "runArgs": ["--init", "--tty", "--network=myproject_sail"], // here you can append --cpus=1
    "mounts": ["type=bind,source=${localEnv:HOME}/.ssh,target=/home/vscode/.ssh,readonly"]
}

@joetannenbaum
Copy link
Collaborator

Is this still happening with v0.1.16? I made some adjustments to the Sail configuration.

@francoism90
Copy link

francoism90 commented Jan 7, 2025

@joetannenbaum Sail configuration? Do you mean in the GitHub repo of Laravel Sail?

@whoisnegrello
Copy link
Author

Is this still happening with v0.1.16? I made some adjustments to the Sail configuration.

Yes, I just reviewed it; I see the new options, but it doesn't recognize Sail as the environment.

Error: 
   Illuminate\Database\QueryException 

  SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo for mysql failed: nodename nor servname provided, or not known (Connection: mysql, SQL: select * from `pages` where `id` = 12 limit 1)

If I change the autodetect option to Sail, I get this new error:

2025-01-08 11:09:54.375 [info] Checking sail PHP installation: ./vendor/bin/sail ps
2025-01-08 11:09:54.375 [info] Using sail PHP installation: NAME      IMAGE     COMMAND   SERVICE   CREATED   STATUS    PORTS
2025-01-08 11:09:55.014 [error] Error:
 Eloquent Attributes and Relations

Sail is not running.

You may Sail using the following commands: './vendor/bin/sail up' or './vendor/bin/sail up -d'

2025-01-08 11:09:55.014 [error] ./vendor/bin/sail php "vendor/_laravel_ide/discover-9b5570eff338a790a0f9b3391151f10c.php"
2025-01-08 11:09:55.014 [error] Eloquent Attributes and Relations

Sail is not running.

You may Sail using the following commands: './vendor/bin/sail up' or './vendor/bin/sail up -d'

Here is my composer:

services:
    laravel.test:
        build:
            context: ./vendor/laravel/sail/runtimes/8.3
            dockerfile: Dockerfile
            args:
                WWWGROUP: "${WWWGROUP}"
        image: sail-8.3/app
        extra_hosts:
            - "host.docker.internal:host-gateway"
        ports:
            - "${APP_PORT:-80}:80"
            - "${VITE_PORT:-5173}:${VITE_PORT:-5173}"
        environment:
            WWWUSER: "${WWWUSER}"
            LARAVEL_SAIL: 1
            XDEBUG_MODE: "${SAIL_XDEBUG_MODE:-off}"
            XDEBUG_CONFIG: "${SAIL_XDEBUG_CONFIG:-client_host=host.docker.internal}"
            IGNITION_LOCAL_SITES_PATH: "${PWD}"
        volumes:
            - ".:/var/www/html"
        networks:
            - sail
        depends_on:
            - mysql
            - redis
            - meilisearch
            - mailpit
            - selenium

    laravel.scheduler:
        build:
            context: ./vendor/laravel/sail/runtimes/8.3
            dockerfile: Dockerfile
            args:
                WWWGROUP: "${WWWGROUP}"
        image: sail-8.3/app
        extra_hosts:
            - "host.docker.internal:host-gateway"
        environment:
            WWWUSER: "${WWWUSER}"
            LARAVEL_SAIL: 1
        volumes:
            - ".:/var/www/html"
        command:
            ["sh", "-c", "while :; do php artisan schedule:run; sleep 60; done"]
        networks:
            - sail
        depends_on:
            - laravel.test

    laravel.worker:
        build:
            context: ./vendor/laravel/sail/runtimes/8.3
            dockerfile: Dockerfile
            args:
                WWWGROUP: "${WWWGROUP}"
        image: sail-8.3/app
        extra_hosts:
            - "host.docker.internal:host-gateway"
        environment:
            WWWUSER: "${WWWUSER}"
            LARAVEL_SAIL: 1
        volumes:
            - ".:/var/www/html"
        command: php artisan queue:work --sleep=3 --tries=3 --timeout=90
        networks:
            - sail
        depends_on:
            - laravel.test

    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
    redis:
        image: "redis:alpine"
        ports:
            - "${FORWARD_REDIS_PORT:-6379}:6379"
        volumes:
            - "sail-redis:/data"
        networks:
            - sail
        healthcheck:
            test:
                - CMD
                - redis-cli
                - ping
            retries: 3
            timeout: 5s
    meilisearch:
        image: "getmeili/meilisearch:latest"
        ports:
            - "${FORWARD_MEILISEARCH_PORT:-7700}:7700"
        environment:
            MEILI_NO_ANALYTICS: "${MEILISEARCH_NO_ANALYTICS:-false}"
        volumes:
            - "sail-meilisearch:/meili_data"
        networks:
            - sail
        healthcheck:
            test:
                - CMD
                - wget
                - "--no-verbose"
                - "--spider"
                - "http://localhost:7700/health"
            retries: 3
            timeout: 5s
    mailpit:
        image: "axllent/mailpit:latest"
        ports:
            - "${FORWARD_MAILPIT_PORT:-1025}:1025"
            - "${FORWARD_MAILPIT_DASHBOARD_PORT:-8025}:8025"
        networks:
            - sail
    selenium:
        image: selenium/standalone-chrome
        extra_hosts:
            - "host.docker.internal:host-gateway"
        volumes:
            - "/dev/shm:/dev/shm"
        networks:
            - sail
    phpmyadmin:
        image: phpmyadmin/phpmyadmin
        links:
            - mysql:mysql
        ports:
            - "${FORWARD_PHPMYADMIN_PORT:-8080}:80"
        environment:
            PMA_HOST: mysql
            PMA_PORT: 3306
            PMA_ARBITRARY: 1
            PMA_USER: "${DB_USERNAME}"
            PMA_PASSWORD: "${DB_PASSWORD}"
            MYSQL_ROOT_PASSWORD: "${DB_PASSWORD}"
        networks:
            - sail
networks:
    sail:
        driver: bridge
volumes:
    sail-mysql:
        driver: local
    sail-redis:
        driver: local
    sail-meilisearch:
        driver: local

Thanks for your help!

@whoisnegrello
Copy link
Author

I discovered that if I run the same command in an external terminal outside of VSC, it shows the containers, but not in the integrated terminal.

@whoisnegrello
Copy link
Author

I got the extension working properly!
Auto-detect doesn't work, but if the Sail environment is configured manually, version 0.1.16 works correctly.

2025-01-08 11:48:54.133 [info] Activating Laravel Extension...
2025-01-08 11:48:54.133 [info] Started

Thank you very much for your help.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants