Running Docker Containers on Windows with WSL2 and Docker Desktop
Docker is a popular platform for developing, shipping, and running applications inside containers. Containers are lightweight and contain everything needed to run the application, so you don’t need to rely on a specific operating system or environment. This article will cover how to run Docker containers on Windows using WSL2 (Windows Subsystem for Linux 2) and Docker Desktop.
Prerequisites
Before you start, make sure you have the following installed:
- Windows 10 version 2004 or higher
- WSL2 enabled on your Windows machine
- A Linux distribution (e.g., Debian) installed on WSL2
- Docker Desktop installed on Windows
Configuring WSL2
To configure WSL2, follow these steps:
- Open PowerShell as Administrator and run the following command to enable the ‘Virtual Machine Platform’ optional component:
dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart- Set WSL2 as the default version:
wsl --set-default-version 2Installing Docker on Linux (WSL2)
Now that WSL2 is configured, you need to install Docker on your Linux distribution. In this example, we will use Debian.
- Update package lists:
sudo apt update
- Install Docker:
sudo apt install docker.io
- Start and enable Docker on boot:
sudo systemctl start docker
sudo systemctl enable docker
Running Docker Containers
With Docker installed on both Windows and Linux (WSL2), you can now run Docker containers. To demonstrate this, let’s create a simple Dockerfile and run it.
- Create a new directory and navigate to it:
mkdir my-docker-app
cd my-docker-app
- Create a new file called Dockerfile and paste the following content:
FROM python:3.9
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["python", "app.py"]
- Create a requirements.txt file with the following content:
flask==2.0.2
gunicorn==20.1.0
- Create a new file called app.py with the following content:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello, World!"
if __name__ == "__main__":
app.run(host='0.0.0.0', port=8080)- Build and run the Docker container:
docker build -t my-docker-app .
docker run -d -p 8080:8080 my-docker-app
Now you can access the application by visiting http://localhost:8080 in your web browser.
In this article, you learned how to run Docker containers on Windows using WSL2 and Docker Desktop. You configured WSL2, installed Docker on Linux, and ran a simple containerized application. This setup allows you to develop and test containerized applications on Windows while using the power and flexibility of Linux.