You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Windows10(Docker Toolbox)下用SQLAlchemy连接Docker中的PostgreSQL?

Fixing Python PostgreSQL Connection Issues with Docker Toolbox on Windows 10 Home

Hey there! It’s super frustrating when code works smoothly on one system but breaks on another—let’s break down why your Python PostgreSQL connection is failing with Docker Toolbox on Windows 10 Home, since it ran fine on Ubuntu.

Common Culprits & Fixes

1. You’re Using localhost Instead of the Docker Toolbox VM IP

Docker Toolbox on Windows 10 Home doesn’t run containers directly on your Windows host—it spins up a VirtualBox Linux VM to host Docker. That means localhost points to your Windows machine, not the VM where your PostgreSQL container lives.

  • Find the VM IP: Run this command in your Docker Toolbox terminal:
    docker-machine ip default
    
    You’ll get an IP like 192.168.99.100—use this as the host value in your Python connection string instead of localhost.

2. Port Mapping Might Be Missing or Misconfigured

Make sure your PostgreSQL Docker run command includes the port mapping to expose the container’s 5432 port to the VM (and then to your Windows host). For example:

docker run -d -p 5432:5432 --name test-postgres -e POSTGRES_PASSWORD=yourpass postgres
  • Verify the mapping is active: Run docker ps and check the PORTS column—you should see 0.0.0.0:5432->5432/tcp or similar.

3. Windows Firewall or VirtualBox Network Blocking the Connection

Windows Firewall might be blocking traffic to the Docker Toolbox VM’s 5432 port. Here’s how to troubleshoot:

  • Try pinging the VM IP you found earlier (e.g., ping 192.168.99.100)—if it fails, check VirtualBox’s network settings for the default VM (ensure it’s set to NAT or Bridged mode, and port forwarding for 5432 is enabled if using NAT).
  • Temporarily disable Windows Firewall (just for testing) to see if that fixes the issue—if it does, add an inbound rule allowing traffic to port 5432 from the VM’s IP range.

4. Double-Check Your Python Connection String

Update your connection code to use the VM IP instead of localhost. Here’s an example with psycopg2:

import psycopg2

try:
    conn = psycopg2.connect(
        host="192.168.99.100",  # Replace with your VM's actual IP
        port=5432,
        dbname="your_database_name",
        user="your_postgres_user",  # Default is 'postgres' if you didn't customize it
        password="your_postgres_password"
    )
    print("Connection successful!")
except psycopg2.Error as e:
    print(f"Error connecting: {e}")

5. Restart the Docker Toolbox VM

Sometimes network glitches can cause random connection issues. Try restarting the VM:

docker-machine restart default

Then restart your PostgreSQL container:

docker restart test-postgres

内容的提问来源于stack exchange,提问作者pajamas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:10:29