Running Docker in Network Mode “host” on Windows 10 with WSL2

Running Docker containers in “host” network mode on Windows 10 using WSL2 (Windows Subsystem for Linux 2) allows containers to directly access the host network stack. Here’s how you can achieve this setup:

Prerequisites

  1. Windows 10 with WSL2: Ensure that your Windows 10 installation supports WSL2 and that you have it installed and configured properly. You can follow the official documentation from Microsoft to set up WSL2: Install WSL on Windows 10.
  2. Docker Desktop for Windows: Install Docker Desktop for Windows, which includes Docker Engine, Docker CLI client, Docker Compose, Docker Content Trust, Kubernetes, and Credential Helper.

Configuring Docker to Use “host” Network Mode

  1. Edit Docker Desktop Settings: Open Docker Desktop for Windows.
  • Right-click on the Docker icon in the system tray.
  • Select “Settings” from the context menu.
  • Go to the “General” tab and ensure that “Expose daemon on tcp://localhost:2375 without TLS” is checked. This setting allows Docker commands to be run from WSL.
  1. Configure Docker Daemon: Docker on WSL2 uses a VM with its own network configuration. To run containers in “host” network mode, you need to modify the Docker daemon configuration.
  • Open a WSL terminal (e.g., Ubuntu on WSL2).
  • Edit the Docker daemon configuration file: sudo nano /etc/docker/daemon.json
sudo nano /etc/docker/daemon.json
  • Add the following configuration to the file:
{
  "exec-opts": ["native.cgroupdriver=systemd"],
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "100m"
  },
  "storage-driver": "overlay2",
  "iptables": false,
  "features": {
    "buildkit": true
  },
  "dns": ["8.8.8.8", "8.8.4.4"],
  "default-address-pools": [{"base":"10.0.0.0/8","size":24}],
  "bridge": "docker0",
  "data-root": "/mnt/wsl/docker-desktop-data",
  "userland-proxy": false,
  "host": ["tcp://0.0.0.0:2375"],
  "experimental": true
}
  1. Restart Docker Daemon: After modifying the daemon configuration, restart Docker for the changes to take effect:
sudo service docker restart
  1. Running Docker Containers in “host” Network Mode: In your WSL terminal, you can now run Docker containers with the --network host option to use the host network stack directly:
docker run --network host -d nginx

This command starts an Nginx container in “host” network mode, enabling it to access services on localhost directly as if it were running on the host machine.

Conclusion

Configuring Docker to run containers in “host” network mode on Windows 10 with WSL2 allows for direct access to the host network stack from within Docker containers. By following these steps and configuring Docker properly, you can leverage the benefits of containerized applications with enhanced networking capabilities in your development and testing environments.