Connect to MySQL from outside vagrant

前端 未结 2 965
执念已碎
执念已碎 2021-01-14 16:40

I would like to connect with mycli to the MySQL server running inside a vagrant instance.

My basic Vagrantfile looks like the following code snippet:



        
相关标签:
2条回答
  • 2021-01-14 17:35

    If you are connecting from outside of the vm, you'll need to add a port mapping that listens on the host and forwards requests to the guest. Similar to the one defined for http here:

    config.vm.network "forwarded_port", guest: 80, host: 8082
    

    For mysql (assuming your mysql listens on the default port):

    config.vm.network "forwarded_port", guest: 3306, host: 33060
    

    After, modifying the Vagrant file, vagrant reload.

    Then when connecting, specify the port

    mysql -P 33060 -u user -p database
    
    0 讨论(0)
  • 2021-01-14 17:41

    on top of what JRD said on the port forwarding, you need to make sure mysql listens on all port and not just locally

    edit the /etc/mysql/my.cnf file and make sure, either

    • you have bind-address = 0.0.0.0
    • or you comment the line #bind-address ...

    make sure to restart your mysql server after the change

    $ sudo service mysql restart
    

    Then you can connect from your host - In case you get the following error

    $ mysql -h127.0.0.1 -P 33600 -uroot -p
    Enter password:
    ERROR 1130 (HY000): Host '172.16.42.2' is not allowed to connect to this MySQL server
    

    Then came back to the guest and do

    vagrant@precise64:~$ mysql -h127.0.0.1 -uroot -p
    ...
    mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'172.16.42.2' WITH GRANT OPTION;
    Query OK, 0 rows affected (0.00 sec)
    
    mysql> FLUSH PRIVILEGES;
    Query OK, 0 rows affected (0.00 sec)
    

    Then you should have no issue to connect from the host machine

    $ mysql -h127.0.0.1 -P 33600 -uroot -p
    Enter password:
    Welcome to the MySQL monitor.  Commands end with ; or \g.
    Your MySQL connection id is 36
    Server version: 5.5.44-0ubuntu0.12.04.1 (Ubuntu)
    
    0 讨论(0)
提交回复
热议问题