How to Use Docker in WSL2: Simple Setup and Usage Guide
To use
Docker in WSL2, install Docker Desktop for Windows and enable the WSL2 integration in its settings. Then, open your WSL2 terminal and run Docker commands directly, as Docker runs inside the WSL2 environment seamlessly.Syntax
Docker commands in WSL2 use the same syntax as on Linux. You run docker followed by the command and options.
docker run [OPTIONS] IMAGE [COMMAND] [ARG...]: Start a container from an image.docker build [OPTIONS] PATH: Build an image from a Dockerfile.docker ps: List running containers.docker stop CONTAINER: Stop a running container.
WSL2 acts like a Linux environment, so Docker commands work natively.
bash
docker run -d -p 80:80 nginx docker ps docker stop <container_id>
Example
This example shows how to run an Nginx web server container inside WSL2 using Docker.
bash
docker run -d -p 8080:80 nginx docker ps
Output
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
abc123def456 nginx "/docker-entrypoint.…" 10 seconds ago Up 9 seconds 0.0.0.0:8080->80/tcp hopeful_morse
Common Pitfalls
1. Docker Desktop not installed or WSL2 integration disabled: Docker commands won't work inside WSL2 without Docker Desktop installed and WSL2 integration enabled.
2. Using Docker Toolbox or legacy Docker for Windows: These older tools do not support WSL2 well and cause issues.
3. Not running WSL2 as default version: Docker requires WSL2, so ensure your distro uses WSL2, not WSL1.
4. Firewall or port conflicts: Make sure ports you map are free on Windows.
bash
## Wrong: Running docker without Docker Desktop or WSL2 integration
$ docker ps
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
## Right: Enable WSL2 integration in Docker Desktop settings and restartOutput
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
Quick Reference
| Step | Command / Action | Description |
|---|---|---|
| 1 | Install Docker Desktop | Download and install Docker Desktop for Windows from the official site. |
| 2 | Enable WSL2 Integration | In Docker Desktop settings, enable integration with your WSL2 Linux distro. |
| 3 | Open WSL2 Terminal | Launch your preferred WSL2 distro terminal (e.g., Ubuntu). |
| 4 | Run Docker Commands | Use Docker commands like docker run or docker ps inside WSL2. |
| 5 | Access Containers | Access container services via localhost and mapped ports on Windows. |
Key Takeaways
Install Docker Desktop and enable WSL2 integration to use Docker inside WSL2.
Run Docker commands directly in your WSL2 terminal as if on Linux.
Ensure your WSL distro is version 2, not 1, for Docker compatibility.
Avoid legacy Docker tools that do not support WSL2 well.
Map ports carefully to avoid conflicts between Windows and WSL2.