When Docker containers are isolated from the host system, connecting to a PostgreSQL server running on WSL (Windows Subsystem for Linux) requires specific configurations.

Methods to Connect Docker to PostgreSQL:

  1. Host Networking:

    docker run --network="host" -p 8181:8181 docker-todo-app
    

    This allows the Docker container to use the host’s network and access PostgreSQL on 127.0.0.1.

  2. Using Docker Compose: Create a docker-compose.yml:

    version: '3.8'
    
    services:
      app:
        build:
          context: .
          dockerfile: Dockerfile
        ports:
          - "8181:8181"
        depends_on:
          - db
        environment:
          DB_HOST: db
          DB_PORT: 5432
          DB_DATABASE: your_database
          DB_USERNAME: your_username
          DB_PASSWORD: your_password
    
      db:
        image: postgres:latest
        environment:
          POSTGRES_DB: your_database
          POSTGRES_USER: your_username
          POSTGRES_PASSWORD: your_password
        ports:
          - "5432:5432"
    

    In your .env file:

    DB_CONNECTION=pgsql
    DB_HOST=db
    DB_PORT=5432
    DB_DATABASE=your_database
    DB_USERNAME=your_username
    DB_PASSWORD=your_password
    

    Run with:

    docker-compose up
    
  3. Exposing WSL IP Address: Find the WSL IP address:

    ip addr show eth0
    

    Update your .env file:

    DB_CONNECTION=pgsql
    DB_HOST=your_wsl_ip_address
    DB_PORT=5432
    DB_DATABASE=your_database
    DB_USERNAME=your_username
    DB_PASSWORD=your_password
    

    Ensure PostgreSQL is configured to accept external connections by modifying postgresql.conf and pg_hba.conf.

Using these methods should resolve connection issues between your Docker container and the PostgreSQL server on WSL.