Search code examples
phpmysqllaraveldockerlaravel-artisan

Laravel php artisan command, to specify the mysql port


In my Laravel database configuration.

'mysql' => [
        'driver'    => 'mysql',
        'read' => [
            'host' => [env('DB_READ_HOST', env('DB_HOST') )]
        ],
        'write' => [
            'host' => env('DB_HOST', 'localhost')
        ],
        'port' => env('DB_PORT', '3306'),  

I connect to mysql on port 3306.

But In docker-compose.yml, we tell mysql to connect on 3307 port. The Laravel website connects to mysql fine on port 3307.

mysql:
image: 'mysql'
container_name: api_mysql
restart: always
volumes:
  - /var/lib/mysql
ports:
  - "3307:3306"
networks:
  - api

And I can connect to mysql from hosting machine on port 3307 from command line too.

 mysql -u web  -P3307 -h 127.0.0.1 -p

But when I run php artisan command like

php artisan getData

From the hosting machine (not the docker)

I got the error

SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known

It means when I run php artisan from hosting machine, I have mysql connection issue.

I think it is due to when I run

php artisan getData

the port changes I setup in docker-compose.yml, php artisan would not know.

php artisan getData

will still try to connect to mysql on 3306, which will cause the error.

So how do I run

php artisan getData

And tell it to use port 3307 for mysql connection?

Thanks!


Solution

  • MySQL is available on port 3307 to the hosting machine. When you run artisan commands on a hosting machine, you need them to use this port, which means you'll need to update the configuration. You could try setting up DB_PORT environment variable on your hosting machine to use different port when commands are run in there. Just run the following in your terminal before executing artisan command:

    export DB_PORT=3307
    

    This variable will only be visible in the hosting machine, so it won't break anything in the hosted environment.

    I would advice against running artisan commands in both hosting and hosted machines - why do you want to do this?