局域网内无法连接MySQL服务器:Django项目连接问题求助
Let's work through this common remote MySQL connection issue step by step— I’ve dealt with this exact problem more times than I can count, so we’ll get your Django app connected in no time.
Step 1: Rule Out Basic Network Issues
First, confirm your local machine can actually reach the remote server:
- Ping the remote IP to check connectivity:
ping 192.168.1.33 - Test if port 3306 is open (use either
telnetornc):telnet 192.168.1.33 3306 # Or with netcat if you have it installed: nc -zv 192.168.1.33 3306
If either of these fail, the problem is with your network (router settings, subnet mismatches, or firewall blocking traffic) rather than MySQL/Django.
Step 2: Update MySQL's Bind Address
By default, MySQL only listens on the local loopback (127.0.0.1), which blocks remote connections. Here's how to fix it:
- Locate your MySQL config file (usually
my.cnfon Linux,my.inion Windows— common paths:/etc/mysql/my.cnfor/etc/mysql/mysql.conf.d/mysqld.cnf). - Find the
bind-addressline and change it to:
(This lets MySQL listen on all network interfaces; you can also specify your local machine’s IP if you want to restrict access.)bind-address = 0.0.0.0 - Restart the MySQL service to apply changes:
# Linux systemd sudo systemctl restart mysql # Windows (via command prompt) net stop mysql && net start mysql
Step 3: Grant Remote Access to Your MySQL User
Your root user is almost certainly restricted to local connections only. You need to explicitly allow it to connect from your Django machine:
- Log into MySQL on the remote server (directly or via SSH):
mysql -u root -p - Run these commands (replace
your_local_ipwith the IP of the machine running Django):
(Quick note: Using an empty password forGRANT ALL PRIVILEGES ON mydb.* TO 'root'@'your_local_ip' IDENTIFIED BY ''; FLUSH PRIVILEGES;rootis a major security risk— consider setting a strong password once the connection works.)
Step 4: Open Port 3306 on the Remote Server's Firewall
Make sure the remote server’s firewall isn’t blocking incoming traffic on port 3306:
- Linux (ufw):
sudo ufw allow 3306/tcp sudo ufw reload - Linux (firewalld):
sudo firewall-cmd --add-port=3306/tcp --permanent sudo firewall-cmd --reload - Windows: Open Windows Defender Firewall > Advanced Settings, then add an inbound rule to allow TCP traffic on port 3306.
Step 5: Double-Check Your Django Configuration
Finally, verify your DATABASES settings are error-free:
- Ensure
HOSTis exactly192.168.1.33(no typos or extra spaces) - Confirm
PORTis set to3306(and MySQL is actually running on this port— check withSHOW GLOBAL VARIABLES LIKE 'port';in MySQL) - Make sure
NAMEmatches the exact database name on the remote server USERandPASSWORDshould match the credentials you just granted remote access to
Once you’ve worked through these steps, try running your Django app again— the connection should go through smoothly.
内容的提问来源于stack exchange,提问作者Abid Omar

