diff --git a/.zshrc b/.zshrc deleted file mode 100644 index dddf0fd..0000000 --- a/.zshrc +++ /dev/null @@ -1,150 +0,0 @@ -# Enable Powerlevel10k instant prompt. Should stay close to the top of ~/.zshrc. -# Initialization code that may require console input (password prompts, [y/n] -# confirmations, etc.) must go above this block; everything else may go below. -if [[ -r "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh" ]]; then - source "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh" -fi - -# If you come from bash you might have to change your $PATH. -# export PATH=$HOME/bin:/usr/local/bin:$PATH - -# Path to your oh-my-zsh installation. -export ZSH="$HOME/.oh-my-zsh" -export PATH=$PATH:/usr/local/go/bin:~/go/bin -# Set name of the theme to load --- if set to "random", it will -# load a random theme each time oh-my-zsh is loaded, in which case, -# to know which specific one was loaded, run: echo $RANDOM_THEME -# See https://github.com/ohmyzsh/ohmyzsh/wiki/Themes -ZSH_THEME="powerlevel10k/powerlevel10k" - -# Set list of themes to pick from when loading at random -# Setting this variable when ZSH_THEME=random will cause zsh to load -# a theme from this variable instead of looking in $ZSH/themes/ -# If set to an empty array, this variable will have no effect. -# ZSH_THEME_RANDOM_CANDIDATES=( "robbyrussell" "agnoster" ) - -# Uncomment the following line to use case-sensitive completion. -# CASE_SENSITIVE="true" - -# Uncomment the following line to use hyphen-insensitive completion. -# Case-sensitive completion must be off. _ and - will be interchangeable. -# HYPHEN_INSENSITIVE="true" - -# Uncomment one of the following lines to change the auto-update behavior -# zstyle ':omz:update' mode disabled # disable automatic updates -# zstyle ':omz:update' mode auto # update automatically without asking -# zstyle ':omz:update' mode reminder # just remind me to update when it's time - -# Uncomment the following line to change how often to auto-update (in days). -# zstyle ':omz:update' frequency 13 - -# Uncomment the following line if pasting URLs and other text is messed up. -# DISABLE_MAGIC_FUNCTIONS="true" - -# Uncomment the following line to disable colors in ls. -# DISABLE_LS_COLORS="true" - -# Uncomment the following line to disable auto-setting terminal title. -# DISABLE_AUTO_TITLE="true" - -# Uncomment the following line to enable command auto-correction. -# ENABLE_CORRECTION="true" - -# Uncomment the following line to display red dots whilst waiting for completion. -# You can also set it to another string to have that shown instead of the default red dots. -# e.g. COMPLETION_WAITING_DOTS="%F{yellow}waiting...%f" -# Caution: this setting can cause issues with multiline prompts in zsh < 5.7.1 (see #5765) -# COMPLETION_WAITING_DOTS="true" - -# Uncomment the following line if you want to disable marking untracked files -# under VCS as dirty. This makes repository status check for large repositories -# much, much faster. -# DISABLE_UNTRACKED_FILES_DIRTY="true" - -# Uncomment the following line if you want to change the command execution time -# stamp shown in the history command output. -# You can set one of the optional three formats: -# "mm/dd/yyyy"|"dd.mm.yyyy"|"yyyy-mm-dd" -# or set a custom format using the strftime function format specifications, -# see 'man strftime' for details. -# HIST_STAMPS="mm/dd/yyyy" - -# Would you like to use another custom folder than $ZSH/custom? -# ZSH_CUSTOM=/path/to/new-custom-folder - -# Which plugins would you like to load? -# Standard plugins can be found in $ZSH/plugins/ -# Custom plugins may be added to $ZSH_CUSTOM/plugins/ -# Example format: plugins=(rails git textmate ruby lighthouse) -# Add wisely, as too many plugins slow down shell startup. -plugins=(git git-flow fast-syntax-highlighting zsh-autosuggestions zsh-completions) - -source $ZSH/oh-my-zsh.sh - -# User configuration - -# export MANPATH="/usr/local/man:$MANPATH" - -# You may need to manually set your language environment -# export LANG=en_US.UTF-8 - -# Preferred editor for local and remote sessions -# if [[ -n $SSH_CONNECTION ]]; then -# export EDITOR='vim' -# else -# export EDITOR='mvim' -# fi - -# Compilation flags -# export ARCHFLAGS="-arch x86_64" - -# Set personal aliases, overriding those provided by oh-my-zsh libs, -# plugins, and themes. Aliases can be placed here, though oh-my-zsh -# users are encouraged to define aliases within the ZSH_CUSTOM folder. -# For a full list of active aliases, run `alias`. -# -# Example aliases -# alias zshconfig="mate ~/.zshrc" -# alias ohmyzsh="mate ~/.oh-my-zsh" - -# To customize prompt, run `p10k configure` or edit ~/.p10k.zsh. -[[ ! -f ~/.p10k.zsh ]] || source ~/.p10k.zsh - -export DOCKER_BUILDKIT=1 -export NVM_DIR="$HOME/.nvm" -[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm -[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion - -. $HOME/.asdf/asdf.sh - - -alias dockerrm='docker rm $(docker ps -a -q)' -alias dockerstop='docker stop $(docker ps -a -q)' -alias serverblog='ssh forge@159.89.86.23 -i ~/.ssh/server-digital-ocean.key' -alias servercode='ssh forge@206.189.255.17 -i ~/.ssh/server-digital-ocean.key' -alias serverson='ssh forge@138.197.227.120 -i ~/.ssh/server-digital-ocean.key' -alias ssh-load='eval $(ssh-agent -s)' -alias nvm="unalias nvm; [ -s ~/.nvm/nvm.sh ] && . ~/.nvm/nvm.sh; nvm" -alias gfw='git flow' -alias rmnodemodules="find . -name 'node_modules' -type d -prune -print -exec rm -rf '{}' \;" -alias rmdbdata='sudo find . -name '\''dbdata'\'' -type d -prune -print -exec rm -rf '\''{}'\'' \;' -alias rmnext='sudo find . -name '\''.next'\'' -type d -prune -print -exec rm -rf '\''{}'\'' \;' -alias rmdist='sudo find . -name '\''dist'\'' -type d -prune -print -exec rm -rf '\''{}'\'' \;' -alias wslip="sudo ip addr add 192.168.99.2/24 broadcast 192.168.99.255 dev eth0 label eth0:1;" -alias k="kubectl" -alias removeduplicates="cat -n ~/.zsh_history | sort -t ';' -uk2 | sort -nk1 | cut -f2- > ./.zsh_short_history" - -if [ -n "$LENS_SESSION" ]; then - c=$(kubectl config current-context) - export KUBECONFIG="" - kubectl config use-context "$c" -fi - -typeset -g POWERLEVEL9K_INSTANT_PROMPT=quiet - -export WAYLAND_DISPLAY="wayland-1" -#setxkbmap -model abnt -layout us -variant intl -setxkbmap -model logitech_base -layout us -variant intl -#setxkbmap -model abnt -layout us -variant altgr-intl - -export K9S_EDITOR=nvim \ No newline at end of file diff --git a/README.en.md b/README.en.md index b62012b..bfdca37 100644 --- a/README.en.md +++ b/README.en.md @@ -2,371 +2,849 @@

-# WSL2 + Docker Quick Guide +# WSL2 + Docker Quick Guide/Tutorial *Read this in other language: [Portuguese](README.md) -## What is WSL2? +## 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) + * [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 Windows Store](#installation-of-wsl-2-via-windows-store) + * [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) + + +
+ +## 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. -In 2016, Microsoft announced the possibility of running Linux within Windows 10 as a subsystem, and this was named **WSL** or **Windows Subsystem for Linux**. +WSL 2 was officially released on **May 28, 2020**. -Accessing the Windows 10 file system 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 execute various tasks in Linux, including Docker. +With WSL 2, it is possible to run Docker and other tools that depend on the Linux Kernel using Windows 10/11. -In 2019, Microsoft announced **WSL 2**, with an improved dynamic in relation to the 1st version. +Compare WSL versions: [https://docs.microsoft.com/en-us/windows/wsl/compare-versions](https://docs.microsoft.com/en-us/windows/wsl/compare-versions) -* Complete execution of the Linux kernel. -* Improved performance for accessing files within Linux. -* Full system call compatibility. +## Minimum Requirements -WSL 2 was officially released on May 28, 2020. +* **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). -With WSL 2, it is possible to run Docker on Linux using Windows 10/11. +* **Windows 11 Home or Professional** + - Version 22000 or higher (any Windows 11). -Compare the versions: [https://docs.microsoft.com/pt-br/windows/wsl/compare-versions](https://docs.microsoft.com/pt-br/windows/wsl/compare-versions) +* 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). -## What is Docker +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. -Docker is an open source platform that enables packaging an application inside a container. An application can fit and run on any machine that has this technology installed. +> **It is essential to keep Windows updated, as WSL 2 depends on an updated version of Hyper-V. Check Windows Update.** -## Why use WSL 2 + Docker for development +## Installation of WSL 2 -Configuring development environments on Windows has always been bureaucratic and complex, and the performance of some tools is not entirely satisfactory. +All instructions below are for Windows 10/11. -With the advent of Docker, this scenario has improved significantly, as we can set up our development environment based on Unix, independently and quickly, and still unify it with other operating systems. +### Windows Update -Check out our **live about WSL 2 + Docker on the Full Cycle channel**: [https://www.youtube.com/watch?v=usF0rYCcj-E](https://www.youtube.com/watch?v=usF0rYCcj-E). +Make sure your Windows is updated, as WSL 2 depends on an updated version of Hyper-V. Check Windows Update. +### Update WSL -## Ways to use Docker on Windows +With Windows 10 version 2004 or Windows 11, WSL will already be present on your machine. Run the command to get the latest version of WSL: -* [Docker Toolbox](#docker-toolbox). -* [Docker Desktop with Hyper-V](#docker-desktop-with-hyper-v). -* [Docker Desktop with WSL2](#docker-desktop-with-wsl2). -* [Docker Engine (Native Docker) directly installed on WSL2](#docker-engine-docker-native-directly-installed-on-wsl2). +```bash +wsl --update +``` -### Docker Toolbox +### Set the default version of WSL to version 2 -Runs on top of Oracle's virtualization program, called **VirtualBox**. The performance of Docker Toolbox for many applications/tools can be very poor, making it impractical to use. +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: -### Docker Desktop with Hyper-V +```bash +wsl --set-default-version 2 +``` -Runs on top of Microsoft's **Hyper-V** instead of using VirtualBox like Docker Toolbox. Docker Desktop with Hyper-V requires the **PRO** version of Windows 10/11, so you need to purchase it if you don't already have it. +### Install Ubuntu -Hyper-V tends to require a lot of machine resources, and although performance is better than Docker Toolbox, the machine may become slow to use for other things in Windows. +Run the command: -*Docker has announced that it will remove support for Hyper-V in the future.* +```bash +wsl --install +``` -### Docker Desktop with WSL2 +This command will install `Ubuntu` as the default Linux distribution. -Runs on top of the **Virtual Machine Platform** instead of using VirtualBox or Hyper-V. Integrates with WSL2 allowing Docker to run within the Linux environment. No need to acquire a PRO license for Windows 10/11, has great performance, and consumes fewer resources compared to Docker Toolbox or Docker Desktop with Hyper-V. +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 have the great advantage of working entirely within Linux for development, so using WSL2 + Docker is the best way to develop applications on Windows. +We suggest Ubuntu (without a version) because it is a popular distribution that comes with many useful development tools installed by default. -#### Advantages +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. -* Simplifies Docker configuration in both Windows and WSL 2. -* Allows Docker to run outside WSL 2. Any shell such as PowerShell or DOS can be used. -* Supports Windows mode containers (images that contain Windows under the hood instead of Linux). -* Creates a centralized environment for storing images, volumes, and other Docker configurations. Multiple WSL 2 distributions can run the same Docker. -* Visual interface for Docker administration. +To open a new Ubuntu window, just type `Ubuntu` in the start menu and click on the Ubuntu icon. -#### Disadvantages +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. -* Initial memory usage without running any Docker containers can reach 3GB. -* Adds complex infrastructure to run Docker when only running Docker containers within WSL 2 is required. +### (Optional) Change the version of a Linux distribution from WSL 1 to WSL 2 -### Docker Engine (Native Docker) directly installed on WSL2 +If the Linux distribution you installed is on version 1, you can change it to version 2 with the following command: -Docker Engine is the native Docker that runs in the Linux environment and is fully supported for WSL2. Its installation is identical to that described for Linux distributions provided on the [Docker](https://docs.docker.com/engine/install/ubuntu/) website. +```bash +wsl --set-version 2 +``` -#### Advantages +Congratulations, your WSL2 is now up and running! -* It consumes the minimum amount of memory necessary to run the Docker daemon (Docker server). -* It is even faster than with Docker Desktop, as it runs directly within the WSL2 instance itself and not in a separate Linux instance. +![Example of WSL2 running](img/wsl2-working.png) -#### Disadvantages +### Installation of WSL 2 via Windows Store -* It is necessary to run the command sudo service docker start every time WSL2 is restarted. This is not necessarily a disadvantage, but it is worth noting, and it will be resolved in the future with the inclusion of the /etc/wsl.conf file, which will allow commands to be executed every time WSL is restarted. -* If you need to run Docker in another WSL2 instance, you need to install Docker again in that instance or configure access to the desired Docker socket to share Docker between instances. -* It does not support containers in Windows mode. +It is also possible to install Linux distributions from the Windows Store. Just access the Windows Store, search for the desired Linux distribution name, and click install. -## Minimum Requirements +We suggest Ubuntu (without a version) because it is a popular distribution that comes with many useful development tools installed by default. -* Windows 10 Home or Professional - - Version 1903 or higher for x64 systems, with Build 18362 or higher. - - Version 2004 or higher for ARM64 systems, with Build 19041 or higher. +![Linux distributions in the Windows Store](img/linux-distros.png) -* Windows 11 Home or Professional - - Version 22000 or higher. +### Integration with VSCode -Your Windows version is likely already supported, but you can check this by accessing the `notification menu near the clock > All settings > System > About`. If it is not, use the Windows Update Assistant to update your Windows version. +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. -* A machine compatible with virtualization (check availability according to your processor brand. If your machine is older, you may need to enable virtualization in the BIOS). -* At least 4GB of RAM. +Learn more about this extension at [Remote - WSL](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-wsl). -## WSL 2 Installation +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`. -> ## Windows 10 +![Connect to WSL 2 in VSCode](img/vscode-remote-wsl.png) -### Enable Virtual Machine Platform +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. -Execute the following commands in PowerShell as an administrator: -``` bash -dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart -dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart -``` -Open PowerShell and type the command `wsl`, if it doesn't work, restart your machine. +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. -### Install the WSL executable +## Windows Terminal as the default development terminal for Windows -Download the WSL 2 Kernel from this link: [https://docs.microsoft.com/pt-br/windows/wsl/wsl2-kernel](https://docs.microsoft.com/pt-br/windows/wsl/wsl2-kernel) and install the package. +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. -### Set the default version of WSL to version 2 +Install it from the Windows Store. -Version 1 of WSL is currently the default, set the default version to version 2, so all installed Linux distributions will already be set to version 2 by default. Run the following command in PowerShell: +See more configuration options at [More about Windows Terminal](https://docs.microsoft.com/en-us/windows/terminal/get-started). -``` bash -wsl --set-default-version 2 +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\)` and define these settings: + +```conf +[wsl2] +memory=8GB +processors=4 ``` -### (Optional) Changing a distribution from WSL 1 to version 2 +These are example limits and the most basic configurations to be used. Adjust them according to your available resources. -If you already have WSL 1 on your machine and have just installed version 2, you can convert your WSL 1 Linux distribution to WSL 2. Run the following command in PowerShell: +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. -``` bash -wsl --set-version 2 +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 ``` -> ## Windows 11 +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. -Execute the command: +![WSLg Architecture](img/WSLg_ArchitectureOverview.png) + +### 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 -wsl --install +sudo apt-get update + +sudo apt-get install gedit ``` -This command will install all WSL dependencies and install `Ubuntu` as the default Linux distribution. +Open Gedit in the WSL 2 terminal by typing `gedit`, and it will open on Windows. -If you want to install a different version of Ubuntu, run the command `wsl -l -o`, which will list all available Linux versions. Install the chosen version with the command `wsl --install -d distribution-name`. +Therefore, just install the application and launch it in the WSL 2 terminal to open it on Windows. -We suggest Ubuntu (no version specified) as a popular distribution that comes with several tools pre-installed. +## What is Docker -## Choose your Linux distribution in the Windows Store +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. -It's also possible to install Linux distributions through the Windows Store. Choose your preferred Linux distribution in the Windows Store app, we suggest Ubuntu (without version) as it is a popular distribution and already comes with several tools installed by default. +### Why Use WSL 2 + Docker for Development -![Linux distributions in the Windows Store](img/distribuicoes_linux.png) +Setting up development environments on Windows has always been bureaucratic and complex, in addition to the performance of some tools not being entirely satisfactory. -When starting the installed Linux, you'll need to create a **username** which can be the same as your machine and a **password**, this will be the **root user of your WSL instance**. +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. -Congratulations, your WSL2 is now working: +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). -![Exemple of WSL2 running](img/wsl2_funcionando.png) +## 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) -## (Optional) Use Windows Terminal as the default development terminal for Windows +### 1. (Obsolete) Docker Toolbox -A deficiency that Windows has always had is providing a suitable terminal for development. Now we have **Windows Terminal** built by Microsoft itself that allows running terminals in tabs, changing colors and themes, configuring shortcuts, and much more. +Runs on Oracle's virtualization program, called **VirtualBox**. +The performance of Docker Toolbox can be very poor, making its use unfeasible. -Install it from the Windows Store and use these [default settings](windows-terminal-settings.json) to enable WSL 2, Git Bash, the dracula theme, and some shortcuts. +It can still be used on older Windows versions, such as XP, Vista, 7, 8, and 8.1. -To override the settings **click the down arrow next to the tabs and then click settings**, it will open the Windows Terminal settings, simply paste the contents of the JSON file and save, then click on `Ubuntu` in the `Profiles` section, click on Starting `Directory` and change the path to: `(\\wsl$\Ubuntu\home\YOUR_UBUNTU_USER)`. +### 2. (Obsolete) Docker Desktop with Hyper-V -## What resources can WSL 2 use from your machine +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. -We can say that WSL 2 has almost complete access to your machine's resources. By default, it has access to: +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. -* The entire hard disk. -* Complete use of processing resources. -* Use of 80% of available RAM. -* Use of 25% of available memory for SWAP. +### 3. Docker Desktop with WSL2 -This may not be desirable since WSL 2 can use virtually all of your machine's resources, but we can configure limits. +> 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) -Create a file called `.wslconfig` in your user folder (C:\Users\) and define these settings: +Runs on **Virtual Machine Platform**, a component of Hyper-V, and integrates with WSL2, allowing Docker to run within the Linux environment. -```txt -[wsl2] -memory=8GB -processors=4 -swap=2GB -``` -These are example limits and the most basic settings to be used, configure them according to your availability. -For more details, see this Microsoft documentation: [https://docs.microsoft.com/pt-br/windows/wsl/wsl-config#wsl-2-settings](https://docs.microsoft.com/pt-br/windows/wsl/wsl-config#wsl-2-settings). +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. + +#### 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. + +#### 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. -To apply these settings, it is necessary to restart the Linux distributions, so we suggest running the command `wsl --shutdown` in PowerShell (this command will shut down all active WSL 2 instances, and you just need to reopen the terminal to use it with the new settings). +### 4. Docker Engine (Native Docker) Directly Installed on WSL2 -## Integrating Docker with WSL 2 +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/). -At the beginning of this tutorial, we saw [4 ways to use Docker on Windows](#ways-to-use-docker-on-windows), but only 2 that we recommend: +It is the purest way to use Docker on Linux. -* [Docker Engine (Docker Native) directly installed on WSL2.](#install-docker-with-docker-engine-native). -* [Docker Desktop with WSL2](#install-docker-with-docker-desktop). +#### Advantages -We recommend choosing the 1st option for its benefits, since most people will be able to use WSL 2 as a central development tool. But in this tutorial, we will show both installation methods. +* Consumes less memory to run the Docker Daemon (Docker server) compared to Docker Desktop. +* Provides the purest experience of using Docker on Linux. +#### Disadvantages -### 1 - Install Docker with Docker Engine (Docker Native) +* 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. -The installation of Docker on WSL 2 is identical to the installation of Docker on your own Linux distribution, so if you have Ubuntu, it's the same as Ubuntu, if it's Fedora, it's the same as Fedora. The installation documentation for Docker on Linux by distribution is [here](https://docs.docker.com/engine/install/), but let's see how to install it on Ubuntu. +## Which Docker Usage Mode to Choose on Windows? -> **For those who are migrating from Docker Desktop to Docker Engine, we have two options:** +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: + +![Docker Desktop Installed](img/installing-docker-desktop.png) + +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. + +![Linux Distributions Running on WSL 2](img/wsl-docker-desktop-running.png) + +#### 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: + +![Activate Docker in the Linux Distribution](img/docker-desktop-wsl-integration.png) + +#### 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: + +![Enable Resource Save Mode in Docker Desktop](img/resource-saver.png) + +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. + +### 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 the Docker Desktop service in Windows services. This option allows you to use Docker Desktop if necessary, but for most users, uninstalling Docker Desktop is the recommended approach. ->If you choose the second option, you will need to delete the file ~/.docker/config.json and authenticate with Docker again using the command "docker login". +> 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 IDEs other than VSCode** -> -> VSCode already integrates with Docker on WSL through the Remote WSL or Remote Container extension. -> ->You need to enable the connection to the Docker server via TCP. Here are the steps: -> 1. Create the file /etc/docker/daemon.json: sudo echo '{"hosts": ["tcp://0.0.0.0:2375", "unix:///var/run/docker.sock"]}' > /etc/docker/daemon.json -> 2. Restart Docker: `sudo service docker restart` -> -> After this procedure, go to your IDE and to connect to Docker, choose the TCP Socket option and put the URL `http://WSL-IP:2375`. Your WSL IP can be found with the command `cat /etc/resolv.conf`. +> **If you need to integrate Docker with other IDEs besides VSCode:** > -> If it doesn't work, restart WSL with the command `wsl --shutdown` and start the Docker service again. +> 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. -Install the prerequisites: +Execute the following commands to install Docker: -``` -sudo apt update && sudo apt upgrade -sudo apt remove docker docker-engine docker.io containerd runc -sudo apt-get install \ - apt-transport-https \ - ca-certificates \ - curl \ - gnupg \ - lsb-release -``` +```bash +sudo apt-get update +sudo apt-get 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 -Add the Docker repository to the list of sources in Ubuntu: +echo \ + "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu \ + $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | \ + sudo tee /etc/apt/sources.list.d/docker.list > /dev/null +sudo apt-get update +sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin ``` + +Add Docker’s repository to Ubuntu’s sources list: + +```bash curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg echo \ "deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu \ $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null ``` -Intall Docker Engine +> **NOTE:** 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/) + +Grant permissions to run Docker with your current user: +```bash +sudo usermod -aG docker $USER ``` -sudo apt-get update + +Restart WSL from the Windows command line to avoid needing root permissions to run Docker commands: + +```bash +wsl --shutdown ``` + +Re-access Ubuntu and start the Docker service: + +```bash +sudo service docker start ``` -sudo apt-get install docker-ce docker-ce-cli containerd.io docker-compose-plugin + +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? ``` -Grant permission to run Docker with your current user: +#### 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 ``` -sudo usermod -aG docker $USER + +Press `i` to enter insert mode and paste the following content: + +```conf +[boot] +command = service docker start ``` -Start Docker service: +#### 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 ``` -sudo service docker start + +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. + +![Mount no WSL2](img/mount-in-wsl2.png) + +### 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$`. + +![Accessing WSL 2 from Windows Explorer](img/acessing-wsl-win-explorer.png) + +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`. + +![Connecting WSL 2 in VSCode](img/vscode-remote-wsl.png) + +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. + +![Running Windows executables in WSL 2](img/executables-win-in-wsl2.png) + +### 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 `. + +![Checking installed distros in WSL 2](img/check-installed-distros.png) + +> 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. -This above command will need to be executed every time Linux is restarted. If the Docker service is not running, it will show this error message when running the docker command: +To restore a Linux distribution, execute: +```bash +wsl --import-in-place Ubuntu C:\path\backup.vhdx ``` -Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running? + +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\\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 ``` -The Docker Compose installed now will be in version 2, to run it instead of `docker-compose` use `docker compose`. +This option will only apply to new virtual disks. -### Error starting Docker in Ubuntu 22.04 +For existing virtual disks, use the following commands: -> If even after starting the Docker service, the following error or a similar one occurs: -> -> `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 choose option 1 `iptables-legacy` -> -> Run `sudo service docker` start again. Run some Docker command such as `docker ps` to verify if it is working correctly. If it does not show the error above, it is OK. +```bash +wsl --manage "Ubuntu" --set-sparse true +wsl --manage "docker-desktop" --set-sparse true # If using Docker Desktop +``` -#### Tip for Windows 11 +This will convert the virtual disk to sparse mode, which is automatic disk compression. -In Windows 11, you can specify a default command to be executed whenever WSL is started. This allows us to automatically start the docker service. Edit the file `/etc/wsl.conf`: +Before running the command, make sure the Linux distribution is stopped by using `wsl --shutdown` to stop all distributions. -Run the command to edit: +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 -`sudo vim /etc/wsl.conf` +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. -Press the letter `i` and paste the contents: +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 -[boot] -command="service docker start" +[wsl2] +networkingMode=mirrored ``` -Press the `:` key, type `wq` to save/exit and press enter. Done, restart WSL with the `wsl --shutdown` command in DOS or PowerShell to test. After opening WSL again, type the `docker ps` command to check if the command doesn't return the following message: `Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?` -### 2 - Install Docker with Docker Desktop +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** -Download in this link: [https://hub.docker.com/editions/community/docker-ce-desktop-windows](https://hub.docker.com/editions/community/docker-ce-desktop-windows) and install Docker Desktop. +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 -Click on the `Docker icon near the clock -> Settings -> Settings at the top -> Resources -> WSL Integration`. +> **For Windows 11 or Windows 10 with update KB5020030 only** +> **For Docker Engine only** +> **For those who haven’t enabled systemd** -Enable `Enable integration with my default WSL distro` and enable your Linux version. +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 +``` -![Docker working within WSL 2](img/docker_funcionando_dentro_do_wsl2.png) +### Releasing RAM Memory from WSL 2 -## Basic tips and tricks with 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: -* The performance of WSL 2 lies in running everything within Linux, so avoid running your projects with or without Docker from the path `/mnt/c`, as you will lose performance. -* To open the WSL terminal, simply type the distribution name in the Start menu or run `C:\Windows\System32\wsl.exe`. -* The Windows 10/11 file system is accessible at `/mnt`. -![Mount no WSL2](img/mount_no_wsl2.png) -* The Linux file system can be accessed via the Windows network by typing `\\wsl$` in Windows Explorer. -![Accessing WSL2 in Windows Explorer](img/acessando_wsl2_no_explorer.png) -* A folder in Windows Explorer can be accessed by typing the command ```explorer.exe .```. -* A folder or file can be opened with Visual Studio Code by typing the command ```code . or code myfile.ext```. -* Surprisingly, Windows executables can be accessed in the Linux terminal by running them with .exe at the end (does not mean they will work correctly). -![Running Windows executables in WSL2](img/executaveis_do_windows_no_wsl2.png) -* Some Linux graphical applications can be run with WSL 2. Read 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 installed Linux distributions and their current status (stopped or running). -![Checking installed Linux distributions in WSL 2](img/verificando_distribuicoes_instaladas_do_linux_no_wsl2.png) -* Run the command ```wsl --shutdown``` with PowerShell to shut down all running Linux distributions at the moment (when executing the command, Docker distributions will also be shut down and Docker Desktop will show a notification next to the clock asking if you want to start its distributions again, if you do not accept you will have to start Docker again with the icon near the Windows clock). -* Run the command ```wsl --t ``` with PowerShell to shut down only a specific Linux distribution. -* If you notice that WSL 2 is consuming too many machine resources, execute the following commands within the WSL 2 terminal to free up RAM: ```bash echo 1 | sudo tee /proc/sys/vm/drop_caches ``` -* Add `export DOCKER_BUILDKIT=1` at the end of the .profile file of your Linux user to gain more performance when building with Docker. Run the command `source ~/.profile` to load this environment variable in your WSL 2 environment. -* If you want to automate the docker startup (other services can also be started), described in the disadvantages section of using native docker, while wsl.conf is not included, you can configure a task in Windows to run commands in WSL, see the following tutorial, [WSL 2: Run Ubuntu Services on Windows 10 Startup](https://techbrij.com/wsl-2-ubuntu-services-windows-10-startup), replacing the contents of the /etc/init-wsl file with one of the examples below: -Example of Docker service initialization: +This method is aggressive as it releases RAM instantly but may be necessary in some cases. -```bash -#!/bin/sh -#Startup message -echo initializing services -#Start Docker service -service docker start +> 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 ``` -Example of generating a log on the Desktop: +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 -#!/bin/sh -#Record the start date/time in the log -date +%d/%m/%Y%t%H:%M:%S >> /mnt/c/Users/your-windows-username/Desktop/wsl_start.log -#Record the startup message in the log -echo initializing services >> /mnt/c/Users/your-windows-username/Desktop/wsl_start.log -#Start the Docker service and record the result in the log -service docker start >> /mnt/c/Users/your-windows-username/Desktop/wsl_start.log -#Check the status of the Docker service and record the result in the log -service docker status >> /mnt/c/Users/your-windows-username/Desktop/wsl_start.log +wsl --system -d df -h /mnt/wslg/distro ``` -* Unfortunately, if you manually restart the WSL, you will need to manually restart the services or run init-wsl manually. -* In Windows 11, it is possible to start Docker automatically, see the section: [Tip for Windows 11](#tip-for-windows-11). +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 +### Dúvidas sobre o Docker Desktop -* Does WSL 2 work with other virtual machines like **VirtualBox** or **VMWare**? Follow the [reference](https://docs.microsoft.com/pt-br/windows/wsl/wsl2-faq#will-i-be-able-to-run-wsl-2-and-other-3rd-party-virtualization-tools-such-as-vmware-or-virtualbox). \ No newline at end of file +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) \ No newline at end of file diff --git a/README.md b/README.md index 46e5670..8b7ebf5 100644 --- a/README.md +++ b/README.md @@ -1,50 +1,118 @@

- +

-# Guia rápido do WSL2 + Docker +# Guia/Tutorial rápido do WSL2 + Docker *Read this in other language: [English](README.en.md) ## Sumário -- [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) - - [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 do Linux de WSL 1 para WSL 2](#opcional-alterar-a-versão-de-uma-distribuição-do-linux-de-wsl-1-para-wsl-2) - - [Instalação do WSL 2 via Windows Store](#instalação-do-wsl-2-via-windows-store) -- [(Opcional/Mas Recomendado) Usar Windows Terminal como terminal padrão de desenvolvimento para Windows](#opcionalmas-recomendado-usar-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) -- [O que é o Docker](#o-que-é-docker) +
+ + 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) + - [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 do Linux de WSL 1 para WSL 2](#opcional-alterar-a-versão-de-uma-distribuição-do-linux-de-wsl-1-para-wsl-2) + - [Instalação do WSL 2 via Windows Store](#instalação-do-wsl-2-via-windows-store) + - [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) - - [(Obsoleto) Docker Toolbox](#obsoleto-docker-toolbox) - - [(Obsoleto) Docker Desktop com Hyper-V](#obsoleto-docker-desktop-com-hyper-v) - - [Docker Desktop com WSL 2](#docker-desktop-com-wsl2) - - [Vantagens](#docker-desktop-vantagens) - - [Desvantagens](#docker-desktop-desvantagens) - - [Docker Engine (Docker Nativo) diretamente instalado no WSL2](#docker-engine-docker-nativo-diretamente-instalado-no-wsl2) - - [Vantagens](#docker-engine-vantagens) - - [Desvantagens](#docker-engine-desvantagens) - - [Integrar Docker com WSL 2](#integrar-docker-com-wsl-2) - - [1 - Instalar o Docker com Docker Engine (Docker Nativo)](#1---instalar-o-docker-com-docker-engine-docker-nativo) + - [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 (apenas para Windows 11)](#iniciar-o-docker-automaticamente-no-wsl-apenas-para-windows-11-ou-windows-10-com-o-update-kb5020030) - - [Systemd](#systemd) - - [Docker com Systemd](#docker-com-systemd) - - [2 - Instalar o Docker com Docker Desktop](#2---instalar-o-docker-com-docker-desktop) -- [Dicas e truques básicos com WSL 2](#dicas-e-truques-básicos-com-wsl-2) -- [Dúvidas](#dúvidas) -- [Quer dicas como ser mais produtivo no Windows?](#quer-dicas-como-ser-mais-produtivo-no-windows) + - [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 e o nome a isto foi dado de **WSL** ou **Windows Subsystem for Linux**. +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. @@ -62,24 +130,24 @@ Compare as versões do WSL: [https://docs.microsoft.com/pt-br/windows/wsl/compar ## Requisitos mínimos -* Windows 10 Home ou Professional +* **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 +* **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 habilita-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 o `menu de notificações perto do relógio > Todas as configurações > Sistema > Sobre`. Caso não esteja, use o Assistente do Windows Update para atualizar a sua versão do Windows. +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.** +> **É 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 -> ## Windows 10/11 +Todas as instruções abaixo são para o Windows 10/11. ### Windows Update @@ -87,17 +155,15 @@ Verifique se seu Windows está atualizado, pois o WSL 2 depende de uma versão a ### Atualizar o WSL -Com a versão 2004 do Windows 10 ou Windows 11, o WSL já está presente em sua máquina, execute o comando para pegar a versão mais recente do WSL: +Com a versão 2004 do Windows 10 ou Windows 11, o WSL já estará presente em sua máquina, execute o comando para pegar a versão mais recente do WSL: ``` bash wsl --update ``` -E pegue a versão mais recente do WSL. - ### Atribuir a versão default do WSL para a versão 2 -A versão 1 do WSL pode ser a padrão em sua máquina, execute o comando abaixo para definir como padrão a versão 2: +A versão 2 normalmente é a default, mas a versão 1 do WSL pode estar como default, execute o comando abaixo para definir como default a versão 2: ``` bash wsl --set-default-version 2 @@ -117,11 +183,11 @@ Se você quiser instalar uma versão diferente do Ubuntu, execute o comando `wsl 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 do comando, você deverá criar um **nome de usuário** que poderá ser o mesmo da sua máquina e uma **senha**, este será o usuário **root da sua instância WSL**. +Após o término do comando, você deverá criar um **nome de usuário** que poderá ser o mesmo da sua máquina (crie um nome de usuário sem espaço e caracteres especiais) e uma **senha** (defina uma senha forte). Esta senha será usada para instalar pacotes e realizar operações de superusuário. Para abrir uma nova janela do Ubuntu, basta digitar `Ubuntu` no menu iniciar e clicar no ícone do Ubuntu. -Recomendamos o uso do [Windows Terminal](https://docs.microsoft.com/pt-br/windows/terminal/get-started) como terminal padrão para desenvolvimento no Windows. Ele agregará o shell do Ubuntu, assim como o PowerShell e o CMD em uma única janela. +Recomendamos o uso do [Windows Terminal](https://docs.microsoft.com/pt-br/windows/terminal/get-started) como terminal padrão para desenvolvimento no Windows. Ele agregará o shell do Ubuntu, assim como o PowerShell e o CMD em uma única janela, além de permitir personalização de cores e temas. ### (Opcional) Alterar a versão de uma distribuição do Linux de WSL 1 para WSL 2 @@ -131,52 +197,125 @@ Se a distribuição Linux que você instalou estiver na versão 1, você pode al wsl --set-version 2 ``` -Parabéns, seu WSL2 já está funcionando: +Parabéns, seu WSL2 já está funcionando! -![Exemplo de WSL2 funcionando](img/wsl2_funcionando.png) +![Exemplo de WSL2 funcionando](img/wsl2-working.png) ### Instalação do WSL 2 via Windows Store -Também é possível instalar distribuições Linux pelo Windows Store. Escolha sua distribuição Linux preferida no aplicativo Windows Store, 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. +Também é possível instalar distribuições Linux pelo Windows Store. Basta acessar o Windows Store e procurar pelo nome da distribuição Linux desejada e clicar em instalar. + +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. + +![Distribuições Linux no Windows Store](img/linux-distros.png) + + +### 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`. -![Distribuições Linux no Windows Store](img/distribuicoes_linux.png) +![Conectar ao WSL 2 no VSCode](img/vscode-remote-wsl.png) +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. -## (Opcional/Mas Recomendado) Usar Windows Terminal como terminal padrão de desenvolvimento para Windows +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 e use estas [configurações padrões](windows-terminal-settings.json) para habilitar WSL 2, Git Bash e o tema drácula e alguns atalhos. +Instale-o pelo Windows Store. -[Link do Windows Terminal](https://docs.microsoft.com/pt-br/windows/terminal/get-started) +Veja mais opções de configuração dele em [Mais sobre o Windows Terminal](https://docs.microsoft.com/pt-br/windows/terminal/get-started). -Para sobrescrever as configurações **acesse o menu configurações e clique no botão "abrir arquivo JSON configurações**, abrirá as configurações do Windows Terminal no VSCode, apenas cole o conteúdo do arquivo JSON e salve, após isso clique em `Ubuntu` na seção `Perfis`, clique sobre `Diretório inicial` e altere o caminho para: `(\\wsl$\Ubuntu\home\SEU_USUÁRIO_UBUNTU)`. +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 todo disco rígido. +* 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. - -Isto pode não ser interessante, uma vez que o WSL 2 pode usar praticamente todos os recursos de sua máquina, mas podemos configurar limites. +* A usar 25% da memória disponível para SWAP (memória virtual). -Crie um arquivo chamado `.wslconfig` na raiz da sua pasta de usuário `(C:\Users\)` e defina estas configurações: +Se você quiser personalizar estes limites, crie um arquivo chamado `.wslconfig` na raiz da sua pasta de usuário `(C:\Users\)` e defina estas configurações: -```txt +```conf [wsl2] memory=8GB processors=4 -swap=2GB ``` 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). + + +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. + +![Arquitetura do WSLg](img/WSLg_ArchitectureOverview.png) + +### 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. @@ -187,84 +326,136 @@ Configurar ambientes de desenvolvimento no Windows sempre foi burocrático e com 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=On_nwfkiSAE](https://www.youtube.com/watch?v=On_nwfkiSAE). +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 +## Modos de usar Docker no Windows -* (Obsoleto) [Docker Toolbox](#obsoleto-docker-toolbox) -* (Obsoleto) [Docker Desktop com Hyper-V](#obsoleto-docker-desktop-com-hyper-v). -* [Docker Desktop com WSL2](#docker-desktop-com-wsl2). -* [Docker Engine (Docker Nativo) diretamente instalado no WSL2](#docker-engine-docker-nativo-diretamente-instalado-no-wsl2). +* 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). -### (Obsoleto) Docker Toolbox +### 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. -### (Obsoleto) Docker Desktop com Hyper-V +### 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. -*A Docker já removeu o suporte ao Hyper-V.* - -### Docker Desktop com WSL2 - -Roda em cima do **Virtual Machine Platform** que é um componente do Hyper-V. +### 3. Docker Desktop com WSL2 -Se integra com o WSL2 permitindo rodar o Docker dentro do ambiente do Linux. +> 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) -Não é necessário adquirir licença PRO do Windows 10/11. T +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. -Tem um grande desempenho e consome menos recursos quando comparado ao Docker Toolbox ou Docker Desktop com Hyper-V. +Não é necessário adquirir licença PRO do Windows 10/11. -Tem-se a grande vantagem de se trabalhar totalmente dentro do Linux para desenvolvimento, portanto, usar WSL2 + Docker é a melhor maneira de se desenvolver aplicações no Windows. +Tem um grande desempenho e consome menos recursos quando comparado ao Docker Toolbox ou Docker Desktop com Hyper-V. #### 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. -* Interface visual para administrar o Docker. #### Desvantagens -* Uso de memória inicial sem rodar nenhum container Docker pode chegar a 3GB. -* Adiciona infraestrutura complexa para executar Docker, quando se necessita apenas de rodar os containers Docker dentro de um WSL apenas. +* 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 -### 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/). -O Docker Engine é o Docker nativo 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. #### Vantagens -* Consume o mínimo de memória necessário para rodar o Docker Daemon (servidor do Docker). -* É mais rápido ainda que com Docker Desktop, porque roda diretamente dentro da própria instância do WSL2 e não em uma instância separada de Linux. -* Temos a melhor experiência de desenvolvimento, pois podemos usar o Docker diretamente dentro do WSL 2, sem precisar de uma instância separada do Docker Desktop. +* 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. #### Desvantagens -* Necessário executar o comando ```sudo service docker start``` sempre que o WSL 2 foi reiniciado (Somente para usuários do Windows 10 sem o update KB5020030). Isto não é necessariamente uma desvantagem, mas é bom pontuar. Isto é um pequeno detalhe, mas no Windows 11 já é possível iniciar o servidor do Docker automaticamente pelo /etc/wsl.conf (Ver detalhes mais abaixo). * 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. -### Integrar Docker com WSL 2 +## Qual modo de usar Docker no Windows escolher? -No início deste tutorial vimos [4 modos de usar Docker no Windows](#modos-de-usar-docker-no-windows), mas somente 2 que recomendamos: +As 2 primeiras opções são obsoletas e não recomendamos seu uso. As 2 últimas opções são as mais recomendadas. -* [Docker Engine (Docker Nativo) diretamente instalado no WSL2](#instalar-o-docker-com-docker-engine-docker-nativo). -* [Docker Desktop com WSL2](#instalar-o-docker-com-docker-desktop). +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. -Recomendamos que escolha a 1ª opção pelos seus benefícios, já que a maioria das pessoas poderão usar o WSL 2 como ferramenta central para desenvolvimento, mas, neste tutorial vamos mostrar as duas formas de instalação. +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. -### 1 - Instalar o Docker com Docker Engine (Docker Nativo) +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: + +![Docker Desktop instalado](img/installing-docker-desktop.png) + +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. + +![Distribuições Linux rodando no WSL 2](img/wsl-docker-desktop-running.png) + +#### 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: + +![Ativar Docker na distribuição Linux](img/docker-desktop-wsl-integration.png) + +#### 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: + +![Ativar Resource Save Mode no Docker Desktop](img/resource-saver.png) + +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. + +### 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. @@ -341,8 +532,6 @@ Este comando acima terá que ser executado toda vez que o Linux for reiniciado. Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running? ``` -O Docker Compose instalado agora estará na versão 2, para executa-lo em vez de `docker-compose` use `docker compose`. - #### Erro ao iniciar o Docker no Ubuntu 22.04 > Se mesmo ao iniciar o serviço do Docker acontecer o seguinte erro ou similar: @@ -353,7 +542,9 @@ O Docker Compose instalado agora estará na versão 2, para executa-lo em vez de > 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) +#### 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`: @@ -370,11 +561,190 @@ Aperte a letra `i` (para entrar no modo de inserção de conteúdo) e cole o con command = service docker start ``` -#### Systemd +#### Docker com 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. +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. + +![Mount no WSL2](img/mount-in-wsl2.png) + +### 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$`. + +![Acessando WSL2 no Windows Explorer](img/acessing-wsl-win-explorer.png) + +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 -Não é obrigatório ativa-lo e a qualquer momento ele pode ser desativado e reativado. Para ativa-lo, edite o arquivo `/etc/wsl.conf`: +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`. + +![Conectar ao WSL 2 no VSCode](img/vscode-remote-wsl.png) + +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. + +![Executando executáveis do Windows no WSL2](img/executables-win-in-wsl2.png) + +### 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 `. + +![Verificando distribuições instaladas do Linux no WSL 2](img/check-installed-distros.png) + +> 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\\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: @@ -386,69 +756,99 @@ Aperte a letra `i` (para entrar no modo de inserção de conteúdo) e cole o con ```conf [boot] -systemd = true +command = service docker start ``` -Quando terminar a edição, pressione `Esc`, em seguida tecle `:` para entrar com o comando `wq` (salvar e sair) e pressione `enter`. +### Liberar memória RAM do WSL 2 -Toda vez que esta mudança for realizada é necessário reiniciar o WSL com o comando `wsl --shutdown` no DOS ou PowerShell. +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: -#### Docker com Systemd +```bash +echo 1 | sudo tee /proc/sys/vm/drop_caches +``` -Quando ativamos 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`. +Este método é agressivo, porque libera instantaneamente a memória RAM, mas pode ser necessário em alguns casos. -Caso contrário, você pode inicia-lo automaticamente usando os comandos: +> 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. -```bash -sudo systemctl enable docker.service -sudo systemctl enable containerd.service +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 ``` -É necessário reiniciar o WSL com o comando `wsl --shutdown` para que as mudanças tenham efeito. +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 -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?` +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. -### 2 - Instalar o Docker com Docker Desktop +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`. -Baixe neste link: [https://www.docker.com/products/docker-desktop/](https://www.docker.com/products/docker-desktop/) e instale o Docker Desktop. +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). -Clique no `ícone do Docker perto do relógio -> Settings -> Settings no topo -> Resources -> WSL Integration`. +> 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. -Habilite `Enable integration with my default WSL distro` e habilite sua versão Linux. +Esta opção só funcionará após reiniciar o WSL com o comando `wsl --shutdown`. -![Docker funcionando dentro do WSL 2](img/docker_funcionando_dentro_do_wsl2.png) +### 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. -## Dicas e truques básicos com WSL 2 +Uma maneira simples de verificar o tamanho do disco é rodar o seguinte comando no PowerShell ou DOS: -* 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. -* Para abrir o terminal do WSL basta digitar o nome da distribuição no menu Iniciar ou executar `C:\Windows\System32\wsl.exe`. -* O sistema de arquivos do Windows 10/11 é acessível em `/mnt/c`. -![Mount no WSL2](img/mount_no_wsl2.png) -* É possível acessar o sistema de arquivos do Linux pela rede do Windows, digite `\\wsl$` no Windows Explorer. -![Acessando WSL2 no Windows Explorer](img/acessando_wsl2_no_explorer.png) -* É possível acessar uma pasta no Windows Explorer digitando o comando ```explorer.exe .```. -* É possível abrir uma pasta ou arquivo com o Visual Studio Code digitando o comando ```code . ou code meu_arquivo.ext```. -* Incrivelmente é possível acessar executáveis do Windows no terminal do Linux executando-os com .exe no final (não significa que funcionarão corretamente). -![Executando executáveis do Windows no WSL2](img/executaveis_do_windows_no_wsl2.png) -* É 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). -![Verificando distribuições instaladas do Linux no WSL 2](img/verificando_distribuicoes_instaladas_do_linux_no_wsl2.png) -* Execute o comando ```wsl --shutdown``` com o PowerShell para desligar todas as distribuições Linux que estão rodando no momento (ao executar o comando, as distribuições do Docker também serão desligadas e o Docker Desktop mostrará uma notificação ao lado do relógio perguntando se você quer iniciar as distribuições dele novamente, se você não aceitar terá que iniciar o Docker novamente com o ícone perto do relógio do Windows). -* Execute com o PowerShell o comando ```wsl --t ``` para desligar somente uma distribuição Linux específica. -* Se verificar que o WSL 2 está consumindo muitos recursos da máquina, execute os seguintes comandos dentro do terminal WSL 2 para liberar memória RAM: ```bash -echo 1 | sudo tee /proc/sys/vm/drop_caches +wsl --system -d df -h /mnt/wslg/distro ``` -* Acrescente `export DOCKER_BUILDKIT=1` no final do arquivo .profile do seu usuário do Linux 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. -* No Windows 11 ou Windows 10 com update KB5020030 é possível iniciar o Docker automaticamente, veja a seção: [Dica para Windows 11](#iniciar-o-docker-automaticamente-no-wsl-apenas-para-windows-11) + +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 -* 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-) +### 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 dicas como ser mais produtivo no Windows? +### Quer configurar um ambiente mais produtivo no Windows? Acesse os tutorias abaixo: diff --git a/img/WSLg_ArchitectureOverview.png b/img/WSLg_ArchitectureOverview.png new file mode 100644 index 0000000..cf6193b Binary files /dev/null and b/img/WSLg_ArchitectureOverview.png differ diff --git a/img/acessando_wsl2_no_explorer.png b/img/acessing-wsl-win-explorer.png similarity index 100% rename from img/acessando_wsl2_no_explorer.png rename to img/acessing-wsl-win-explorer.png diff --git a/img/verificando_distribuicoes_instaladas_do_linux_no_wsl2.png b/img/check-installed-distros.png similarity index 100% rename from img/verificando_distribuicoes_instaladas_do_linux_no_wsl2.png rename to img/check-installed-distros.png diff --git a/img/docker-desktop-wsl-integration.png b/img/docker-desktop-wsl-integration.png new file mode 100644 index 0000000..6239141 Binary files /dev/null and b/img/docker-desktop-wsl-integration.png differ diff --git a/img/docker_funcionando_dentro_do_wsl2.png b/img/docker_funcionando_dentro_do_wsl2.png deleted file mode 100644 index 7aea2ba..0000000 Binary files a/img/docker_funcionando_dentro_do_wsl2.png and /dev/null differ diff --git a/img/executaveis_do_windows_no_wsl2.png b/img/executables-win-in-wsl2.png similarity index 100% rename from img/executaveis_do_windows_no_wsl2.png rename to img/executables-win-in-wsl2.png diff --git a/img/installing-docker-desktop.png b/img/installing-docker-desktop.png new file mode 100644 index 0000000..8abc745 Binary files /dev/null and b/img/installing-docker-desktop.png differ diff --git a/img/distribuicoes_linux.png b/img/linux-distros.png similarity index 100% rename from img/distribuicoes_linux.png rename to img/linux-distros.png diff --git a/img/mount_no_wsl2.png b/img/mount-in-wsl2.png similarity index 100% rename from img/mount_no_wsl2.png rename to img/mount-in-wsl2.png diff --git a/img/resource-saver.png b/img/resource-saver.png new file mode 100644 index 0000000..b51580f Binary files /dev/null and b/img/resource-saver.png differ diff --git a/img/vscode-remote-wsl.png b/img/vscode-remote-wsl.png new file mode 100644 index 0000000..630af71 Binary files /dev/null and b/img/vscode-remote-wsl.png differ diff --git a/img/wsl-docker-desktop-running.png b/img/wsl-docker-desktop-running.png new file mode 100644 index 0000000..32ff12c Binary files /dev/null and b/img/wsl-docker-desktop-running.png differ diff --git a/img/wsl2_funcionando.png b/img/wsl2-working.png similarity index 100% rename from img/wsl2_funcionando.png rename to img/wsl2-working.png diff --git a/windows-terminal-settings.json b/windows-terminal-settings.json deleted file mode 100644 index d01df04..0000000 --- a/windows-terminal-settings.json +++ /dev/null @@ -1,792 +0,0 @@ -{ - "$help": "https://aka.ms/terminal-documentation", - "$schema": "https://aka.ms/terminal-profiles-schema", - "actions": - [ - { - "command": - { - "action": "copy", - "singleLine": false - }, - "keys": "ctrl+c" - }, - { - "command": "paste", - "keys": "ctrl+v" - }, - { - "command": "duplicateTab", - "keys": "ctrl+f3" - }, - { - "command": - { - "action": "newTab" - }, - "keys": "ctrl+f1" - }, - { - "command": "find", - "keys": "ctrl+shift+f" - }, - { - "command": - { - "action": "splitPane", - "split": "auto", - "splitMode": "duplicate" - }, - "keys": "alt+shift+d" - } - ], - "alwaysOnTop": false, - "copyFormatting": "none", - "copyOnSelect": true, - "defaultProfile": "{2c4de342-38b7-51cf-b940-2309a097f518}", - "profiles": - { - "defaults": - { - "colorScheme": "Dracula" - }, - "list": - [ - { - "font": - { - "face": "MesloLGS NF", - "size": 11 - }, - "guid": "{2c4de342-38b7-51cf-b940-2309a097f518}", - "hidden": false, - "name": "Ubuntu", - "source": "Windows.Terminal.Wsl", - "startingDirectory": "\\\\wsl$\\Ubuntu\\home\\argen\\" - }, - { - "guid": "{61c54bbd-c2c6-5271-96e7-009a87ff44bf}", - "hidden": false, - "name": "Windows PowerShell" - }, - { - "guid": "{0caa0dad-35be-5f56-a8ff-afceeeaa6101}", - "hidden": false, - "name": "Prompt de comando" - }, - { - "guid": "{b453ae62-4e3d-5e58-b989-0a998ec441b8}", - "hidden": false, - "name": "Azure Cloud Shell", - "source": "Windows.Terminal.Azure" - }, - { - "guid": "{07b52e3e-de2c-5db4-bd2d-ba144ed6c273}", - "hidden": false, - "name": "Ubuntu-20.04", - "source": "Windows.Terminal.Wsl" - }, - { - "guid": "{20f38a4b-26ad-54d9-aec9-7c1c28b32b4b}", - "hidden": false, - "name": "Ubuntu-Old", - "source": "Windows.Terminal.Wsl" - }, - { - "guid": "{659fb644-3252-552c-bab8-b2124f7d97b9}", - "hidden": false, - "name": "Ubuntu-Test", - "source": "Windows.Terminal.Wsl" - }, - { - "guid": "{17bf3de4-5353-5709-bcf9-835bd952a95e}", - "hidden": true, - "name": "Ubuntu-22.04", - "source": "Windows.Terminal.Wsl" - }, - { - "guid": "{f9ceaf27-504c-58d7-927c-d1d6a7ac7d3c}", - "hidden": false, - "name": "Ubuntu 22.04.1 LTS", - "source": "CanonicalGroupLimited.Ubuntu22.04LTS_79rhkp1fndgsc" - }, - { - "guid": "{94fdb6eb-31c6-5aaa-bac5-8161e463d3f7}", - "hidden": false, - "name": "Ubuntu-Backup", - "source": "Windows.Terminal.Wsl" - } - ] - }, - "schemes": - [ - { - "background": "#111416", - "black": "#000000", - "blue": "#1093F5", - "brightBlack": "#404040", - "brightBlue": "#11B5F6", - "brightCyan": "#00FFFF", - "brightGreen": "#00FF00", - "brightPurple": "#FF00FF", - "brightRed": "#FF0000", - "brightWhite": "#FFFFFF", - "brightYellow": "#FFFF00", - "cursorColor": "#BBBBBB", - "cyan": "#00CDCD", - "foreground": "#EEEEEC", - "green": "#00CD00", - "name": "Abernathy", - "purple": "#CD00CD", - "red": "#CD0000", - "selectionBackground": "#EEEEEC", - "white": "#FAEBD7", - "yellow": "#CDCD00" - }, - { - "background": "#212121", - "black": "#151515", - "blue": "#6C99BB", - "brightBlack": "#505050", - "brightBlue": "#6C99BB", - "brightCyan": "#7DD6CF", - "brightGreen": "#7E8E50", - "brightPurple": "#9F4E85", - "brightRed": "#AC4142", - "brightWhite": "#F5F5F5", - "brightYellow": "#E5B567", - "cursorColor": "#D0D0D0", - "cyan": "#7DD6CF", - "foreground": "#D0D0D0", - "green": "#7E8E50", - "name": "Afterglow", - "purple": "#9F4E85", - "red": "#AC4142", - "selectionBackground": "#303030", - "white": "#D0D0D0", - "yellow": "#E5B567" - }, - { - "background": "#262A33", - "black": "#000000", - "blue": "#2472C8", - "brightBlack": "#666666", - "brightBlue": "#2472C8", - "brightCyan": "#0FA8CD", - "brightGreen": "#05BC79", - "brightPurple": "#BC3FBC", - "brightRed": "#CD3131", - "brightWhite": "#E5E5E5", - "brightYellow": "#E5E512", - "cursorColor": "#FFFFFF", - "cyan": "#0FA8CD", - "foreground": "#E5E5E5", - "green": "#05BC79", - "name": "Andromeda", - "purple": "#BC3FBC", - "red": "#CD3131", - "selectionBackground": "#FFFFFF", - "white": "#E5E5E5", - "yellow": "#E5E512" - }, - { - "background": "#0E1019", - "black": "#232323", - "blue": "#008DF8", - "brightBlack": "#444444", - "brightBlue": "#0092FF", - "brightCyan": "#67FFF0", - "brightGreen": "#ABE15B", - "brightPurple": "#9A5FEB", - "brightRed": "#FF2740", - "brightWhite": "#FFFFFF", - "brightYellow": "#FFD242", - "cursorColor": "#FFFFFF", - "cyan": "#00D8EB", - "foreground": "#FFFAF4", - "green": "#8CE10B", - "name": "Argonaut", - "purple": "#6D43A6", - "red": "#FF000F", - "selectionBackground": "#FFFFFF", - "white": "#FFFFFF", - "yellow": "#FFB900" - }, - { - "background": "#1E2127", - "black": "#4A505D", - "blue": "#285BFF", - "brightBlack": "#61697A", - "brightBlue": "#199FFD", - "brightCyan": "#50ACAE", - "brightGreen": "#37BD58", - "brightPurple": "#FC58F6", - "brightRed": "#FC4A6D", - "brightWhite": "#FFFFFF", - "brightYellow": "#F6BE48", - "cursorColor": "#FFFFFF", - "cyan": "#366F9A", - "foreground": "#ABB2BF", - "green": "#23974A", - "name": "BlulocoDark", - "purple": "#8C62FD", - "red": "#F81141", - "selectionBackground": "#FFFFFF", - "white": "#CCD5E5", - "yellow": "#FD7E57" - }, - { - "background": "#31363B", - "black": "#31363B", - "blue": "#1D99F3", - "brightBlack": "#7F8C8D", - "brightBlue": "#3DAEE9", - "brightCyan": "#16A085", - "brightGreen": "#1CDC9A", - "brightPurple": "#8E44AD", - "brightRed": "#C0392B", - "brightWhite": "#FCFCFC", - "brightYellow": "#FDBC4B", - "cursorColor": "#FFFFFF", - "cyan": "#1ABC9C", - "foreground": "#EFF0F1", - "green": "#11D116", - "name": "Breeze", - "purple": "#9B59B6", - "red": "#ED1515", - "selectionBackground": "#FFFFFF", - "white": "#EFF0F1", - "yellow": "#F67400" - }, - { - "background": "#191919", - "black": "#191919", - "blue": "#76D4FF", - "brightBlack": "#191919", - "brightBlue": "#76D5FF", - "brightCyan": "#6CBFB5", - "brightGreen": "#B7E876", - "brightPurple": "#BA76E7", - "brightRed": "#FF355B", - "brightWhite": "#C2C8D7", - "brightYellow": "#FFC251", - "cursorColor": "#FFFFFF", - "cyan": "#6CBFB5", - "foreground": "#B3C9D7", - "green": "#B7E876", - "name": "Bright Lights", - "purple": "#BA76E7", - "red": "#FF355B", - "selectionBackground": "#FFFFFF", - "white": "#C2C8D7", - "yellow": "#FFC251" - }, - { - "background": "#0C0C0C", - "black": "#0C0C0C", - "blue": "#0037DA", - "brightBlack": "#767676", - "brightBlue": "#3B78FF", - "brightCyan": "#61D6D6", - "brightGreen": "#16C60C", - "brightPurple": "#B4009E", - "brightRed": "#E74856", - "brightWhite": "#F2F2F2", - "brightYellow": "#F9F1A5", - "cursorColor": "#FFFFFF", - "cyan": "#3A96DD", - "foreground": "#CCCCCC", - "green": "#13A10E", - "name": "Campbell", - "purple": "#881798", - "red": "#C50F1F", - "selectionBackground": "#FFFFFF", - "white": "#CCCCCC", - "yellow": "#C19C00" - }, - { - "background": "#012456", - "black": "#0C0C0C", - "blue": "#0037DA", - "brightBlack": "#767676", - "brightBlue": "#3B78FF", - "brightCyan": "#61D6D6", - "brightGreen": "#16C60C", - "brightPurple": "#B4009E", - "brightRed": "#E74856", - "brightWhite": "#F2F2F2", - "brightYellow": "#F9F1A5", - "cursorColor": "#FFFFFF", - "cyan": "#3A96DD", - "foreground": "#CCCCCC", - "green": "#13A10E", - "name": "Campbell Powershell", - "purple": "#881798", - "red": "#C50F1F", - "selectionBackground": "#FFFFFF", - "white": "#CCCCCC", - "yellow": "#C19C00" - }, - { - "background": "#0E0E0E", - "black": "#000000", - "blue": "#2472C8", - "brightBlack": "#666666", - "brightBlue": "#3B8EEA", - "brightCyan": "#29B8DB", - "brightGreen": "#23D18B", - "brightPurple": "#D670D6", - "brightRed": "#F14C4C", - "brightWhite": "#E5E5E5", - "brightYellow": "#F5F543", - "cursorColor": "#FFFFFF", - "cyan": "#11A8CD", - "foreground": "#CCCCCC", - "green": "#0DBC79", - "name": "Dark+", - "purple": "#BC3FBC", - "red": "#CD3131", - "selectionBackground": "#FFFFFF", - "white": "#E5E5E5", - "yellow": "#E5E510" - }, - { - "background": "#212121", - "black": "#21222C", - "blue": "#82AAFF", - "brightBlack": "#545454", - "brightBlue": "#D6ACFF", - "brightCyan": "#A4FFFF", - "brightGreen": "#69FF94", - "brightPurple": "#FF92DF", - "brightRed": "#FF6E6E", - "brightWhite": "#F8F8F2", - "brightYellow": "#FFCB6B", - "cursorColor": "#ECEFF4", - "cyan": "#8BE9FD", - "foreground": "#F8F8F2", - "green": "#50FA7B", - "name": "Dracula", - "purple": "#C792EA", - "red": "#FF5555", - "selectionBackground": "#F8F8F2", - "white": "#F8F8F2", - "yellow": "#FFCB6B" - }, - { - "background": "#232322", - "black": "#212121", - "blue": "#134EB2", - "brightBlack": "#424242", - "brightBlue": "#54A4F3", - "brightCyan": "#26BBD1", - "brightGreen": "#7ABA3A", - "brightPurple": "#AA4DBC", - "brightRed": "#E83B3F", - "brightWhite": "#D9D9D9", - "brightYellow": "#FFEA2E", - "cursorColor": "#16AFCA", - "cyan": "#0E717C", - "foreground": "#E5E5E5", - "green": "#457B24", - "name": "MaterialDark", - "purple": "#560088", - "red": "#B7141F", - "selectionBackground": "#DFDFDF", - "white": "#EFEFEF", - "yellow": "#F6981E" - }, - { - "background": "#212121", - "black": "#000000", - "blue": "#82AAFF", - "brightBlack": "#545454", - "brightBlue": "#82AAFF", - "brightCyan": "#89DDFF", - "brightGreen": "#C3E88D", - "brightPurple": "#C792EA", - "brightRed": "#FF5370", - "brightWhite": "#FFFFFF", - "brightYellow": "#FFCB6B", - "cursorColor": "#FFFFFF", - "cyan": "#89DDFF", - "foreground": "#EEFFFF", - "green": "#C3E88D", - "name": "MaterialDarker", - "purple": "#C792EA", - "red": "#FF5370", - "selectionBackground": "#EEFFFF", - "white": "#FFFFFF", - "yellow": "#FFCB6B" - }, - { - "background": "#121212", - "black": "#121212", - "blue": "#1080D0", - "brightBlack": "#555555", - "brightBlue": "#00AFFF", - "brightCyan": "#51CEFF", - "brightGreen": "#B1E05F", - "brightPurple": "#AF87FF", - "brightRed": "#F6669D", - "brightWhite": "#FFFFFF", - "brightYellow": "#FFF26D", - "cursorColor": "#BBBBBB", - "cyan": "#43A8D0", - "foreground": "#BBBBBB", - "green": "#98E123", - "name": "Molokai", - "purple": "#8700FF", - "red": "#FA2573", - "selectionBackground": "#B5D5FF", - "white": "#BBBBBB", - "yellow": "#DFD460" - }, - { - "background": "#403E41", - "black": "#403E41", - "blue": "#FC9867", - "brightBlack": "#727072", - "brightBlue": "#FC9867", - "brightCyan": "#78DCE8", - "brightGreen": "#A9DC76", - "brightPurple": "#AB9DF2", - "brightRed": "#FF6188", - "brightWhite": "#FCFCFA", - "brightYellow": "#FFD866", - "cursorColor": "#FCFCFA", - "cyan": "#78DCE8", - "foreground": "#FCFCFA", - "green": "#A9DC76", - "name": "Monokai Pro", - "purple": "#AB9DF2", - "red": "#FF6188", - "selectionBackground": "#FCFCFA", - "white": "#FCFCFA", - "yellow": "#FFD866" - }, - { - "background": "#0C0C0C", - "black": "#1A1A1A", - "blue": "#9D65FF", - "brightBlack": "#625E4C", - "brightBlue": "#9D65FF", - "brightCyan": "#58D1EB", - "brightGreen": "#98E024", - "brightPurple": "#F4005F", - "brightRed": "#F4005F", - "brightWhite": "#F6F6EF", - "brightYellow": "#E0D561", - "cursorColor": "#FC971F", - "cyan": "#58D1EB", - "foreground": "#D9D9D9", - "green": "#98E024", - "name": "Monokai Remastered", - "purple": "#F4005F", - "red": "#F4005F", - "selectionBackground": "#343434", - "white": "#C4C5B5", - "yellow": "#FD971F" - }, - { - "background": "#121212", - "black": "#121212", - "blue": "#0443FF", - "brightBlack": "#838383", - "brightBlue": "#0443FF", - "brightCyan": "#51CEFF", - "brightGreen": "#B1E05F", - "brightPurple": "#F200F6", - "brightRed": "#F6669D", - "brightWhite": "#FFFFFF", - "brightYellow": "#FFF26D", - "cursorColor": "#FFFFFF", - "cyan": "#01B6ED", - "foreground": "#F9F9F9", - "green": "#98E123", - "name": "Monokai Vivid", - "purple": "#F800F8", - "red": "#FA2934", - "selectionBackground": "#FFFFFF", - "white": "#FFFFFF", - "yellow": "#FFF30A" - }, - { - "background": "#0D0D17", - "black": "#4D4D4D", - "blue": "#3182E0", - "brightBlack": "#808080", - "brightBlue": "#6096FF", - "brightCyan": "#0AE78D", - "brightGreen": "#0AE78D", - "brightPurple": "#FF78A2", - "brightRed": "#F16D86", - "brightWhite": "#FFFFFF", - "brightYellow": "#FFFC67", - "cursorColor": "#FFFFFF", - "cyan": "#09C87A", - "foreground": "#E6E5E5", - "green": "#09CD7E", - "name": "Nocturnal Winter", - "purple": "#FF2B6D", - "red": "#F12D52", - "selectionBackground": "#FFFFFF", - "white": "#FCFCFC", - "yellow": "#F5F17A" - }, - { - "background": "#282C34", - "black": "#282C34", - "blue": "#61AFEF", - "brightBlack": "#5A6374", - "brightBlue": "#61AFEF", - "brightCyan": "#56B6C2", - "brightGreen": "#98C379", - "brightPurple": "#C678DD", - "brightRed": "#E06C75", - "brightWhite": "#DCDFE4", - "brightYellow": "#E5C07B", - "cursorColor": "#FFFFFF", - "cyan": "#56B6C2", - "foreground": "#DCDFE4", - "green": "#98C379", - "name": "One Half Dark", - "purple": "#C678DD", - "red": "#E06C75", - "selectionBackground": "#FFFFFF", - "white": "#DCDFE4", - "yellow": "#E5C07B" - }, - { - "background": "#FAFAFA", - "black": "#383A42", - "blue": "#0184BC", - "brightBlack": "#4F525D", - "brightBlue": "#61AFEF", - "brightCyan": "#56B5C1", - "brightGreen": "#98C379", - "brightPurple": "#C577DD", - "brightRed": "#DF6C75", - "brightWhite": "#FFFFFF", - "brightYellow": "#E4C07A", - "cursorColor": "#4F525D", - "cyan": "#0997B3", - "foreground": "#383A42", - "green": "#50A14F", - "name": "One Half Light", - "purple": "#A626A4", - "red": "#E45649", - "selectionBackground": "#FFFFFF", - "white": "#FAFAFA", - "yellow": "#C18301" - }, - { - "background": "#0E0E0E", - "black": "#000000", - "blue": "#2472C8", - "brightBlack": "#666666", - "brightBlue": "#3B8EEA", - "brightCyan": "#29B8DB", - "brightGreen": "#23D18B", - "brightPurple": "#D861D8", - "brightRed": "#FA4B4B", - "brightWhite": "#FAFAFA", - "brightYellow": "#FCFC5C", - "cursorColor": "#FFFFFF", - "cyan": "#33A0BB", - "foreground": "#E4E4E4", - "green": "#0DBC79", - "name": "OneStar", - "purple": "#C42CC4", - "red": "#D13B3B", - "selectionBackground": "#FFFFFF", - "white": "#F1F1F1", - "yellow": "#DFDF44" - }, - { - "background": "#002B36", - "black": "#002B36", - "blue": "#268BD2", - "brightBlack": "#073642", - "brightBlue": "#839496", - "brightCyan": "#93A1A1", - "brightGreen": "#586E75", - "brightPurple": "#6C71C4", - "brightRed": "#CB4B16", - "brightWhite": "#FDF6E3", - "brightYellow": "#657B83", - "cursorColor": "#FFFFFF", - "cyan": "#2AA198", - "foreground": "#839496", - "green": "#859900", - "name": "Solarized Dark", - "purple": "#D33682", - "red": "#DC322F", - "selectionBackground": "#FFFFFF", - "white": "#EEE8D5", - "yellow": "#B58900" - }, - { - "background": "#FDF6E3", - "black": "#002B36", - "blue": "#268BD2", - "brightBlack": "#073642", - "brightBlue": "#839496", - "brightCyan": "#93A1A1", - "brightGreen": "#586E75", - "brightPurple": "#6C71C4", - "brightRed": "#CB4B16", - "brightWhite": "#FDF6E3", - "brightYellow": "#657B83", - "cursorColor": "#002B36", - "cyan": "#2AA198", - "foreground": "#657B83", - "green": "#859900", - "name": "Solarized Light", - "purple": "#D33682", - "red": "#DC322F", - "selectionBackground": "#FFFFFF", - "white": "#EEE8D5", - "yellow": "#B58900" - }, - { - "background": "#000000", - "black": "#000000", - "blue": "#3465A4", - "brightBlack": "#555753", - "brightBlue": "#729FCF", - "brightCyan": "#34E2E2", - "brightGreen": "#8AE234", - "brightPurple": "#AD7FA8", - "brightRed": "#EF2929", - "brightWhite": "#EEEEEC", - "brightYellow": "#FCE94F", - "cursorColor": "#FFFFFF", - "cyan": "#06989A", - "foreground": "#D3D7CF", - "green": "#4E9A06", - "name": "Tango Dark", - "purple": "#75507B", - "red": "#CC0000", - "selectionBackground": "#FFFFFF", - "white": "#D3D7CF", - "yellow": "#C4A000" - }, - { - "background": "#FFFFFF", - "black": "#000000", - "blue": "#3465A4", - "brightBlack": "#555753", - "brightBlue": "#729FCF", - "brightCyan": "#34E2E2", - "brightGreen": "#8AE234", - "brightPurple": "#AD7FA8", - "brightRed": "#EF2929", - "brightWhite": "#EEEEEC", - "brightYellow": "#FCE94F", - "cursorColor": "#000000", - "cyan": "#06989A", - "foreground": "#555753", - "green": "#4E9A06", - "name": "Tango Light", - "purple": "#75507B", - "red": "#CC0000", - "selectionBackground": "#FFFFFF", - "white": "#D3D7CF", - "yellow": "#C4A000" - }, - { - "background": "#300A24", - "black": "#2E3436", - "blue": "#3465A4", - "brightBlack": "#555753", - "brightBlue": "#729FCF", - "brightCyan": "#34E2E2", - "brightGreen": "#8AE234", - "brightPurple": "#AD7FA8", - "brightRed": "#EF2929", - "brightWhite": "#EEEEEC", - "brightYellow": "#FCE94F", - "cursorColor": "#FFFFFF", - "cyan": "#06989A", - "foreground": "#EEEEEC", - "green": "#4E9A06", - "name": "Ubuntu", - "purple": "#75507B", - "red": "#CC0000", - "selectionBackground": "#FFFFFF", - "white": "#D3D7CF", - "yellow": "#C4A000" - }, - { - "background": "#300A24", - "black": "#171421", - "blue": "#0037DA", - "brightBlack": "#767676", - "brightBlue": "#08458F", - "brightCyan": "#2C9FB3", - "brightGreen": "#26A269", - "brightPurple": "#A347BA", - "brightRed": "#C01C28", - "brightWhite": "#F2F2F2", - "brightYellow": "#A2734C", - "cursorColor": "#FFFFFF", - "cyan": "#3A96DD", - "foreground": "#FFFFFF", - "green": "#26A269", - "name": "Ubuntu-22.04-ColorScheme", - "purple": "#881798", - "red": "#C21A23", - "selectionBackground": "#FFFFFF", - "white": "#CCCCCC", - "yellow": "#A2734C" - }, - { - "background": "#000000", - "black": "#000000", - "blue": "#000080", - "brightBlack": "#808080", - "brightBlue": "#0000FF", - "brightCyan": "#00FFFF", - "brightGreen": "#00FF00", - "brightPurple": "#FF00FF", - "brightRed": "#FF0000", - "brightWhite": "#FFFFFF", - "brightYellow": "#FFFF00", - "cursorColor": "#FFFFFF", - "cyan": "#008080", - "foreground": "#C0C0C0", - "green": "#008000", - "name": "Vintage", - "purple": "#800080", - "red": "#800000", - "selectionBackground": "#FFFFFF", - "white": "#C0C0C0", - "yellow": "#808000" - }, - { - "background": "#2A2139", - "black": "#FEFEFE", - "blue": "#6D77B3", - "brightBlack": "#FEFEFE", - "brightBlue": "#36F9F6", - "brightCyan": "#F92AAD", - "brightGreen": "#72F1B8", - "brightPurple": "#E1ACFF", - "brightRed": "#F88414", - "brightWhite": "#FEFEFE", - "brightYellow": "#FFF951", - "cursorColor": "#FFFFFF", - "cyan": "#F772E0", - "foreground": "#F0EFF1", - "green": "#72F1B8", - "name": "synthwave-everything", - "purple": "#C792EA", - "red": "#F97E72", - "selectionBackground": "#FFFFFF", - "white": "#FEFEFE", - "yellow": "#FEDE5D" - } - ], - "tabWidthMode": "equal" -}