## File: README.md

# Guia/Tutorial rápido do WSL2 + Docker

*Read this in other language: [English](README.en.md)

## Sumário


  
    **WSL**
  

  - [O que é o WSL2](#o-que-é-o-wsl2)
  - [Requisitos mínimos](#requisitos-mínimos)
  - [Instalação do WSL 2](#instalação-do-wsl-2)
    - [Windows Update](#windows-update)
    - [Atualizar o WSL](#atualizar-o-wsl)
    - [(Opcional) Habilitando WSL em versões antigas do Windows 10](#opcional-habilitando-wsl-em-versões-antigas-do-windows-10)
    - [Atribuir a versão default do WSL para a versão 2](#atribuir-a-versão-default-do-wsl-para-a-versão-2)
    - [Instale o Ubuntu](#instale-o-ubuntu)
    - [(Opcional) Alterar a versão de uma distribuição Linux de WSL 1 para WSL 2](#opcional-alterar-a-versão-de-uma-distribuição-linux-de-wsl-1-para-wsl-2)
    - [Instalação do WSL 2 via Microsoft Store (alternativa)](#instalação-do-wsl-2-via-microsoft-store-alternativa)
    - [Integração com VSCode](#integração-com-vscode)
  - [Windows Terminal como terminal padrão de desenvolvimento para Windows](#windows-terminal-como-terminal-padrão-de-desenvolvimento-para-windows)
  - [O que o WSL 2 pode usar de recursos da minha máquina?](#o-que-o-wsl-2-pode-usar-de-recursos-da-sua-máquina)
  - [Systemd](#systemd)



  
    **WSLg**
  

  - [O que é WSLg](#o-que-é-wslg)
  - [Arquitetura do WSLg](#arquitetura-do-wslg)
  - [Como ativar o WSLg](#como-ativar-o-wslg)



  
    **Docker**
  

  - [O que é o Docker](#o-que-é-docker)
  - [Porque usar WSL 2 + Docker para desenvolvimento](#porque-usar-wsl-2--docker-para-desenvolvimento)
  - [Modo de usar Docker no Windows](#modos-de-usar-docker-no-windows)
    - [1 - (Obsoleto) Docker Toolbox](#1-obsoleto-docker-toolbox)
    - [2 - (Obsoleto) Docker Desktop com Hyper-V](#2-obsoleto-docker-desktop-com-hyper-v)
    - [3 - Docker Desktop com WSL 2](#3-docker-desktop-com-wsl2)
      - [Vantagens](#docker-desktop-vantagens)
      - [Desvantagens](#docker-desktop-desvantagens)
    - [4 - Docker Engine (Docker Nativo) diretamente instalado no WSL2](#4-docker-engine-docker-nativo-diretamente-instalado-no-wsl2)
      - [Vantagens](#docker-engine-vantagens)
      - [Desvantagens](#docker-engine-desvantagens)
  - [Qual modo de usar Docker no Windows escolher?](#qual-modo-de-usar-docker-no-windows-escolher)
  - [Instalação do Docker](#instalação-do-docker)
    - [1 - Instalar o Docker com Docker Desktop](#1---instalar-o-docker-com-docker-desktop)
      - [Ativar o Docker na distribuição Linux](#ativar-o-docker-na-distribuição-linux)
      - [Otimizar recursos do Docker Desktop](#otimizar-recursos-do-docker-desktop)
      - [Aplicar autoMemoryReclaim no WSL 2](#aplicar-automemoryreclaim-no-wsl-2)
    - [2 - Instalar o Docker com Docker Engine (Docker Nativo)](#instalar-o-docker-com-docker-engine-docker-nativo)
      - [Erro ao iniciar o Docker no Ubuntu 22.04](#erro-ao-iniciar-o-docker-no-ubuntu-2204)
      - [Iniciar o Docker automaticamente no WSL](#iniciar-o-docker-automaticamente-no-wsl)
      - [Docker com Systemd](#docker-com-systemd) 




  
    **Dicas e truques**
  

  - [Dicas e truques básicos com WSL 2](#dicas-e-truques-básicos-com-wsl-2)
    - [Performance ao usar o WSL 2](#performance-ao-usar-o-wsl-2)
    - [Windows Terminal](#windows-terminal)
    - [Acessar disco e outros dispositivos do Windows](#acessar-disco-e-outros-dispositivos-do-windows)
    - [Acessar o WSL 2 pelo Windows](#acessar-o-wsl-2-pelo-windows)
    - [Integração com VSCode](#integração-com-vscode)
    - [Executáveis do Windows no WSL 2](#executáveis-do-windows-no-wsl-2)
    - [Listando as distribuições Linux instaladas no WSL 2](#listando-as-distribuições-linux-instaladas-no-wsl-2)
    - [Parando todas as distribuições Linux no WSL 2](#parando-todas-as-distribuições-linux-no-wsl-2)
    - [Backup e restauração de distribuições Linux no WSL 2](#backup-e-restauração-de-distribuições-linux-no-wsl-2)
    - [Compactação do disco virtual do WSL 2](#compactação-do-disco-virtual-do-wsl-2)
    - [Rede em modo LAN e VPN](#rede-em-modo-lan-e-vpn)
    - [Ativar BuildKit no Docker](#ativar-buildkit-no-docker)
    - [Iniciar o Docker automaticamente no WSL 2](#iniciar-o-docker-automaticamente-no-wsl-2)
    - [Liberar memória RAM do WSL 2](#liberar-memória-ram-do-wsl-2)
    - [Arquivos .wslconfig e wsl.conf](#arquivos-wslconfig-e-wslconf)
    - [Expandir o disco virtual do WSL 2](#expandir-o-disco-virtual-do-wsl-2)



  
    **Dúvidas**
  

  - [Dúvidas](#dúvidas)
      - [Preciso de uma licença PRO do Windows 10/11 para usar o WSL 2?](#preciso-de-uma-licença-pro-do-windows-1011-para-usar-o-wsl-2)
      - [Posso continuar desenvolvendo no Windows sem usar o WSL 2?](#posso-continuar-desenvolvendo-no-windows-sem-usar-o-wsl-2)
      - [O WSL 2 funciona junto com outras máquinas virtuais como VirtualBox ou VMWare?](#o-wsl-2-funciona-junto-com-outras-máquinas-virtuais-como-virtualbox-ou-vmware)
      - [É possível acessar aplicações rodando no WSL 2 pelo Windows?](#é-possível-acessar-aplicações-rodando-no-wsl-2-pelo-windows)
      - [É possível rodar aplicações gráficas no WSL 2?](#é-possível-rodar-aplicações-gráficas-no-wsl-2)
      - [Posso usar o WSL em cenários de produção?](#posso-usar-o-wsl-em-cenários-de-produção)
      - [Posso rodar o Docker Engine junto com o Docker Desktop?](#posso-rodar-o-docker-engine-junto-com-o-docker-desktop)
      - [Dúvidas sobre o Docker Desktop](#dúvidas-sobre-o-docker-desktop)
      - [Quer configurar um ambiente mais produtivo no Windows?](#quer-configurar-um-ambiente-mais-produtivo-no-windows)



## O que é o WSL2 

Em 2016, a Microsoft anunciou a possibilidade de rodar o Linux dentro do Windows 10 como um subsistema, isso foi chamado de **WSL** ou **Windows Subsystem for Linux**.

O acesso ao sistema de arquivos no Windows 10 pelo Linux era simples e rápido, porém não tínhamos uma execução completa do kernel do Linux, além de outros artefatos nativos e isto impossibilitava a execução de várias tarefas no Linux, uma delas é o Docker.

Em 2019, a Microsoft anunciou o **WSL 2**, com uma dinâmica aprimorada em relação à 1ª versão:

* Execução do kernel completo do Linux.
* Melhor desempenho para acesso aos arquivos dentro do Linux.
* Compatibilidade completa de chamada do sistema.

O WSL 2 foi lançado oficialmente no dia **28 de maio de 2020**.

Com WSL 2 é possível executar Docker e outras ferramentas que dependem do Kernel do Linux usando o Windows 10/11.

Compare as versões do WSL: [https://docs.microsoft.com/pt-br/windows/wsl/compare-versions](https://docs.microsoft.com/pt-br/windows/wsl/compare-versions)

---

## Requisitos mínimos

* **Windows 10 Home ou Professional**
  - Versão 2004 ou superior (Build 19041 ou superior).
  - Versões mais antigas requerem a instalação manual do WSL 2. Ver tutorial [https://learn.microsoft.com/en-us/windows/wsl/install-manual](https://learn.microsoft.com/en-us/windows/wsl/install-manual).

* **Windows 11 Home ou Professional**
  - Versão 22000 ou superior (qualquer Windows 11).

* Uma máquina compatível com virtualização (verifique a disponibilidade de acordo com a marca do seu processador. Se sua máquina for mais antiga pode ser necessária habilitá-la na BIOS).

* Pelo menos 4GB de memória RAM (Recomendado 8GB).

Provavelmente seu Windows já está na versão suportada, mas verifique isto acessando `Todas as Configurações > Sistema > Sobre`. Caso não esteja, use o Assistente do Windows Update para atualizar a sua versão do Windows.

> **É essencial manter o Windows atualizado, pois o WSL 2 depende de uma versão atualizada do Hyper-V. Verifique o Windows Update.**

---

## Instalação do WSL 2

Todas as instruções abaixo são para o Windows 10/11.

### Windows Update

Verifique se seu Windows está atualizado, pois o WSL 2 depende de uma versão atualizada do Hyper-V. Verifique o Windows Update.

### Atualizar o WSL

Com a versão 2004 do Windows 10 ou qualquer versão do Windows 11, o WSL já estará presente em sua máquina. Para garantir que você está usando a versão mais recente do WSL, execute:

```bash
wsl --update
```

---

### (Opcional) Habilitando WSL em versões antigas do Windows 10

Em versões mais antigas do Windows 10, o WSL 2 não vem habilitado por padrão. Siga os passos seguintes.

1. Pressione `Win + R`, digite `optionalfeatures` e pressione Enter.
2. Na janela “Recursos do Windows”, habilite:

   - Subsistema do Windows para Linux  
   - Plataforma de Máquina Virtual  
   - Hyper-V  

3. Clique em **OK** e reinicie o computador.

> Esses recursos são essenciais para o funcionamento do WSL 2 e para evitar erros como `Não foi possível iniciar a operação porque um recurso necessário não foi instalado.`.

---

### Atribuir a versão default do WSL para a versão 2

A versão 2 normalmente é a default, mas a versão 1 do WSL pode estar como padrão. Execute o comando abaixo para definir como padrão a versão 2:

```bash
wsl --set-default-version 2
```

---

### Instale o Ubuntu

Execute o comando:

```bash
wsl --install
```

Este comando irá instalar o `Ubuntu` como o Linux padrão. 

Se quiser instalar uma versão diferente do Ubuntu, execute:

```bash
wsl --list --online
```

Caso queria instalar outra distribuição execute:

```bash
wsl --install -d nome-da-distribuicao
```

Sugerimos o Ubuntu (sem versão) por ser uma distribuição popular e que já vem com várias ferramentas úteis para desenvolvimento instaladas por padrão.

Após o término da instalação, será solicitado que você crie um **nome de usuário** (sem espaços ou caracteres especiais) e uma **senha**. Essa senha será usada para instalar pacotes e executar comandos como superusuário.

Para abrir o Ubuntu, digite `Ubuntu` no menu iniciar e clique no ícone.

---

### (Opcional) Alterar a versão de uma distribuição Linux de WSL 1 para WSL 2

Se você já tinha o WSL instalado antes e a distribuição está usando a versão 1, altere com:

```bash
wsl --set-version <distribution name> 2
```

Isto acontece raramente, mas algumas pessoas já tinham o WSL 1 instalado antes do WSL 2 ser lançado. Se você não sabe qual versão está usando, execute o comando:

```bash
wsl -l -v
```

Certifique-se de que a distribuição que você está usando está na versão 2. Se não estiver, execute o comando acima para alterar a versão.

---

Parabéns, seu WSL2 já está funcionando!



---

### Instalação do WSL 2 via Microsoft Store (alternativa)

Também é possível instalar distribuições Linux pela Microsoft Store. Basta abrir a loja e buscar pela distribuição desejada, como `Ubuntu`, e clicar em instalar.



### Integração com VSCode

O Visual Studio Code tem uma extensão chamada **Remote - WSL** que permite acessar o WSL 2 diretamente do VSCode. Com esta extensão, você pode editar seus arquivos diretamente no WSL 2, rodar comandos, instalar extensões e muito mais.

Veja mais sobre esta extensão em [Remote - WSL](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-wsl).

Ao abrir um projeto que está dentro do Linux, é importante que o modo WSL do VSCode esteja ativado. No canto inferior esquerdo do VSCode, clique no botão `><` e selecione `Connect to WSL`. Isto irá conectar o VSCode ao WSL 2 e então poderá abrir o projeto que está dentro do Linux. Você verá que o botão `><` mudará para `WSL: Ubuntu`.



Se o VSCode não estiver desta forma ao abrir projetos dentro do Linux, então o modo WSL não estará ativado e você perderá performance ao editar arquivos dentro do Linux, além de não ter suporte para algumas extensões.

Outra forma de abrir o projeto no modo WSL, é acessando a pasta do projeto no terminal do WSL e digitando `code .`. Isto abrirá o VSCode no modo WSL.

## Windows Terminal como terminal padrão de desenvolvimento para Windows

Uma deficiência que o Windows sempre teve era prover um terminal adequado para desenvolvimento. Agora temos o **Windows Terminal** construído pela própria Microsoft que permite rodar terminais em abas, alterar cores e temas, configurar atalhos e muito mais.

Instale-o pelo Windows Store.

Veja mais opções de configuração dele em [Mais sobre o Windows Terminal](https://docs.microsoft.com/pt-br/windows/terminal/get-started).

Por padrão, o Windows Terminal vai identificar os principais shells instalados no Windows, como PowerShell, CMD e WSL.

## O que o WSL 2 pode usar de recursos da sua máquina

Podemos dizer que o WSL 2 tem acesso quase que total ao recursos de sua máquina. Ele tem acesso por padrão:

* A 1TB de disco rígido. É criado um disco virtual de 1TB para armazenar os arquivos do Linux (este limite pode ser expandido, ver a área de dicas e truques).
* A usar completamente os recursos de processamento.
* A usar 50% da memória RAM disponível.
* A usar 25% da memória disponível para SWAP (memória virtual).

Se você quiser personalizar estes limites, crie um arquivo chamado `.wslconfig` na raiz da sua pasta de usuário `(C:\Users\<seu_usuario>)` e defina estas configurações:

```conf
[wsl2]
memory=8GB
processors=4
```

Estes são limites de exemplo e as configurações mais básicas a serem utilizadas, configure-os às suas disponibilidades.


Para mais detalhes veja esta documentação da Microsoft: [https://learn.microsoft.com/pt-br/windows/wsl/wsl-config#configuration-setting-for-wslconfig](https://learn.microsoft.com/pt-br/windows/wsl/wsl-config#configuration-setting-for-wslconfig). Existem outras configurações que podem ser feitas, como configurações de rede, VPN, liberação de memória, etc.

Para aplicar estas configurações é necessário reiniciar as distribuições Linux. Execute o comando: `wsl --shutdown` (Este comando vai desligar todas as instâncias WSL 2 ativas, basta abrir o terminal novamente para usa-las já com as novas configurações).

Este arquivo `.wslconfig` é um arquivo de configuração global, ou seja, ele afetará todas as distribuições Linux que você tiver instalado no WSL 2, porque você pode ter mais de uma distribuição Linux instalada no WSL 2, como um Ubuntu, um Debian, um Fedora, etc.

## Systemd

O WSL é compatível com o `systemd`. O `systemd` é um sistema de inicialização e gerenciamento de serviços que é amplamente utilizado em distribuições Linux modernas. Ela permitirá que você use ferramentas mais complexas no Linux como snapd, LXD, etc.

Não é obrigatório ativa-lo e a qualquer momento ele pode ser desativado e reativado. Mas, recomendamos que o mantenha ativado, porque ele melhorará a compatibilidade com as distribuições Linux, permitindo que você use mais ferramentas e serviços, como Kubernetes, etc (Ele não é necessário para rodar o Docker).

Para ativa-lo, edite o arquivo `/etc/wsl.conf`:

Rode o comando para editar:

```conf
sudo vim /etc/wsl.conf
```

Aperte a letra `i` (para entrar no modo de inserção de conteúdo) e cole o conteúdo:

```conf
[boot]
systemd = true
```

Quando terminar a edição, pressione `Esc`, em seguida tecle `:` para entrar com o comando `wq` (salvar e sair) e pressione `enter`.

Toda vez que esta mudança for realizada é necessário reiniciar o WSL com o comando `wsl --shutdown` no DOS ou PowerShell.

## O que é WSLg

O WSLg é uma extensão do WSL 2 que permite rodar aplicações gráficas do Linux no Windows. Ele é uma extensão do WSL 2 e não é necessário instalar nada adicional, basta ter o WSL 2 instalado e atualizado.

Com ele é possível rodar aplicações como Chrome, Firefox, Gedit, IDEs (VSCode, JetBrains) e até aplicações gráficas feitas em Java, Python e etc.

### Arquitetura do WSLg

O WSLg é composto pelos componentes: Wayland, Weston, PulseAudio e CBL-Mariner.

Basicamente teremos o Wayland como servidor gráfico, o Weston como compositor, o PulseAudio para áudio e o CBL-Mariner como distribuição Linux para rodar as aplicações gráficas.



### Como ativar o WSLg

Para ativar o WSLg, basta ter o WSL 2 instalado e atualizado. Não é necessário instalar nada adicional.

Quando instalar algum aplicativo que dependente de interface gráfica, o WSLg será ativado automaticamente. Vamos a um exemplo:

```bash
sudo apt-get update

sudo apt-get install gedit
```

Abra o Gedit no terminal do WSL 2 digitando `gedit` e ele será aberto no Windows.

Portanto basta instalar o aplicativo e lança-lo no terminal do WSL 2 para que ele seja aberto no Windows.


## O que é Docker

Docker é uma plataforma open source que possibilita o empacotamento de uma aplicação dentro de um container. Uma aplicação consegue se adequar e rodar em qualquer máquina que tenha essa tecnologia instalada.

### Porque usar WSL 2 + Docker para desenvolvimento

Configurar ambientes de desenvolvimento no Windows sempre foi burocrático e complexo, além do desempenho de algumas ferramentas não serem totalmente satisfatórias.

Com o nascimento do Docker este cenário melhorou bastante, pois podemos montar nosso ambiente de desenvolvimento baseado em Unix, de forma independente e rápida, e ainda unificada com outros sistemas operacionais.

Veja nossa **live sobre WSL 2 + Docker no canal Full Cycle**: [https://www.youtube.com/watch?v=O33trWxqVC4](https://www.youtube.com/watch?v=O33trWxqVC4).


## Modos de usar Docker no Windows

* 1. *Obsoleto* [Docker Toolbox](#obsoleto-docker-toolbox)
* 2. *Obsoleto* [Docker Desktop com Hyper-V](#obsoleto-docker-desktop-com-hyper-v).
* 3. [Docker Desktop com WSL2](#docker-desktop-com-wsl2).
* 4. [Docker Engine (Docker Nativo) diretamente instalado no WSL2](#docker-engine-docker-nativo-diretamente-instalado-no-wsl2).

### 1. (Obsoleto) Docker Toolbox

Roda em cima do programa de virtualização de sistemas da Oracle, chamado de **VirtualBox**.
O desempenho do Docker Toolbox pode ser muito ruim, inviabilizando seu uso.

Pode ainda ser usado em Windows mais antigos, como XP, Vista, 7, 8 e 8.1.

### 2. (Obsoleto) Docker Desktop com Hyper-V

Roda em cima do **Hyper-V** da Microsoft em vez de usar o VirtualBox usando pelo Docker Toolbox. O Docker Desktop com Hyper-V necessita da versão **PRO** do Windows 10/11, portanto é necessário compra-la se você não a tem.

O Hyper-V costuma requerer muitos recursos da máquina e apesar do desempenho ser melhor que o Docker Toolbox, a máquina pode ficar lenta para se utilizar outras coisas no Windows.

### 3. Docker Desktop com WSL2

> Fizemos um overview completo do Docker Desktop, inclusive para outros sistemas operacionais também, veja [https://www.youtube.com/watch?v=99dCerRKO6s](https://www.youtube.com/watch?v=99dCerRKO6s)

Roda em cima do **Virtual Machine Platform** que é um componente do Hyper-V e Se integra com o WSL2 permitindo rodar o Docker dentro do ambiente do Linux. 

Não é necessário adquirir licença PRO do Windows 10/11.

Tem um grande desempenho e consome menos recursos quando comparado ao Docker Toolbox ou Docker Desktop com Hyper-V. 

#### <a id="docker-desktop-vantagens"></a> Vantagens

* Tem uma ferramenta visual para administrar o Docker.
* Permite instalar extensões para usar ferramentas diretas no Docker.
* Permite rodar um cluster Kubernetes localmente de forma fácil.
* Simplifica a configuração do Docker tanto no Windows quanto no WSL 2.
* Permite rodar o Docker fora do WSL 2, sendo possível usar qualquer shell como PowerShell ou DOS.
* Suporta containers em modo Windows (Imagens que contém Windows por debaixo dos panos ao invés de Linux).
* Como rodar outra instância de Linux separada da que usamos, implementa um ambiente de desenvolvimento mais isolado e mais segurança.
* Cria um ambiente centralizado para armazenamento de imagens, volumes e outras configurações Docker. Pode-se ter várias distribuições do WSL 2 rodando a mesma instância do Docker.

#### <a id="docker-desktop-desvantagens"></a> Desvantagens

* Uso de memória inicial sem rodar nenhum container Docker é de 1GB ou mais.
* Pode ser necessário reiniciar o Docker Desktop para que ele funcione corretamente em algumas situações.
* Tende a consumir mais recursos da máquina que o Docker Engine diretamente instalado no WSL 2.

### 4. Docker Engine (Docker Nativo) diretamente instalado no WSL2

O Docker Engine é o Docker nativo (como foi criado) que roda no ambiente Linux e completamente suportado para WSL 2. Sua instalação é idêntica a descrita para as próprias distribuições Linux disponibilizadas no site do [Docker](https://docs.docker.com/engine/install/ubuntu/).

É a maneira pura de usar o Docker no Linux.

#### <a id="docker-engine-vantagens"></a> Vantagens

* Consume menos memória para rodar o Docker Daemon (servidor do Docker) quando comparado ao Docker Desktop.
* Traz a experiência mais pura de usar o Docker no Linux.

#### <a id="docker-engine-desvantagens"></a> Desvantagens

* Se necessitar executar o Docker em outra instância do WSL 2, é necessário instalar novamente o Docker nesta instância ou configurar o acesso ao socket do Docker desejado para compartilhar o Docker entre as instâncias.
* Não suporta containers no modo Windows.
* Por enquanto o tamanho do VHDX (disco virtual onde é montando o Linux) não diminui automaticamente usando o modo sparse do WSL (modo compactação automática) quando se exclui os artefatos do Docker (containers, imagens, volumes, layers). Dependendo do tamanho do disco virtual, pode ser necessário compacta-lo manualmente de tempos em tempos.
* Pode trazer mais riscos de segurança ao Linux, pois o Docker Engine é um software que roda diretamente no Linux e ao rodar imagens de terceiros, pode haver riscos de segurança.

## Qual modo de usar Docker no Windows escolher?

As 2 primeiras opções são obsoletas e não recomendamos seu uso. As 2 últimas opções são as mais recomendadas.

O uso do **Docker Desktop** como explicado na seção [Docker Desktop com WSL2](#3-docker-desktop-com-wsl2) é recomendado para a maioria dos usuários, pois é mais fácil de usar e tem uma interface gráfica para administrar o Docker, entretanto consome mais recursos da máquina, principalmente memória RAM. Com 8GB, o Docker Desktop pode não ser a melhor opção. Pode ser que 16GB pode ser o ideal para rodar o Docker Desktop, na sua máquina.

Você pode testar o Docker Desktop e se não gostar, se ver que está consumindo muitos recursos, pode desinstala-lo e instalar o Docker Engine diretamente no WSL 2.
O Docker Desktop tem um indicador de uso de memória RAM e CPU, acompanhe-o durante alguns dias para ver se está consumindo muitos recursos. Mais abaixo, vamos mostrar como otimizar os recursos consumidos pelo Docker Desktop, usando o Resource Save Mode.

## Instalação do Docker

### 1 - Instalar o Docker com Docker Desktop

Baixe neste link: [https://www.docker.com/products/docker-desktop/](https://www.docker.com/products/docker-desktop/) e instale o Docker Desktop.

Logo após a instalação, será pedido para logar com sua conta do Docker. Faça o login (crie uma conta se não tiver) e siga as instruções.

Ao final da instalação, o Docker Desktop estará instalado e rodando. Você pode ver o ícone do Docker perto do relógio do Windows. Ele ficará rodando em segundo plano. A interface do Docker Desktop deverá ficar assim:



Podemos ver agora que há 2 distribuições Linux rodando no WSL 2, uma é a distribuição padrão do Ubuntu (ou a que você instalou) e a outra é a distribuição do Docker Desktop. Rode o comando `wsl -l -v` para ver as distribuições Linux instaladas e seu status atual.



#### Ativar o Docker na distribuição Linux

Para o Docker funcionar na sua distribuição Linux, você precisa ativa-lo no painel do Docker Desktop. Abra a interface do Docker Desktop, clique no ícone de engrenagem no canto superior direito, vá em `Resources -> WSL Integration` e habilite a distribuição Linux que você deseja usar o Docker, e clique em `Apply & Restart`, conforme a imagem abaixo:



#### Otimizar recursos do Docker Desktop

Existe um recurso no Docker Desktop chamado **Resource Save Mode** que otimiza o uso de recursos da máquina. Ele diminui o uso de memória RAM e CPU quando o Docker Desktop não está sendo usado.

De tempos em tempos, o Docker Desktop vai analisar já há containers rodando e se não houver, ele vai diminuir o uso de recursos da máquina.

Ative-o, clicando no ícone de engrenagem no canto superior direito, vá em `Resources -> Advanced` e habilite a opção `Resource Save Mode`, conforme a imagem abaixo:



Você pode escolher de quanto em quanto tempo o Docker Desktop vai analisar se há containers rodando e diminuir o uso de recursos da máquina. O padrão é 5 min.

#### Aplicar autoMemoryReclaim no WSL 2

Com o passar do tempo, o WSL pode consumir memória RAM e não liberar, é feito cache de memória para melhorar o desempenho, mas podemos liberar esta memória depois de um tempo. Esta opção é chamada de `autoMemoryReclaim`, ela libera a memória RAM que não está sendo usada através de uma das 2 opções:

* gradual: Libera a memória RAM de forma gradual de 5 em 5 minutos.
* dropcache: Libera a memória RAM de forma imediata.

Para ativar o `autoMemoryReclaim`, edite o arquivo `.wslconfig`:

```conf
[experimental]
autoMemoryReclaim=gradual
```

Esta opção só funcionará após reiniciar o WSL com o comando `wsl --shutdown`.

> Não use esta opção se estiver usando o Docker Engine, porque isto causará problemas no Docker Engine. Utilize apenas se estiver usando o Docker Desktop ou se não tiver o Docker instalado.

### <a id="instalar-o-docker-com-docker-engine-docker-nativo"></a>2 - Instalar o Docker com Docker Engine (Docker Nativo)

A instalação do Docker no WSL 2 é idêntica a instalação do Docker em sua própria distribuição Linux, portanto se você tem o Ubuntu é igual ao Ubuntu, se é Fedora é igual ao Fedora. A documentação de instalação do Docker no Linux por distribuição está [aqui](https://docs.docker.com/engine/install/), mas vamos ver como instalar no Ubuntu.


> **Quem está migrando de Docker Desktop para Docker Engine, temos duas opções**
> 1. Desinstalar o Docker Desktop.
> 2. Desativar o Docker Desktop Service nos serviços do Windows. Esta opção permite que você utilize o Docker Desktop, se necessário, para a maioria dos usuários a desinstalação do Docker Desktop é a mais recomendada.
>Se você escolheu a 2º opção, precisará excluir o arquivo ~/.docker/config.json e realizar a autenticação com Docker novamente através do comando "docker login"

> **Se necessitar integrar o Docker com outras IDEs que não sejam o VSCode**
>
> O VSCode já se integra com o Docker no WSL desta forma através da extensão Remote WSL ou Remote Container.
> 
> É necessário habilitar a conexão ao servidor do Docker via TCP. Vamos aos passos:
> 1. Crie o arquivo /etc/docker/daemon.json: `sudo echo '{"hosts": ["tcp://0.0.0.0:2375", "unix:///var/run/docker.sock"]}' > /etc/docker/daemon.json`
> 2. Reinicie o Docker: `sudo service docker restart`
> 
> Após este procedimento, vá na sua IDE e para conectar ao Docker escolha a opção TCP Socket e coloque a URL `http://IP-DO-WSL:2375`. Seu IP do WSL pode ser encontrado com o comando `cat /etc/resolv.conf`.
> 
> Se caso não funcionar, reinicie o WSL com o comando `wsl --shutdown` e inicie o serviço do Docker novamente.

> **Para outras distribuições Linux**
>
> Se você estiver usando uma distribuição diferente do Ubuntu, veja os comandos de instalação no documentação do Docker [https://docs.docker.com/engine/install/](https://docs.docker.com/engine/install/)

Execute os comandos:

```
sudo apt update
sudo apt install ca-certificates curl
sudo install -m 0755 -d /etc/apt/keyrings
sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
sudo chmod a+r /etc/apt/keyrings/docker.asc

sudo tee /etc/apt/sources.list.d/docker.sources <<EOF
Types: deb
URIs: https://download.docker.com/linux/ubuntu
Suites: $(. /etc/os-release && echo "${UBUNTU_CODENAME:-$VERSION_CODENAME}")
Components: stable
Signed-By: /etc/apt/keyrings/docker.asc
EOF

sudo apt update

sudo apt install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
```

Dê permissão para rodar o Docker com seu usuário corrente:

```
sudo usermod -aG docker $USER
```

Reiniciar o WSL via linha de comando do Windows para que não seja necessário autorização root para rodar o comando docker:

```
wsl --shutdown
```

O serviço Docker inicia automaticamente após a instalação. Para verificar se o Docker está em execução acessar novamente o Ubuntu e utilize:

```
 sudo service docker status
```

Alguns sistemas podem ter esse comportamento desativado e exigirão uma inicialização manual:

```
 sudo service docker start
```

Este comando acima terá que ser executado toda vez que o Linux for reiniciado. Se caso o serviço do Docker não estiver executando, mostrará esta mensagem de erro ao rodar comando `docker`:

```
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
```

Por fim, verifique se a instalação foi bem-sucedida executando a imagem `hello-world`:

```
sudo docker run hello-world
```

E aparecerá em seu terminal:

```
"Hello from Docker!
This message shows that your installation appears to be working correctly..."
```

#### Erro ao iniciar o Docker no Ubuntu 22.04

> Se mesmo ao iniciar o serviço do Docker acontecer o seguinte erro ou similar:
>
> `Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?`
> Rode o comando `sudo update-alternatives --config iptables` e escolha a opção 1 `iptables-legacy`
>
> Rode novamente o `sudo service docker start`. Rode algum comando Docker como `docker ps` para verificar se está funcionando corretamente. Se não mostrar o erro acima, está ok.


#### Iniciar o Docker automaticamente no WSL

> **Apenas para Windows 11 ou Windows 10 com o update KB5020030**

É possível especificar um comando padrão para ser executados sempre que o WSL for iniciado, isto permite que já coloquemos o serviço do docker para iniciar automaticamente. Edite o arquivo `/etc/wsl.conf`:

Rode o comando para editar:

```conf
sudo vim /etc/wsl.conf
```

Aperte a letra `i` (para entrar no modo de inserção de conteúdo) e cole o conteúdo:

```conf
[boot]
command = service docker start
```

#### Docker com Systemd

Caso tenha ativado o systemd, na maioria dos casos o Docker iniciará automaticamente, portanto se você se tem a linha `command = service docker start` no `/etc/wsl.conf`, comente-a com `#` e reinicie o WSL com o comando `wsl --shutdown`.

Caso contrário, você pode inicia-lo automaticamente usando os comandos:

```bash
sudo systemctl enable docker.service
sudo systemctl enable containerd.service
```

É necessário reiniciar o WSL com o comando `wsl --shutdown` para que as mudanças tenham efeito.

Pronto, basta reiniciar o WSL com o comando `wsl --shutdown` no DOS ou PowerShell para testar. Após abrir o WSL novamente, digite o comando `docker ps` para avaliar se o comando não retorna a mensagem acima: `Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?`

## Dicas e truques básicos com WSL 2

### Performance ao usar o WSL 2

A performance do WSL 2 está em se executar tudo dentro do Linux, por isso evite executar seus projetos com ou sem Docker do caminho `/mnt/c`, pois você perderá performance. O ideal é executar tudo dentro do Linux, no caminho `/home/seu_usuario`.

A ideia é você pegar todos os seus projetos que estão no C: e copia-los para o Linux, no `/home/seu_usuario`. Assim, tudo estará dentro do Linux e a performance será melhor.

A princípio a ideia de fazer tudo no Linux pode parecer estranha, mas é a melhor forma de se obter performance com o WSL 2.

### Windows Terminal

O Windows Terminal é um terminal que agrega vários terminais em uma única janela, como PowerShell, CMD e WSL. Ele permite personalização de cores, temas, atalhos e muito mais.

Instale-o pelo Windows Store.

A experiência de usar o Windows Terminal é muito melhor que o terminal padrão do Windows, use ele para desenvolver no Windows e também para acessar o WSL 2.

### Acessar disco e outros dispositivos do Windows

O WSL 2 tem acesso a todo o disco rígido do Windows, basta acessar o caminho `/mnt/c` para acessar o disco C: do Windows. Se você tiver mais discos, eles estarão disponíveis em `/mnt/d`, `/mnt/e`, etc.

O `/mnt` é um ponto de montagem do Linux, onde ele monta os dispositivos do Windows.



### Acessar o WSL 2 pelo Windows

É possível acessar o WSL 2 pelo Windows Explorer, basta digitar `\\wsl.localhost$` na barra de endereços e será mostrado as distribuições Linux instaladas no WSL 2.

Também é possível acessar pelo ícone `Linux` que fica do lado esquerdo do Windows Explorer. Talvez sua versão do Windows não tenha este ícone, então use o caminho `\\wsl.localhost$`.



Também é possível de dentro do Linux abrir uma pasta no Windows Explorer, basta digitar o comando `explorer.exe .` e a pasta atual será aberta no Windows Explorer.

### Integração com VSCode

O Visual Studio Code tem uma extensão chamada **Remote - WSL** que permite acessar o WSL 2 diretamente do VSCode. Com esta extensão, você pode editar seus arquivos diretamente no WSL 2, rodar comandos, instalar extensões e muito mais.

Veja mais sobre esta extensão em [Remote - WSL](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-wsl).

Ao abrir um projeto que está dentro do Linux, é importante que o modo WSL do VSCode esteja ativado. No canto inferior esquerdo do VSCode, clique no botão `><` e selecione `Connect to WSL`. Isto irá conectar o VSCode ao WSL 2 e então poderá abrir o projeto que está dentro do Linux. Você verá que o botão `><` mudará para `WSL: Ubuntu`.



Se o VSCode não estiver desta forma ao abrir projetos dentro do Linux, então o modo WSL não estará ativado e você perderá performance ao editar arquivos dentro do Linux, além de não ter suporte para algumas extensões.

Outra forma de abrir o projeto no modo WSL, é acessando a pasta do projeto no terminal do WSL e digitando `code .`. Isto abrirá o VSCode no modo WSL.

### Executáveis do Windows no WSL 2

É possível executar executáveis do Windows no WSL 2, basta digitar o caminho completo do executável do Windows no terminal do WSL 2. Por exemplo, para executar o executável `notepad.exe` do Windows, basta digitar `notepad.exe` no terminal do WSL 2.



### Listando as distribuições Linux instaladas no WSL 2

Para listar as distribuições Linux instaladas no WSL 2, execute o comando `wsl -l -v` no terminal do Windows.

### Parando todas as distribuições Linux no WSL 2

Para parar todas as distribuições Linux que estão rodando no WSL 2, execute o comando `wsl --shutdown` no terminal do Windows.

Se você quiser parar somente uma distribuição Linux específica, execute o comando `wsl --t <distribution name>`.



> Se estiver usando o Docker Desktop, ao executar o comando `wsl --shutdown`, o Docker Desktop irá parar também e será necessário reinicia-lo novamente.

* É possível executar algumas aplicações gráficas do Linux com WSL 2. Leia este tutorial: [https://medium.com/@dianaarnos/aplica%C3%A7%C3%B5es-gr%C3%A1ficas-no-wsl2-e0a481e9768c](https://medium.com/@dianaarnos/aplica%C3%A7%C3%B5es-gr%C3%A1ficas-no-wsl2-e0a481e9768c).
* Execute o comando ```wsl -l -v``` com o PowerShell para ver as versões de Linux instaladas e seu status atual(parado ou rodando).

### Backup e restauração de distribuições Linux no WSL 2

É possível fazer backup e restauração de distribuições Linux no WSL 2. Isto é interessante, porque tudo que você estiver fazendo no Linux, como instalação de pacotes, configurações, etc, estará salvo no backup e poderá ser restaurado onde quiser.

Para fazer backup de uma distribuição Linux, execute o comando:

```bash
wsl --export Ubuntu C:\caminho\backup.vhdx --vhd
```

Onde `Ubuntu` é o nome da distribuição Linux que você quer fazer backup e `C:\caminho\backup.vhdx` é o caminho onde o backup será salvo. A opção `--vhd` é para salvar o backup em formato VHD, isto facilitar a restauração e ainda é possível monta-lo como um disco rígido no Windows, se quiser.

Dependendo do tamanho do disco virtual, o backup pode demorar um pouco.

Para restaurar uma distribuição Linux, execute o comando:

```bash
wsl --import-in-place Ubuntu C:\caminho\backup.vhdx
```

Onde `Ubuntu` é o nome da distribuição Linux (pode ser o nome que você quiser) que você quer restaurar e `C:\caminho\backup.vhdx` é o caminho onde o backup foi salvo.

Normalmente os VHDX são salvos em `C:\Users\<seu_usuario>\AppData\Local\Packages\CanonicalGroupLimited...\LocalState\`, mas, uma vez que você tenho restaurado a distribuição Linux, você pode mover o VHDX para onde quiser. Será o caminho que você passar no comando `wsl --import-in-place`. 


### Compactação do disco virtual do WSL 2

O disco virtual do WSL 2 é um arquivo VHDX que cresce conforme você vai usando o Linux. Se você excluir arquivos, o disco virtual não diminuirá automaticamente, ele continuará com o mesmo tamanho. 

Para diminuir ative o modo `sparse` do WSL 2, que é a compactação automática do disco virtual. Para ativar, edite o arquivo `.wslconfig`:

```conf
[wsl2]
sparseVhd=true
```

Esta opção só funcionará para novos discos virtuais.

Para os discos virtuais já criados, execute o comando:

```bash
wsl --manage "Ubuntu" --set-sparse true
wsl --manage "docker-desktop" --set-sparse true # Se estiver usando o Docker Desktop
```

Isto irá converter o disco virtual para o modo sparse, que é a compactação automática do disco virtual.

Antes de executar o comando, verifique se a distribuição Linux está parada, execute o comando `wsl --shutdown` para parar todas as distribuições Linux.

Se você já tinha uma distribuição antiga e após aplicar o modo sparse, o disco virtual não diminuiu, você pode compacta-lo manualmente.

Use a ferramenta [wslcompact](https://github.com/okibcn/wslcompact) para realizar este procedimento. Basicamente esta ferramenta será um executável ativo no `PowerShell` e ao executá-lo ele irá exportar e importar o disco virtual, forçando o WSL a compacta-lo.

Execute o comando:

```bash
wslcompact -c Ubuntu
```

Será gerado um novo disco virtual chamado de `ext4.vhdx` que será sua distribuição compactada. Quando o executável pedir para registrar o disco, coloque `Y` e pressione `Enter`, isto não fará ele registrar, você deverá fazer isto manualmente como foi mostrado na seção de backup e restauração deste tutorial.

Remova o disco antigo com o comando `wsl --unregister Ubuntu` e registre o novo disco com o comando `wsl --import-in-place Ubuntu C:\caminho\ext4.vhdx`.

> Cuidado: Faça um backup da sua distribuição Linux antes de compacta-la, pois você pode cometer um erro e perder seu Linux.


### Rede em modo LAN e VPN

Como o WSL é virtualizado, há uma outra interface de rede, por isso se você usa rede LAN (cabeada), ao rodar aplicações e tentar acessar pelo navegador, por exemplo, você não conseguirá acessar. Seria necessário ficar fazendo binding de portas o que não seria produtivo.

Eventualmente, podemos ter problemas com VPNs, pois o WSL 2 tem uma interface de rede própria e a VPN pode não funcionar corretamente.

Para resolver isto, ative o modo `mirrored` da rede do WSL 2, que fará com que a interface de rede do WSL 2 seja a mesma do Windows. Edite o arquivo `.wslconfig`:

```conf
[wsl2]
networkingMode=mirrored
```

Esta opção só funcionará após reiniciar o WSL com o comando `wsl --shutdown`.

Esta opção ajuda a melhorar a experiência com o uso de VPNs.

### Ativar BuildKit no Docker

> **Apenas para Docker Engine**

Acrescente `export DOCKER_BUILDKIT=1` no final do arquivo `.profile` do seu usuário do Linux ou em seu arquivo de terminal personalizado para ganhar mais performance ao realizar builds com Docker. Execute o comando `source ~/.profile` para carregar esta variável de ambiente no ambiente do seu WSL 2.

### Iniciar o Docker automaticamente no WSL 2

> **Apenas para Windows 11 ou Windows 10 com o update KB5020030**
> **Apenas para Docker Engine**
> **Apenas para quem não ativou o systemd**

É possível especificar um comando padrão para ser executados sempre que o WSL for iniciado, isto permite que já coloquemos o serviço do docker para iniciar automaticamente. Edite o arquivo `/etc/wsl.conf`:

Rode o comando para editar:

```conf
sudo vim /etc/wsl.conf
```

Aperte a letra `i` (para entrar no modo de inserção de conteúdo) e cole o conteúdo:

```conf
[boot]
command = service docker start
```

### Liberar memória RAM do WSL 2

Se verificar que o WSL 2 está consumindo muitos recursos da máquina, execute o seguinte comando dentro do terminal WSL 2 para liberar memória RAM:

```bash
echo 1 | sudo tee /proc/sys/vm/drop_caches
```

Este método é agressivo, porque libera instantaneamente a memória RAM, mas pode ser necessário em alguns casos.

> Não use a opção abaixo opção se não estiver usando o Docker Engine. Pode ser utilizado com o Docker Desktop ou se não tiver o Docker instalado.

O WSL possui um recurso chamado `autoMemoryReclaim` que libera a memória RAM que não está sendo usada de forma automática. 

Há 2 opções para o `autoMemoryReclaim`:

* gradual: Libera a memória RAM de forma gradual de 5 em 5 minutos.
* dropcache: Libera a memória RAM de forma imediata.

Edite o arquivo `.wslconfig`:

```conf
[experimental]
autoMemoryReclaim=gradual
```

Caso queria uma opção de liberação de memória automática e estiver usando o Docker Engine, coloque o seguinte script para rodar no WSL: [https://gist.github.com/craigloewen-msft/496078591e0bbbfdec9f144c6b50a8cc](https://gist.github.com/craigloewen-msft/496078591e0bbbfdec9f144c6b50a8cc). Por padrão, ele vai rodar de 2 em 2 minutos, mas você pode alterar o tempo de execução.

### Arquivos .wslconfig e wsl.conf

O arquivo `.wslconfig` é um arquivo de configuração global, ou seja, ele afetará todas as distribuições Linux que você tiver instalado no WSL 2, porque você pode ter mais de uma distribuição Linux instalada no WSL 2, como um Ubuntu, um Debian, um Fedora, etc.

O arquivo `wsl.conf` é um arquivo de configuração específico de uma distribuição Linux, ou seja, ele afetará somente a distribuição Linux que você especificar no arquivo `wsl.conf`.

Existem algumas opções que podem ser usadas no arquivo `.wslconfig` e `wsl.conf`, veja a documentação oficial [https://docs.microsoft.com/pt-br/windows/wsl/wsl-config](https://docs.microsoft.com/pt-br/windows/wsl/wsl-config).

> Estas opções pode ajudar em como o WSL 2 se comporta, como alocar mais memória RAM, mais CPUs, etc. As configurações mais básicas já foram mostradas na parte de instalação do WSL, na parte de instalação do Docker e também nesta seção de Dicas e trues.

Esta opção só funcionará após reiniciar o WSL com o comando `wsl --shutdown`.

### Expandir o disco virtual do WSL 2

Por padrão o disco virtual do WSL 2 é de 1TB, mas se você precisar de mais espaço, é possível expandir o disco virtual. 

Uma maneira simples de verificar o tamanho do disco é rodar o seguinte comando no PowerShell ou DOS:

```bash
wsl --system -d <distribution-name> df -h /mnt/wslg/distro
```

Utilize o `diskpart` do Windows para expandir o tamanho dele, siga este tutorial: [https://learn.microsoft.com/en-us/windows/wsl/disk-space#how-to-expand-the-size-of-your-wsl-2-virtual-hard-disk](https://learn.microsoft.com/en-us/windows/wsl/disk-space#how-to-expand-the-size-of-your-wsl-2-virtual-hard-disk)


## Dúvidas

### Preciso de uma licença PRO do Windows 10/11 para usar o WSL 2?

Não, o WSL 2 é suportado em todas as versões do Windows 10/11, desde que estejam atualizadas.

### Posso continuar desenvolvendo no Windows sem usar o WSL 2?

Sim, você pode continuar desenvolvendo no Windows sem usar o WSL 2, mas o WSL 2 traz uma experiência de desenvolvimento mais próxima do Linux, com melhor desempenho e mais recursos.

A não ser que você tenha uma necessidade específica de desenvolver no Windows, como desenvolver aplicações usando .Net, por exemplo, provavelmente sua aplicação rodará no Linux, então, o WSL 2 é a melhor opção quando se quer continuar a usar o Windows, usando Linux, mas sem dual boot ou máquina virtual.

### O WSL 2 funciona junto com outras máquinas virtuais como VirtualBox ou VMWare?

O WSL 2 funciona junto com outras máquinas virtuais como **VirtualBox** ou **VMWare**? Siga a [referência](https://learn.microsoft.com/pt-br/windows/wsl/faq#poderei-executar-o-wsl-2-e-outras-ferramentas-de-virtualiza--o-de-terceiros--como-vmware-ou-virtualbox-)

### É possível acessar aplicações rodando no WSL 2 pelo Windows?

Sim, é possível acessar aplicações rodando no WSL 2 pelo Windows, basta acessar o endereço `localhost` no navegador do Windows. O WSL 2 tem uma interface de rede própria e o Windows consegue acessar aplicações rodando no WSL 2.

### É possível rodar aplicações gráficas no WSL 2?

Sim, este o projeto WSLg (Windows Subsystem for Linux GUI) que permite rodar aplicações gráficas no WSL 2. Veja mais sobre isto no topo do tutorial

### Posso usar o WSL em cenários de produção?

O WSL é uma ferramenta de desenvolvimento e não é recomendado para uso em produção.

### Posso rodar o Docker Engine junto com o Docker Desktop?

Não, só é possível rodar um de cada vez. É até possível ter os dois instalados, mas só um pode ser executado por vez.

### Dúvidas sobre o Docker Desktop

Fizemos um overview completo do Docker Desktop, inclusive para outros sistemas operacionais também, veja [https://www.youtube.com/watch?v=99dCerRKO6s](https://www.youtube.com/watch?v=99dCerRKO6s)

### Quer configurar um ambiente mais produtivo no Windows?

Acesse os tutorias abaixo:

- Configuração de ambiente de desenvolvimento produtivo: [https://github.com/argentinaluiz/ambiente-dev-produtivo](https://github.com/argentinaluiz/ambiente-dev-produtivo)
- Como montar um ambiente produtivo no VSCode: [https://github.com/argentinaluiz/my-vscode-settings](https://github.com/argentinaluiz/my-vscode-settings)

---

## File: README.en.md

# WSL2 + Docker Quick Guide/Tutorial

*Read this in other language: [Portuguese](README.md)

## Summary


  
    **WSL**
  

  * [What is WSL2](#what-is-wsl2)
  * [Minimum Requirements](#minimum-requirements)
  * [Installation of WSL 2](#installation-of-wsl-2)
    * [Windows Update](#windows-update)
    * [Update WSL](#update-wsl)
    * [(Optional) Enabling WSL on older versions of Windows 10](#optional-enabling-wsl-on-older-versions-of-windows-10)
    * [Set the default version of WSL to version 2](#set-the-default-version-of-wsl-to-version-2)
    * [Install Ubuntu](#install-ubuntu)
    * [(Optional) Change the version of a Linux distribution from WSL 1 to WSL 2](#optional-change-the-version-of-a-linux-distribution-from-wsl-1-to-wsl-2)
    * [Installation of WSL 2 via Microsoft Store (alternative)](#installation-of-wsl-2-via-microsoft-store-alternative)
    * [Integration with VSCode](#integration-with-vscode)
  * [Windows Terminal as the default development terminal for Windows](#windows-terminal-as-the-default-development-terminal-for-windows)
  * [What WSL 2 Can Use from Your Machine's Resources](#what-wsl-2-can-use-from-your-machines-resources)
  * [Systemd](#systemd)



  
    **WSLg**
  

  * [What is WSLg](#what-is-wslg)
  * [WSLg Architecture](#wslg-architecture)
  * [How to Activate WSLg](#how-to-activate-wslg)



  
    **Docker**
  

  * [What is Docker](#what-is-docker)
  * [Why Use WSL 2 + Docker for Development](#why-use-wsl-2--docker-for-development)
  * [Ways to Use Docker on Windows](#ways-to-use-docker-on-windows)
    * [1. (Obsolete) Docker Toolbox](#1-obsolete-docker-toolbox)
    * [2. (Obsolete) Docker Desktop with Hyper-V](#2-obsolete-docker-desktop-with-hyper-v)
    * [3. Docker Desktop with WSL2](#3-docker-desktop-with-wsl2)
      * [Advantages](#docker-desktop-advantages)
      * [Disadvantages](#docker-desktop-disadvantages)
    * [4. Docker Engine (Native Docker) Directly Installed on WSL2](#4-docker-engine-native-docker-directly-installed-on-wsl2)
      * [Advantages](#docker-engine-advantages)
      * [Disadvantages](#docker-engine-disvantages)
  * [Which Docker Usage Mode to Choose on Windows?](#which-docker-usage-mode-to-choose-on-windows)
  * [Installing Docker](#installing-docker)
    * [1 - Install Docker with Docker Desktop](#1---install-docker-with-docker-desktop)
      * [Activate Docker in the Linux Distribution](#activate-docker-in-the-linux-distribution)
      * [Optimize Docker Desktop Resources](#optimize-docker-desktop-resources)
      * [Apply autoMemoryReclaim in WSL 2](#apply-automemoryreclaim-in-wsl-2)
    * [2 - Install Docker with Docker Engine (Docker Native)](#install-docker-using-docker-engine)
      * [Error Starting Docker on Ubuntu 22.04](#error-starting-docker-on-ubuntu-2204)
      * [Automatically Start Docker in WSL](#automatically-start-docker-in-wsl)
      * [Docker with Systemd](#docker-with-systemd)  
  



  
    **Basic Tips and Tricks with WSL 2**
  

  * [Basic Tips and Tricks with WSL 2](#basic-tips-and-tricks-with-wsl-2)
    * [Performance When Using WSL 2](#performance-when-using-wsl-2)
    * [Windows Terminal](#windows-terminal)
    * [Access Windows Disks and Other Devices](#access-windows-disks-and-other-devices)
    * [Access WSL 2 from Windows](#access-wsl-2-from-windows)
    * [Integration with VSCode](#integration-with-vscode-1)
    * [Running Windows Executables in WSL 2](#running-windows-executables-in-wsl-2)
    * [Listing Installed Linux Distributions in WSL 2](#listing-installed-linux-distributions-in-wsl-2)
    * [Stopping All Linux Distributions in WSL 2](#stopping-all-linux-distributions-in-wsl-2)
    * [Backup and Restore Linux Distributions in WSL 2](#backup-and-restore-linux-distributions-in-wsl-2)
    * [Compressing the WSL 2 Virtual Disk](#compressing-the-wsl-2-virtual-disk)
    * [LAN and VPN Network Mode](#lan-and-vpn-network-mode)
    * [Enabling BuildKit in Docker](#enabling-buildkit-in-docker)
    * [Automatically Start Docker in WSL 2](#automatically-start-docker-in-wsl-2)
    * [Releasing RAM Memory from WSL 2](#releasing-ram-memory-from-wsl-2)
    * [.wslconfig and wsl.conf Files](#wslconfig-and-wslconf-files)
    * [Expanding the WSL 2 Virtual Disk](#expanding-the-wsl-2-virtual-disk)
  



  FAQ

  * [FAQs](#faqs)
    * [Do I need a Windows 10/11 Pro license to use WSL 2?](#do-i-need-a-windows-1011-pro-license-to-use-wsl-2)
    * [Can I continue developing on Windows without using WSL 2?](#can-i-continue-developing-on-windows-without-using-wsl-2)
    * [Does WSL 2 work alongside other virtual machines like VirtualBox or VMWare?](#does-wsl-2-work-alongside-other-virtual-machines-like-virtualbox-or-vmware)
    * [Can I access applications running in WSL 2 from Windows?](#can-i-access-applications-running-in-wsl-2-from-windows)
    * [Can I run graphical applications in WSL 2?](#can-i-run-graphical-applications-in-wsl-2)
    * [Can I use WSL in production scenarios?](#can-i-use-wsl-in-production-scenarios)
    * [Can I run Docker Engine alongside Docker Desktop?](#can-i-run-docker-engine-alongside-docker-desktop)
    * [Questions about Docker Desktop](#questions-about-docker-desktop)
    * [Want to set up a more productive environment on Windows?](#want-to-set-up-a-more-productive-environment-on-windows)
    


## What is WSL2

In 2016, Microsoft announced the possibility of running Linux inside Windows 10 as a subsystem, and this was named **WSL** or **Windows Subsystem for Linux**.

Accessing the file system in Windows 10 from Linux was simple and fast, but we did not have a complete execution of the Linux kernel, among other native artifacts, which made it impossible to perform several tasks on Linux, one of them being Docker.

In 2019, Microsoft announced **WSL 2**, with an improved dynamic compared to the 1st version:

* Execution of the complete Linux kernel.
* Better performance for accessing files within Linux.
* Full system call compatibility.

WSL 2 was officially released on **May 28, 2020**.

With WSL 2, it is possible to run Docker and other tools that depend on the Linux Kernel using Windows 10/11.

Compare WSL versions: [https://docs.microsoft.com/en-us/windows/wsl/compare-versions](https://docs.microsoft.com/en-us/windows/wsl/compare-versions)

## Minimum Requirements

* **Windows 10 Home or Professional**
  - Version 2004 or higher (Build 19041 or higher).
  - Older versions require manual installation of WSL 2. See tutorial [https://learn.microsoft.com/en-us/windows/wsl/install-manual](https://learn.microsoft.com/en-us/windows/wsl/install-manual).

* **Windows 11 Home or Professional**
  - Version 22000 or higher (any Windows 11).

* A machine compatible with virtualization (check availability according to your processor brand. If your machine is older, it may be necessary to enable it in the BIOS).

* At least 4GB of RAM (8GB recommended).

Your Windows is probably already on the supported version, but check this by going to `All Settings > System > About`. If it is not, use the Windows Update Assistant to update your Windows version.

> **It is essential to keep Windows updated, as WSL 2 depends on an updated version of Hyper-V. Check Windows Update.**

## Installation of WSL 2

All instructions below are for Windows 10/11.

### Windows Update

Make sure your Windows is updated, as WSL 2 depends on an updated version of Hyper-V. Check Windows Update.

### Update WSL

With Windows 10 version 2004 or any version of Windows 11, WSL will already be present on your machine. To ensure you're using the latest version of WSL, run:

```bash
wsl --update
```

---

### (Optional) Enabling WSL on older versions of Windows 10

On older versions of Windows 10, WSL 2 is not enabled by default. Follow these steps:

1. Press `Win + R`, type `optionalfeatures` and press Enter.
2. In the "Windows Features" window, enable:

   - Windows Subsystem for Linux  
   - Virtual Machine Platform  
   - Hyper-V  

3. Click **OK** and restart your computer.

> These features are essential for WSL 2 to work and to avoid errors like `Could not start the operation because a required feature is not installed.`.

---

### Set the default version of WSL to version 2

Version 2 is usually the default, but version 1 of WSL might be the default. Run the command below to set version 2 as the default:

```bash
wsl --set-default-version 2
```

### Install Ubuntu

Run the command:

```bash
wsl --install
```

This command will install `Ubuntu` as the default Linux distribution.

If you want to install a different version of Ubuntu, run the command `wsl -l -o`. It will list all available Linux distributions. Install the chosen version with the command `wsl --install -d distribution-name`.

We suggest Ubuntu (without a version) because it is a popular distribution that comes with many useful development tools installed by default.

After the command completes, you will need to create a **username** (use a username without spaces or special characters) and a **password** (set a strong password). This password will be used to install packages and perform superuser operations.

To open a new Ubuntu window, just type `Ubuntu` in the start menu and click on the Ubuntu icon.

We recommend using the [Windows Terminal](https://docs.microsoft.com/en-us/windows/terminal/get-started) as the default terminal for development on Windows. It will aggregate the Ubuntu shell, as well as PowerShell and CMD, into a single window, and allow for color and theme customization.

### (Optional) Change the version of a Linux distribution from WSL 1 to WSL 2

If you already had WSL installed before and the distribution is using version 1, change it with:

```bash
wsl --set-version <distribution name> 2
```

This rarely happens, but some people already had WSL 1 installed before WSL 2 was released. If you don't know which version you're using, run the command:

```bash
wsl -l -v
```

Make sure the distribution you're using is on version 2. If not, run the command above to change the version.

---

Congratulations, your WSL2 is now up and running!



---

### Installation of WSL 2 via Microsoft Store (alternative)

It is also possible to install Linux distributions from the Microsoft Store. Just open the store and search for the desired distribution, such as `Ubuntu`, and click install.



### Integration with VSCode

Visual Studio Code has an extension called **Remote - WSL** that allows accessing WSL 2 directly from VSCode. With this extension, you can edit your files directly in WSL 2, run commands, install extensions, and much more.

Learn more about this extension at [Remote - WSL](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-wsl).

When opening a project located inside Linux, make sure that the WSL mode in VSCode is activated. In the bottom left corner of VSCode, click on the `><` button and select `Connect to WSL`. This will connect VSCode to WSL 2, allowing you to open the project inside Linux. You will see that the `><` button will change to `WSL: Ubuntu`.



If VSCode is not set this way when opening projects inside Linux, WSL mode will not be activated, and you will lose performance when editing files inside Linux, as well as support for some extensions.

Another way to open the project in WSL mode is by accessing the project folder in the WSL terminal and typing `code .`. This will open VSCode in WSL mode.

## Windows Terminal as the default development terminal for Windows

A deficiency that Windows has always had was providing an adequate terminal for development. Now we have the **Windows Terminal** built by Microsoft itself, which allows running terminals in tabs, changing colors and themes, configuring shortcuts, and much more.

Install it from the Windows Store.

See more configuration options at [More about Windows Terminal](https://docs.microsoft.com/en-us/windows/terminal/get-started).

By default, Windows Terminal will identify the main shells installed on Windows, such as PowerShell, CMD, and WSL.

## What WSL 2 Can Use from Your Machine's Resources

We can say that WSL 2 has almost complete access to your machine's resources. By default, it has access to:

* A 1TB hard disk. A 1TB virtual disk is created to store Linux files (this limit can be expanded, see the Tips and Tricks section).
* Full use of processing resources.
* 50% of the available RAM.
* 25% of the available SWAP (virtual memory).

If you want to customize these limits, create a file named `.wslconfig` at the root of your user folder `(C:\Users\<your_username>)` and define these settings:

```conf
[wsl2]
memory=8GB
processors=4
```

These are example limits and the most basic configurations to be used. Adjust them according to your available resources.

For more details, see Microsoft's documentation: [Configuration Settings for WSL](https://learn.microsoft.com/en-us/windows/wsl/wsl-config#configuration-setting-for-wslconfig). There are other configurations that can be made, such as network settings, VPN, memory release, etc.

To apply these settings, you need to restart the Linux distributions. Run the command: `wsl --shutdown` (This command will shut down all active WSL 2 instances, just open the terminal again to use them with the new settings).

This `.wslconfig` file is a global configuration file, meaning it will affect all Linux distributions you have installed in WSL 2, as you can have more than one Linux distribution installed in WSL 2, such as Ubuntu, Debian, Fedora, etc.

## Systemd

WSL is compatible with `systemd`. `Systemd` is an initialization and service management system widely used in modern Linux distributions. It allows you to use more complex tools on Linux like snapd, LXD, etc.

It is not mandatory to activate it, and it can be deactivated and reactivated at any time. However, we recommend keeping it activated because it will improve compatibility with Linux distributions, allowing you to use more tools and services like Kubernetes, etc. (It is not necessary for running Docker).

To activate it, edit the `/etc/wsl.conf` file:

Run the command to edit:

```bash
sudo vim /etc/wsl.conf
```

Press the `i` key (to enter insert mode) and paste the following content:

```conf
[boot]
systemd = true
```

When you finish editing, press `Esc`, then type `:` to enter the command `wq` (write and quit) and press `enter`.

Every time this change is made, it is necessary to restart WSL with the command `wsl --shutdown` in DOS or PowerShell.

## What is WSLg

WSLg is an extension of WSL 2 that allows running Linux graphical applications on Windows. It is an extension of WSL 2, and no additional installation is required, just have WSL 2 installed and updated.

With it, you can run applications such as Chrome, Firefox, Gedit, IDEs (VSCode, JetBrains), and even graphical applications made in Java, Python, etc.

### WSLg Architecture

WSLg is composed of the following components: Wayland, Weston, PulseAudio, and CBL-Mariner.

Basically, Wayland serves as the display server, Weston as the compositor, PulseAudio for audio, and CBL-Mariner as the Linux distribution to run graphical applications.



### How to Activate WSLg

To activate WSLg, just have WSL 2 installed and updated. No additional installation is necessary.

When you install an application that depends on a graphical interface, WSLg will be activated automatically. Let's look at an example:

```bash
sudo apt-get update

sudo apt-get install gedit
```

Open Gedit in the WSL 2 terminal by typing `gedit`, and it will open on Windows.

Therefore, just install the application and launch it in the WSL 2 terminal to open it on Windows.

## What is Docker

Docker is an open-source platform that enables the packaging of an application within a container. An application can adapt and run on any machine that has this technology installed.

### Why Use WSL 2 + Docker for Development

Setting up development environments on Windows has always been bureaucratic and complex, in addition to the performance of some tools not being entirely satisfactory.

With the advent of Docker, this scenario has greatly improved, as we can set up our development environment based on Unix, independently and quickly, while still being unified with other operating systems.

Check out our **live session on WSL 2 + Docker on the Full Cycle channel**: [https://www.youtube.com/watch?v=O33trWxqVC4](https://www.youtube.com/watch?v=O33trWxqVC4).

## Ways to Use Docker on Windows

* 1. *Obsolete* [Docker Toolbox](#obsoleto-docker-toolbox)
* 2. *Obsolete* [Docker Desktop with Hyper-V](#obsoleto-docker-desktop-com-hyper-v)
* 3. [Docker Desktop with WSL2](#docker-desktop-com-wsl2)
* 4. [Docker Engine (Native Docker) Directly Installed on WSL2](#docker-engine-docker-nativo-diretamente-instalado-no-wsl2)

### 1. (Obsolete) Docker Toolbox

Runs on Oracle's virtualization program, called **VirtualBox**.
The performance of Docker Toolbox can be very poor, making its use unfeasible.

It can still be used on older Windows versions, such as XP, Vista, 7, 8, and 8.1.

### 2. (Obsolete) Docker Desktop with Hyper-V

Runs on Microsoft's **Hyper-V** instead of using VirtualBox used by Docker Toolbox. Docker Desktop with Hyper-V requires the **PRO** version of Windows 10/11, so it is necessary to purchase it if you do not have it.

Hyper-V tends to require many machine resources and, although the performance is better than Docker Toolbox, the machine may become slow for other tasks on Windows.

### 3. Docker Desktop with WSL2

> We did a complete overview of Docker Desktop, including for other operating systems as well. Check it out [https://www.youtube.com/watch?v=99dCerRKO6s](https://www.youtube.com/watch?v=99dCerRKO6s)

Runs on **Virtual Machine Platform**, a component of Hyper-V, and integrates with WSL2, allowing Docker to run within the Linux environment.

No need to purchase a PRO license for Windows 10/11.

It has excellent performance and consumes fewer resources compared to Docker Toolbox or Docker Desktop with Hyper-V.

#### <a id="docker-desktop-advantages"></a> Advantages

* Has a visual tool to manage Docker.
* Allows installing extensions to use direct tools in Docker.
* Enables running a local Kubernetes cluster easily.
* Simplifies Docker configuration both on Windows and WSL 2.
* Allows running Docker outside of WSL 2, making it possible to use any shell like PowerShell or DOS.
* Supports Windows mode containers (Images that contain Windows under the hood instead of Linux).
* By running another separate Linux instance, it provides a more isolated development environment and increased security.
* Creates a centralized environment for storing images, volumes, and other Docker configurations. Multiple WSL 2 distributions can run the same Docker instance.

#### <a id="docker-desktop-disadvantages"></a> Disadvantages

* Initial memory usage without running any Docker container is 1GB or more.
* It may be necessary to restart Docker Desktop to function correctly in some situations.
* Tends to consume more machine resources than Docker Engine directly installed on WSL 2.

### 4. Docker Engine (Native Docker) Directly Installed on WSL2

Docker Engine is the native Docker (as it was created) that runs in the Linux environment and is fully supported for WSL 2. Its installation is identical to that described for the Linux distributions available on the [Docker site](https://docs.docker.com/engine/install/ubuntu/).

It is the purest way to use Docker on Linux.

#### <a id="docker-engine-advantages"></a> Advantages

* Consumes less memory to run the Docker Daemon (Docker server) compared to Docker Desktop.
* Provides the purest experience of using Docker on Linux.

#### <a id="docker-engine-disvantages"></a> Disadvantages

* If you need to run Docker in another WSL 2 instance, you need to install Docker again in that instance or configure access to the desired Docker socket to share Docker between instances.
* Does not support Windows mode containers.
* Currently, the size of the VHDX (virtual disk where Linux is mounted) does not automatically shrink using the sparse mode of WSL (automatic compression mode) when Docker artifacts (containers, images, volumes, layers) are deleted. Depending on the size of the virtual disk, it may be necessary to compact it manually from time to time.
* It may pose more security risks to Linux because Docker Engine is software that runs directly on Linux, and running third-party images may pose security risks.

## Which Docker Usage Mode to Choose on Windows?

The first two options are obsolete and not recommended. The last two options are the most recommended.

**Docker Desktop**, as explained in the [Docker Desktop with WSL2](#3-docker-desktop-com-wsl2) section, is recommended for most users because it is easier to use and has a graphical interface for managing Docker. However, it consumes more machine resources, particularly RAM. With 8GB of RAM, Docker Desktop may not be the best option. Having 16GB of RAM might be ideal for running Docker Desktop on your machine.

You can try Docker Desktop, and if you find it consuming too many resources, you can uninstall it and install Docker Engine directly on WSL 2 instead. Docker Desktop has a RAM and CPU usage indicator, so monitor it over a few days to see if it consumes too many resources. Below, we will show how to optimize the resources consumed by Docker Desktop using Resource Save Mode.

## Installing Docker

### 1 - Install Docker with Docker Desktop

Download it from this link: [https://www.docker.com/products/docker-desktop/](https://www.docker.com/products/docker-desktop/) and install Docker Desktop.

Immediately after installation, you'll be prompted to log in with your Docker account. Log in (create an account if you don't have one) and follow the instructions.

Once the installation is complete, Docker Desktop will be installed and running. You can see the Docker icon near the Windows clock. It will run in the background. The Docker Desktop interface should look like this:



You can now see that there are two Linux distributions running on WSL 2: one is the default Ubuntu distribution (or the one you installed), and the other is the Docker Desktop distribution. Run the command `wsl -l -v` to view the installed Linux distributions and their current status.



#### Activate Docker in the Linux Distribution

To make Docker work in your Linux distribution, you need to enable it in the Docker Desktop panel. Open the Docker Desktop interface, click on the gear icon in the upper right corner, go to `Resources -> WSL Integration`, enable the Linux distribution you want to use Docker with, and click `Apply & Restart`, as shown in the image below:



#### Optimize Docker Desktop Resources

Docker Desktop has a feature called **Resource Save Mode** that optimizes machine resource usage. It reduces RAM and CPU usage when Docker Desktop is not in use.

Occasionally, Docker Desktop will check for running containers, and if none are found, it will reduce resource usage.

Enable it by clicking on the gear icon in the upper right corner, going to `Resources -> Advanced`, and enabling the `Resource Save Mode` option, as shown in the image below:



You can choose how often Docker Desktop will check for running containers and reduce resource usage. The default is 5 minutes.

#### Apply autoMemoryReclaim in WSL 2

Over time, WSL may consume RAM and not release it; memory caching is done to improve performance, but this memory can be freed after a while. This option is called `autoMemoryReclaim`, which frees up unused RAM through one of two options:

* **gradual:** Frees RAM gradually every 5 minutes.
* **dropcache:** Frees RAM immediately.

To activate `autoMemoryReclaim`, edit the `.wslconfig` file:

```conf
[experimental]
autoMemoryReclaim=gradual
```

This option will only work after restarting WSL with the command `wsl --shutdown`.

> Do not use this option if you are using Docker Engine, as it will cause issues with Docker Engine. Use it only if you are using Docker Desktop or if Docker is not installed.

### <a id="install-docker-using-docker-engine"></a>2 - Install Docker with Docker Engine (Docker Native)

Installing Docker on WSL 2 is similar to installing Docker on any Linux distribution. For instance, if you have Ubuntu, the process is the same as for Ubuntu; if it's Fedora, it's the same as for Fedora. The Docker installation documentation for different Linux distributions is [here](https://docs.docker.com/engine/install/), but let’s see how to install it on Ubuntu.

> **For those migrating from Docker Desktop to Docker Engine, there are two options:**
> 1. Uninstall Docker Desktop.
> 2. Disable Docker Desktop Service in Windows services. This option allows you to use Docker Desktop if necessary, but for most users, uninstalling Docker Desktop is recommended.
> If you chose the 2nd option, you will need to delete the `~/.docker/config.json` file and authenticate with Docker again using the `docker login` command.

> **If you need to integrate Docker with other IDEs besides VSCode:**
> 
> VSCode integrates with Docker on WSL through the Remote WSL or Remote Container extension.
> 
> To enable TCP socket connection to the Docker server, follow these steps:
> 1. Create the file `/etc/docker/daemon.json` with the command:
>    ```bash
>    sudo echo '{"hosts": ["tcp://0.0.0.0:2375", "unix:///var/run/docker.sock"]}' > /etc/docker/daemon.json
>    ```
> 2. Restart Docker:
>    ```bash
>    sudo service docker restart
>    ```
> 
> After this, go to your IDE and select TCP Socket to connect to Docker, entering the URL `http://IP-OF-WSL:2375`. You can find your WSL IP with the command `cat /etc/resolv.conf`.
> 
> If it does not work, restart WSL with the command `wsl --shutdown` and start Docker service again.

> **For other Linux distributions**
>
> If you are using a distribution other than Ubuntu, check the Docker documentation for installation commands: [https://docs.docker.com/engine/install/](https://docs.docker.com/engine/install/)

Execute the following commands:

```bash
sudo apt update
sudo apt install ca-certificates curl
sudo install -m 0755 -d /etc/apt/keyrings
sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
sudo chmod a+r /etc/apt/keyrings/docker.asc

sudo tee /etc/apt/sources.list.d/docker.sources <<EOF
Types: deb
URIs: https://download.docker.com/linux/ubuntu
Suites: $(. /etc/os-release && echo "${UBUNTU_CODENAME:-$VERSION_CODENAME}")
Components: stable
Signed-By: /etc/apt/keyrings/docker.asc
EOF

sudo apt update

sudo apt install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
```

Grant permissions to run Docker with your current user:

```bash
sudo usermod -aG docker $USER
```

Restart WSL from the Windows command line to avoid needing root permissions to run Docker commands:

```bash
wsl --shutdown
```

The Docker service starts automatically after installation. To check if Docker is running, re-access Ubuntu and use:

```bash
 sudo service docker status
```

Some systems may have this behavior disabled and will require manual startup:

```bash
 sudo service docker start
```

This command will need to be executed every time Linux is restarted. If Docker is not running, you will see the following error when running Docker commands:

```bash
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
```

Finally, verify the installation was successful by running the `hello-world` image:

```bash
sudo docker run hello-world
```

You will see in your terminal:

```
"Hello from Docker!
This message shows that your installation appears to be working correctly..."
```

#### Error Starting Docker on Ubuntu 22.04

> If you encounter the following error or a similar one even after starting the Docker service:
>
> `Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?`
> Run the command `sudo update-alternatives --config iptables` and select option 1 `iptables-legacy`
>
> Then run `sudo service docker start` again. Run a Docker command like `docker ps` to check if it’s working properly. If the error no longer appears, Docker is running correctly.

#### Automatically Start Docker in WSL

> **For Windows 11 or Windows 10 with update KB5020030 only**

You can specify a default command to run each time WSL starts, which allows Docker to start automatically. Edit the file `/etc/wsl.conf`:

Run the command to edit:

```bash
sudo vim /etc/wsl.conf
```

Press `i` to enter insert mode and paste the following content:

```conf
[boot]
command = service docker start
```

#### Docker with Systemd

If you have enabled systemd, Docker will usually start automatically. Therefore, if you have the line `command = service docker start` in `/etc/wsl.conf`, comment it out with `#` and restart WSL with the command `wsl --shutdown`.

Otherwise, you can start Docker automatically using these commands:

```bash
sudo systemctl enable docker.service
sudo systemctl enable containerd.service
```

You need to restart WSL with `wsl --shutdown` for the changes to take effect.

Once you’ve done this, restart WSL with `wsl --shutdown` from DOS or PowerShell to test. After reopening WSL, type `docker ps` to check if the command no longer returns the message: `Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?`

## Basic Tips and Tricks with WSL 2

### Performance When Using WSL 2

The performance of WSL 2 is optimal when running everything inside Linux, so avoid running your projects with or without Docker from the `/mnt/c` path, as it will result in reduced performance. Ideally, run everything within Linux, in the `/home/your_user` path.

The idea is to move all your projects from `C:` to Linux, specifically `/home/your_user`. This way, everything is within Linux and performance will be better.

It might seem strange to do everything within Linux at first, but it’s the best way to achieve optimal performance with WSL 2.

### Windows Terminal

Windows Terminal is a terminal application that combines multiple terminals into one window, such as PowerShell, CMD, and WSL. It offers customization for colors, themes, shortcuts, and more.

Install it from the Windows Store.

Using Windows Terminal is a much better experience than the default Windows terminal. Use it for development on Windows and to access WSL 2.

### Access Windows Disks and Other Devices

WSL 2 has access to the entire Windows hard drive. You can access the C: drive from `/mnt/c`. If you have other drives, they will be available at `/mnt/d`, `/mnt/e`, etc.

The `/mnt` directory is a mount point in Linux where Windows devices are mounted.



### Access WSL 2 from Windows

You can access WSL 2 through Windows Explorer by typing `\\wsl.localhost$` in the address bar to view the installed Linux distributions.

You can also access it through the `Linux` icon on the left side of Windows Explorer. If your Windows version doesn’t have this icon, use the path `\\wsl.localhost$`.



You can also open a folder in Windows Explorer from within Linux by typing `explorer.exe .` in the WSL terminal. This will open the current folder in Windows Explorer.

### Integration with VSCode

Visual Studio Code has an extension called **Remote - WSL** that allows you to access WSL 2 directly from VSCode. With this extension, you can edit your files directly in WSL 2, run commands, install extensions, and more.

Learn more about this extension at [Remote - WSL](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-wsl).

When opening a project that is inside Linux, make sure the WSL mode in VSCode is enabled. In the lower-left corner of VSCode, click the `><` button and select `Connect to WSL`. This will connect VSCode to WSL 2, allowing you to open projects inside Linux. You’ll see the button `><` change to `WSL: Ubuntu`.



If VSCode doesn’t open projects in WSL mode, the WSL mode isn’t activated, and you will lose performance while editing files in Linux and may miss out on some extensions.

Another way to open a project in WSL mode is by accessing the project folder in the WSL terminal and typing `code .`. This will open VSCode in WSL mode.

### Running Windows Executables in WSL 2

You can run Windows executables within WSL 2 by typing the full path of the Windows executable in the WSL terminal. For example, to run `notepad.exe`, just type `notepad.exe` in the WSL terminal.



### Listing Installed Linux Distributions in WSL 2

To list the Linux distributions installed in WSL 2, execute the command `wsl -l -v` in the Windows terminal.

### Stopping All Linux Distributions in WSL 2

To stop all running Linux distributions in WSL 2, execute the command `wsl --shutdown` in the Windows terminal.

To stop a specific Linux distribution, use the command `wsl --t <distribution name>`.



> If you are using Docker Desktop, executing `wsl --shutdown` will also stop Docker Desktop, and you will need to restart it.

* You can run some graphical applications in Linux with WSL 2. Check this tutorial: [https://medium.com/@dianaarnos/aplica%C3%A7%C3%B5es-gr%C3%A1ficas-no-wsl2-e0a481e9768c](https://medium.com/@dianaarnos/aplica%C3%A7%C3%B5es-gr%C3%A1ficas-no-wsl2-e0a481e9768c).
* Run the command ```wsl -l -v``` with PowerShell to see the Linux versions installed and their current status (running or stopped).

### Backup and Restore Linux Distributions in WSL 2

You can back up and restore Linux distributions in WSL 2. This is useful as it saves everything you’ve done in Linux, such as package installations and configurations, and allows you to restore it wherever you want.

To back up a Linux distribution, execute:

```bash
wsl --export Ubuntu C:\path\backup.vhdx --vhd
```

Where `Ubuntu` is the name of the Linux distribution you want to back up and `C:\path\backup.vhdx` is the path where the backup will be saved. The `--vhd` option saves the backup in VHD format, which facilitates restoration and can be mounted as a hard disk in Windows if desired.

Depending on the size of the virtual disk, the backup process may take some time.

To restore a Linux distribution, execute:

```bash
wsl --import-in-place Ubuntu C:\path\backup.vhdx
```

Where `Ubuntu` is the name of the Linux distribution (or any name you prefer) you want to restore and `C:\path\backup.vhdx` is the path where the backup was saved.

Typically, VHDX files are saved in `C:\Users\<your_user>\AppData\Local\Packages\CanonicalGroupLimited...\LocalState\`, but once you have restored the Linux distribution, you can move the VHDX file wherever you like. It will be the path you provide in the `wsl --import-in-place` command.

### Compressing the WSL 2 Virtual Disk

The WSL 2 virtual disk is a VHDX file that grows as you use Linux. If you delete files, the virtual disk does not automatically shrink; it will remain the same size.

To reduce its size, enable the `sparse` mode in WSL 2, which provides automatic disk compression. To enable it, edit the `.wslconfig` file:

```conf
[wsl2]
sparseVhd=true
```

This option will only apply to new virtual disks.

For existing virtual disks, use the following commands:

```bash
wsl --manage "Ubuntu" --set-sparse true
wsl --manage "docker-desktop" --set-sparse true # If using Docker Desktop
```

This will convert the virtual disk to sparse mode, which is automatic disk compression.

Before running the command, make sure the Linux distribution is stopped by using `wsl --shutdown` to stop all distributions.

If you have an old distribution and after applying sparse mode the virtual disk hasn't reduced in size, you can compress it manually.

Use the [wslcompact](https://github.com/okibcn/wslcompact) tool for this process. This tool is an executable for `PowerShell` that exports and imports the virtual disk, forcing WSL to compress it.

Run the command:

```bash
wslcompact -c Ubuntu
```

This will generate a new virtual disk named `ext4.vhdx`, which will be your compressed distribution. When the executable asks to register the disk, press `Y` and then `Enter`. This won't automatically register it; you'll need to do it manually as shown in the backup and restoration section of this tutorial.

Remove the old disk with:

```bash
wsl --unregister Ubuntu
```

And register the new disk with:

```bash
wsl --import-in-place Ubuntu C:\path\to\ext4.vhdx
```

> **Warning**: Backup your Linux distribution before compressing it to avoid losing data in case of errors.

### LAN and VPN Network Mode

Since WSL is virtualized, there is a separate network interface, so if you use LAN (wired), you may not be able to access applications running in WSL through a browser, for instance, without port binding, which can be inefficient.

You might also encounter issues with VPNs as WSL 2 has its own network interface, which might not work correctly with some VPNs.

To resolve this, enable the `mirrored` network mode in WSL 2, which makes the WSL 2 network interface the same as Windows. Edit the `.wslconfig` file:

```conf
[wsl2]
networkingMode=mirrored
```

This option will only work after restarting WSL with the command `wsl --shutdown`.

This option helps improve the experience when using VPNs.

### Enabling BuildKit in Docker

> **For Docker Engine only**

Add `export DOCKER_BUILDKIT=1` at the end of your Linux user’s `.profile` file or in your custom terminal file to enhance performance when building with Docker. Run `source ~/.profile` to load this environment variable into your WSL 2 environment.

### Automatically Start Docker in WSL 2

> **For Windows 11 or Windows 10 with update KB5020030 only**
> **For Docker Engine only**
> **For those who haven’t enabled systemd**

You can specify a default command to run every time WSL starts, allowing Docker to start automatically. Edit the `/etc/wsl.conf` file:

Run the command to edit:

```conf
sudo vim /etc/wsl.conf
```

Press `i` to enter insert mode and paste the following content:

```conf
[boot]
command = service docker start
```

### Releasing RAM Memory from WSL 2

If you notice that WSL 2 is consuming a lot of your machine's resources, run the following command in the WSL 2 terminal to free up RAM:

```bash
echo 1 | sudo tee /proc/sys/vm/drop_caches
```

This method is aggressive as it releases RAM instantly but may be necessary in some cases.

> Do not use the option below if you are not using Docker Engine. It can be used with Docker Desktop or if you do not have Docker installed.

WSL has a feature called `autoMemoryReclaim` that automatically releases unused RAM. 

There are two options for `autoMemoryReclaim`:

* `gradual`: Releases RAM gradually every 5 minutes.
* `dropcache`: Releases RAM immediately.

Edit the `.wslconfig` file:

```conf
[experimental]
autoMemoryReclaim=gradual
```

If you want an automatic memory release option and are using Docker Engine, run the following script in WSL: [https://gist.github.com/craigloewen-msft/496078591e0bbbfdec9f144c6b50a8cc](https://gist.github.com/craigloewen-msft/496078591e0bbbfdec9f144c6b50a8cc). By default, it runs every 2 minutes, but you can change the execution interval.

### .wslconfig and wsl.conf Files

The `.wslconfig` file is a global configuration file, meaning it affects all Linux distributions installed in WSL 2, as you might have multiple Linux distributions like Ubuntu, Debian, Fedora, etc.

The `wsl.conf` file is a distribution-specific configuration file, affecting only the Linux distribution specified in `wsl.conf`.

Some options you can use in `.wslconfig` and `wsl.conf` are detailed in the official documentation [https://docs.microsoft.com/pt-br/windows/wsl/wsl-config](https://docs.microsoft.com/pt-br/windows/wsl/wsl-config).

> These options can help manage WSL 2 behavior, such as allocating more RAM, CPUs, etc. Basic configurations were already covered in the WSL installation section, Docker installation, and this Tips and Tricks section.

These options will only take effect after restarting WSL with the command `wsl --shutdown`.

### Expanding the WSL 2 Virtual Disk

By default, the WSL 2 virtual disk is 1TB, but if you need more space, you can expand the virtual disk.

A simple way to check the disk size is to run the following command in PowerShell or DOS:

```bash
wsl --system -d <distribution-name> df -h /mnt/wslg/distro
```

Use Windows `diskpart` to expand its size. Follow this tutorial: [How to Expand the Size of Your WSL 2 Virtual Hard Disk](https://learn.microsoft.com/en-us/windows/wsl/disk-space#how-to-expand-the-size-of-your-wsl-2-virtual-hard-disk).

## FAQs

### Do I need a Windows 10/11 Pro license to use WSL 2?

No, WSL 2 is supported on all versions of Windows 10/11, as long as they are updated.

### Can I continue developing on Windows without using WSL 2?

Yes, you can continue developing on Windows without using WSL 2. However, WSL 2 provides a development experience closer to Linux, with better performance and more features.

Unless you have a specific need to develop directly on Windows, such as developing .NET applications, your application will likely run on Linux. WSL 2 is a better option if you want to use Windows while leveraging Linux capabilities without dual booting or using a virtual machine.

### Does WSL 2 work alongside other virtual machines like VirtualBox or VMWare?

Yes, WSL 2 can work alongside other virtual machines like **VirtualBox** or **VMWare**. For more details, check the [official reference](https://learn.microsoft.com/pt-br/windows/wsl/faq#poderei-executar-o-wsl-2-e-outras-ferramentas-de-virtualiza--o-de-terceiros--como-vmware-ou-virtualbox-).

### Can I access applications running in WSL 2 from Windows?

Yes, you can access applications running in WSL 2 from Windows by navigating to `localhost` in your Windows browser. WSL 2 has its own network interface, and Windows can access applications running on WSL 2.

### Can I run graphical applications in WSL 2?

Yes, WSL 2 supports graphical applications through the WSLg (Windows Subsystem for Linux GUI) project. For more information, check the top of this tutorial.

### Can I use WSL in production scenarios?

WSL is designed as a development tool and is not recommended for production use.

### Can I run Docker Engine alongside Docker Desktop?

No, you can only run one at a time. It is possible to have both installed, but only one can be running at any given time.

### Questions about Docker Desktop

We did a complete overview of Docker Desktop, including for other operating systems as well. Check it out [https://www.youtube.com/watch?v=99dCerRKO6s](https://www.youtube.com/watch?v=99dCerRKO6s)

### Want to set up a more productive environment on Windows?

Check out the tutorials below:

- Productive development environment setup: [https://github.com/argentinaluiz/ambiente-dev-produtivo](https://github.com/argentinaluiz/ambiente-dev-produtivo)
- How to set up a productive environment in VSCode: [https://github.com/argentinaluiz/my-vscode-settings](https://github.com/argentinaluiz/my-vscode-settings)