mysqldjangovagrant

How to connect to a database inside Vagrant


I'm running Django, and I need to have my database inside Vagrant which I want to connect to. Apache is running on my local PC. How should I set up the port forwarding in the Vagrant config file and the settings file in Django so I can connect to the db inside Vagrant? My current Django db configuration:

   DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',  # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
            'NAME': 'db_name',  # Or path to database file if using sqlite3.
            'USER': 'root',  # Not used with sqlite3.
            'PASSWORD': 'db_pass',  # Not used with sqlite3.
            'HOST': '',  # Set to empty string for localhost. Not used with sqlite3.
            'PORT': '',  # Set to empty string for default. Not used with sqlite3.
            'OPTIONS': {
                "init_command": "SET storage_engine=INNODB",
            }
        },

and Vagrant config:

   config.vm.network :forwarded_port, guest: 80, host: 8080
   config.vm.network :forwarded_port, guest: 8000, host: 8001

Solution

  • Your network call should look like this:

    config.vm.network :forwarded_port, guest: [db port x, e.g. 3306 for MySQL], host: [unused host port y]
    

    In your Django configuration, leave the host empty (defaults to localhost) and specify the same port y from above. VirtualBox will forward your request to localhost:y to [guest]:x.