Django项目连接MariaDB报错:Host '19x.xxx.xxx.xxx'不被允许连接
Hey there! That 1130 error is a super common gotcha with MariaDB/MySQL when connecting from a remote host. The reason phpMyAdmin works is because it’s running directly on the same server as your MariaDB instance—so it uses local access permissions, which are allowed by default. Your Django app, though, is coming from an external IP (19x.xxx.xxx.xxx) that MariaDB hasn’t been told to trust yet. Let’s fix this step by step:
Step 1: Log into your MariaDB server’s command line
First, access the MariaDB shell on the server where your database lives (the 17x.xxx.xxx.xxx machine). You can do this via SSH if it’s a remote server, or use the local terminal if you have direct access. Run:
mysql -u root -p
Enter your root password when prompted. If you don’t have root access, use a database user that has CREATE USER and GRANT privileges.
Step 2: Verify your current user permissions
Check what hosts your database user is allowed to connect from. Run this query:
SELECT user, host FROM mysql.user;
You’ll see a list of users and their allowed hosts. Look for your Django database user—its host value is probably localhost, 127.0.0.1, or the IP of the database server itself, not your Django app’s IP (19x.xxx.xxx.xxx).
Step 3: Grant access to your Django server’s IP
You have two options here, depending on your needs:
Option A: Allow only your Django server’s specific IP (recommended for production)
Replace your_database_name, your_db_user, your_db_password, and 19x.xxx.xxx.xxx with your actual details:
GRANT ALL PRIVILEGES ON your_database_name.* TO 'your_db_user'@'19x.xxx.xxx.xxx' IDENTIFIED BY 'your_db_password';
Option B: Allow any external host (not recommended for production)
If your Django server’s IP might change frequently, you can use % to allow connections from any host. Only do this if you trust all external connections (or are in a dev environment):
GRANT ALL PRIVILEGES ON your_database_name.* TO 'your_db_user'@'%' IDENTIFIED BY 'your_db_password';
Step 4: Flush privileges to apply changes
MariaDB won’t recognize the new permissions until you flush them:
FLUSH PRIVILEGES;
Then exit the shell with:
EXIT;
Step 5: Check your server’s firewall
Even if permissions are set correctly, your database server’s firewall might be blocking incoming connections on port 3306 (MariaDB’s default port). Make sure port 3306 is open for your Django server’s IP. For example, on a Linux server using UFW, you’d run:
sudo ufw allow from 19x.xxx.xxx.xxx to any port 3306
Final Check
Double-check your Django settings.py database configuration to make sure it’s pointing to the right values:
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'your_database_name', 'USER': 'your_db_user', 'PASSWORD': 'your_db_password', 'HOST': '17x.xxx.xxx.xxx', 'PORT': '3306', } }
That should get your Django app connected to the MariaDB database!
内容的提问来源于stack exchange,提问作者Pabasara Ranathunga

