How to install docker on windows 11

Что такое Docker Desktop

Docker Desktop — это инструмент для работы с Docker-контейнерами на локальной машине. Он упрощает процесс разработки, тестирования и развертывания приложений, позволяя взаимодействовать с контейнерами как через консоль, так и через удобный интерфейс. 

Ключевые особенности:

  • понятный графический интерфейс,
  • удобное управление образами и контейнерами,
  • встроенные инструменты для мониторинга,
  • возможность разработки и тестирования без привязки к серверу,
  • поддержка работы с Docker Compose.

Если вы только начинаете изучение Docker и хотите разобраться в основах, рекомендуем ознакомиться с отдельным вводным обзором. В нем разобрали принципы работы Docker, его основные компоненты и решаемые задач. Из текста вы узнаете, как создать и запустить контейнер, а также какую роль играет Kubernetes в связке c Docker.

Скриншот интерфейса Docker Desktop.

Интерфейс Docker Desktop. Источник.

О системных требованиях

Перед установкой Docker Desktop важно выбрать подходящий бэкенд для работы с контейнерами: WSL 2 или Hyper-V. Оба имеют свои особенности, так что от выбора будут зависеть и системные требования. Далее в тексте разберемся, когда и какой бэкенд подойдет лучше.

Когда нужен WSL

WSL 2 (Windows Subsystem for Linux 2) — это усовершенствованная версия подсистемы Windows для Linux, которая использует виртуальную машину с реальным Linux-ядром. В отличие от первой версии, WSL 2 обеспечивает лучшую совместимость с Linux-инструментами, технологиями и приложениями, а также более высокую производительность. 

Преимущества использования WSL 2 с Docker Desktop

Работа с Linux-контейнерами. Docker изначально разрабатывали для работы в Linux-среде, поэтому большинство контейнеров в Docker Hub — это образы, ориентированные на Linux. Использование WSL 2 предоставляет Docker Desktop полноценную Linux-среду на Windows.

Повышенная производительность. WSL 2 значительно ускоряет выполнение контейнеров, что особенно заметно в сравнении с WSL 1 или Hyper-V, о котором мы расскажем дальше. Это преимущество обеспечивает полноценное Linux-ядро, которое позволяет Docker работать гораздо быстрее и с меньшими накладными расходами.
Работа с файловой системой Linux. В WSL 2 можно монтировать файловую систему Linux, что позволяет работать с кодом и данными в нативной Linux-среде. Это особенно важно при разработке приложений, которые будут запускаться в Linux-контейнерах и требуют специфической настройки среды — например, прав доступа или структуры каталогов.

Когда нужен Hyper-V

Рассмотрим ключевые сценарии, в которых предпочтительнее использовать Hyper-V. 

Если система не поддерживает WSL 2

Некоторые сборки системы не позволяют включать необходимые компонентов для работы WSL 2 В частности, это касается старых версий Windows, а также устройств, которые не поддерживают Windows 10 Pro или 11 Pro, — WSL 2 для них недоступна, так как требует включенной виртуализации на уровне системы. В таких случаях можно использовать Hyper-V для виртуализации контейнеров и запуска Docker Desktop.

Для работы с Windows-контейнерами

Docker Desktop поддерживает как Linux-, так и Windows-контейнеры. Однако последние требуют прямого взаимодействия с ядром Windows, а WSL 2 предоставляет только Linux-среду. Hyper-V позволяет запускать Windows-контейнеры благодаря виртуализации Windows-системы.

Для изоляции и обеспечения безопасности

Hyper-V создает полноценные виртуальные машины, обеспечивая строгую изоляцию контейнеров друг от друга и от хост-системы. Это может быть важно в корпоративной среде или при работе с чувствительными данными.

Разница между WSL 2 и Hyper-V

Если вам нужны Linux-контейнеры и высокая производительность — выбирайте WSL 2. Если же требуется строгая изоляция или работа с Windows-контейнерами, Hyper-V будет предпочтительнее. Подробнее о разнице по ключевым критериям — в таблице:

Критерий WSL 2 Hyper-V
Производительность Высокая (нативное Linux-ядро) Низкая (работа через полноценную ВМ)
Изоляция Относительно низкая Высокая (контейнеры изолированы)
Типы контейнеров Только Linux-контейнеры Linux- и Windows-контейнеры

Системные требования Docker Desktop

При использовании WSL 2 в качестве бэкенда

  • WSL версии 1.1.3.0 или новее.
  • Windows 11 64-bit Home / Pro / Enterprise / Education, версия 22H2 или новее.
  • Windows 10 64-bit Home / Pro / Enterprise / Education, версия 22H2  (сборка 19045) или новее.
  • Включенная функция WSL 2 в Windows. Подробная инструкция есть в документации Microsoft;
  • 4 ГБ ОЗУ.
  • Включенная аппаратная виртуализация в BIOS на вашей локальной машине.

При использовании Hyper-V в качестве бэкенда

  • Windows 11 64-разрядная Enterprise / Pro / Education, версия 22H2 или новее.
  • Windows 10 64-разрядная Enterprise / Pro / Education, версия 22H2 (сборка 19045) или новее.
  • Включенная функция Hyper-V. Подробнее об установке — в документации Microsoft;
  • 4 ГБ ОЗУ.
  • Включенная аппаратная виртуализация в BIOS на вашей локальной машине.

Установка WSL 2

1. Откройте PowerShell от имени администратора и введите команду wsl —install. Она выполняет следующие действия:

  • включает дополнительные компоненты WSL и платформы виртуальных машин;
  • скачивает и устанавливает последнюю версию ядра Linux;
  • задает WSL 2 в качестве среды по умолчанию;
  • скачивает и устанавливает дистрибутив Ubuntu Linux.
Скриншот PowerShell. Установка дистрибутива.

Ввод команды в PowerShell.

2. После успешной установки всех компонентов перезапустите компьютер.

Скриншот PowerShell. Установка компонентов.

Успешная установка компонентов.

Первичная настройка

1. Откройте установленный дистрибутив с помощью меню Пуск — найдите установленный дистрибутив (Ubuntu).

2. При первом запуске системы нужно создать имя пользователя и пароль для дистрибутива Linux.

Создание имени пользователи и пароля в консоли.

3. Первичная настройка завершена, можно приступать к использованию WSL 2.

Альтернативный вариант — запустить WSL через PowerShell. Для этого введите команду wsl и система предложит произвести первичную настройку.

Скриншот Powershell. Запуск WSL-2.

Запуск WSL через Powershell.

Установка Hyper-V

Для установки компонентов Hyper-V откройте PowerShell от имени администратора и выполните команду:

    Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V -All

Она установит все компоненты для работы Hyper-V, после чего нужно будет перезапустить компьютер.

Установка компонентов в PowerShell.

Ввод команды в PowerShell.

Проверить корректность установки Hyper-V можно с помощью команды:

    Get-WindowsOptionalFeature -Online -FeatureName *hyper*|ft
Проверка установленных компонентов в PowerShell.

Проверка установленных компонентов.

Установка Docker с бэкендом WSL 2

  1. Скачайте дистрибутив Docker Desktop с официального сайта и запустите установщик. Галочки оставьте на всех пунктах.
Окно конфигурации в установщике.

  1. После установки перезайдите в учетную запись и откройте ярлык Docker Desktop
  2. Если все прошло успешно, вы увидите интерфейс инструмента:
Скриншот интерфейса Docker Desktop. 

Установка Docker с бэкендом Hyper-V

1. Скачайте дистрибутив Docker Desktop с официального сайта и запустите установщик. В инсталляционном окне уберите галочку Use WSL 2 instead of Hyper-V.

Окно конфигурации в установщике.

2. После установки перезайдите в учетную запись и откройте ярлык Docker Desktop

3. Если установка выполнена корректно, программа запустится без ошибок и вы увидите интерфейс:

Скриншот интерфейса Docker Desktop. 

Запуск контейнера

Рассмотрим запуск первого контейнера на примере самого популярного образа — hello-world. 

Поиск и скачивание образа

Поскольку вы только установили Docker Desktop, в системе нет образов контейнеров, которые можно запустить. Исправим это.

  1. Перейдите в раздел Images и нажмите кнопку Search images to run.
Скриншот раздела Images в Docker Desktop.

  1. Введите hello-world. В текущем окне на выбор есть две кнопки: Pull и Run. Если планируете для начала просто скачать образ, то выбирайте Pull. Если скачать и сразу запустить — Run.
Поиск образов контейнеров в Docker Desktop.

  1. Оставляем стандартные настройки для запуска.
Окно установки образа.

Проверка работы контейнера

Чтобы посмотреть запущенные контейнеры, перейдите во вкладку Containers и выберите созданный на прошлом этапе. В нашем примере для него было автоматически сгенерировано имя determined_jennings. Открыв контейнер, вы увидите сообщение, если настройка установка прошла успешно.

Просмотр созданного контейнера в Docker Desktop.

Как настроить запуск Docker при старте Windows

Для автозапуска Docker Desktop при авторизации на компьютере достаточно поставить галочку в настройках: Settings → General → Start Docker Desktop when you sign in to your computer.

Скриншот раздела «Настройки» в Windows.

После этого Docker Desktop будет запускаться автоматически при включении устройства.

Запуск Docker в облаке

Docker Desktop — удобный инструмент для локальной работы, но в ряде случаев может потребоваться облачная инфраструктура:

  • если мощности вашего ПК не хватает для работы с контейнерами;
  • если нужна среда для тестирования без нагрузки на локальную машину;
  • если вы работаете с ML/AI и нужны видеокарты для обучения моделей.

1. В панели управления в верхнем меню перейдем в раздел Продукты → Облачные серверы.

Выбор раздела «Облачные серверы» в панели управления Selectel.

2. Нажмем кнопку Создать сервер

Создание облачного сервера в панели управления Selectel.

3. Выберем имя, регион и сегмент пула. Важно учесть, что от сегмента зависят доступные конфигурации и стоимость. После создания сервера менять сегмент пула нельзя. 

Настройка имени, региона и пула в панели управления Selectel.

4. В качестве источника выберите готовый образ, приложение, свой образ, сетевой диск или снапшот. В нашем случае — приложение Containers Ready с настроенной Ubuntu 22.04. Оно содержит:

  • Docker версии 27.0.3;
  • плагины для запуска Docker Compose версии 2.11.1;
  • Portainer версии 2.20.3 — графический интерфейс для мониторинга и управления Docker-контейнерами, образами и сетью Docker.
Выбор источника для сервера в панели управления.

5. Конфигурацию для примера возьмем базовую — 2 vCPU и 2 ГБ RAM, а в поле Диски выберем SSD Быстрый на 20 ГБ. Важно: это минимальные требования. Рекомендуем выбирать параметры серверы, исходя из ваших задач. 

Помимо прочего, на этапе создания сервера или позже вы можете добавить GPU. При этом объем ОЗУ, который выделяется серверу, может быть меньше указанного в конфигурации — ядро ОС резервирует ее часть. Выделенный объем на сервере можно посмотреть с помощью команды sudo dmesg | grep Memory

Конфигурирование дисков, RAM и vCPU в панели управления.

6. Для работы Containers Ready сервер должен быть доступен из интернета. Для этого создадим приватную подсеть и подключим публичный IP-адрес. В поле Сеть выберем Приватная подсеть и добавим новый публичный адрес. Подробнее о настройке подсети можно узнать в документации.

Настройка сети для облачного сервера в панели управления.

6. Добавьте SSH-ключ в поле Доступ. Подробнее о его генерации можно узнать в отдельной инструкции.

Добавление SSH-ключа в панели управления.

7. Ознакомьтесь с ценой и нажмите кнопку Создать сервер

Раздел со стоимостью облачного сервера и его создание.

Сервер готов к использованию! Подробности о создании сервера с Сontainers Ready вы можете найти в документации. Если вам нужно запускать контейнеры с ML-моделями на мощных видеокартах, развернуть облачные серверы с GPU можно за несколько минут. Они помогут ускорить обучение нейросетей без закупки дорогого оборудования.

Читайте другие тексты о Docker

Docker has revolutionized the way developers interact with application containers. It simplifies the process of deploying and managing applications by using lightweight containers, which encapsulate everything needed for a software to run. If you are on Windows 11 and want to harness the power of Docker for your projects, follow this comprehensive guide on how to install and set up Docker on your machine.

Prerequisites

Before you start installing Docker on Windows 11, ensure that your system meets the following requirements:

  1. Windows Version: You need either Windows 11 Pro, Enterprise, or Education, as Docker Desktop requires WSL 2 (Windows Subsystem for Linux) to run.

  2. Virtualization: Ensure that Virtualization is enabled in your Computer’s BIOS/UEFI settings. Virtualization is essential for Docker to operate efficiently.

  3. Hardware: A 64-bit processor with Second Level Address Translation (SLAT) capabilities is required.

  4. Memory: At least 4 GB of RAM is recommended, although more is preferable for handling multiple or resource-intensive containers.

  5. Disk Space: Sufficient disk space to accommodate Docker images and containers.

Once you’ve confirmed these prerequisites, you can proceed with the installation.

Step 1: Enable WSL 2

The first step in setting up Docker on Windows 11 is to enable WSL 2. Here’s how to do it:

  1. Open PowerShell as Administrator: Right-click the Start button and select «Windows Terminal (Admin)» or search for PowerShell, right-click it and select «Run as Administrator».

  2. Install WSL: Type the following command and press Enter. This command will enable the WSL feature and install the latest Ubuntu distribution.

    wsl --install

    If you want to install a specific distribution, replace wsl --install with wsl --set-default-version 2.

  3. Restart Your Computer: After the installation is complete, it’s important to restart your system to apply the changes.

  4. Set WSL 2 as Default Version: Once your computer restarts, open PowerShell again and run:

    wsl --set-default-version 2

    This command makes sure that any new Linux installations will be using WSL 2.

  5. Check Your WSL Version: To confirm the installation and check which version is running, execute:

    wsl --list --verbose

    You should see listed distros with their WSL versions.

Step 2: Download Docker Desktop

With WSL 2 properly set up, the next step is to download Docker Desktop:

  1. Visit the Docker Website: Go to the Docker Desktop for Windows page.

  2. Download the Installer: Click on the «Download Docker Desktop for Windows» button.

  3. Locate the Installer: Once the download is complete, navigate to your Downloads folder and double-click on the Docker Desktop Installer executable (typically named Docker Desktop Installer.exe).

Step 3: Install Docker Desktop

Now that you have the installer, it’s time to install Docker Desktop. Here is how to go about it:

  1. Run the Installer: Double-click on the installer file and follow the on-screen instructions.

  2. Enable WSL 2 Feature: During the installation process, you may be prompted to enable the WSL 2 feature. Make sure it is checked.

  3. Add Windows Containers: If prompted, you can also choose to enable Windows containers alongside Linux containers.

  4. Complete Installation: Once you’ve made your selections, click on the Install button. When the installation completes, you may need to log out and log back into your Windows account.

  5. Launch Docker Desktop: After logging back in, search for Docker Desktop in the Start Menu and launch it.

  6. Accept the License Agreement: The first time you open Docker Desktop, you’ll be required to read and accept the license agreement.

  7. Sign-in Option: You will also have the option to sign in with a Docker Hub account. If you don’t have one, you can create it later.

Step 4: Configure Docker Desktop

Once you launch Docker Desktop, there are a few configurations you should pay attention to:

  1. Settings Access: Click on the Docker icon in the system tray (the area near the clock) and select «Settings».

  2. General Settings: Here, you can select options such as starting Docker Desktop when you log in.

  3. Resources Allocation: Under the «Resources» section, adjust CPU, Memory, and Disk image size according to your workload.

    • CPU: Allocate enough cores for your containers.
    • Memory: Depending on how resource-intensive your containers are, consider allocating more RAM.
    • Swap, Disk image size: These can usually remain at the default unless you’re working on large-scale projects.
  4. Enable Kubernetes (optional): If you’re interested in Kubernetes for managing your containers, there’s an option to enable it in the settings.

  5. Apply & Restart: After making any changes, ensure you click “Apply & Restart” to update the configuration.

Step 5: Verify Docker Installation

After Docker Desktop is installed and configured, it’s crucial to verify that Docker is functioning correctly:

  1. Open Command Prompt: Press Windows + R, type cmd, and hit Enter.

  2. Run Docker Command: Type the following command:

    docker --version

    This command should return the version of Docker that you have installed.

  3. Test Docker Installation: To further verify that Docker is operational, run the classic «Hello World» container by entering:

    docker run hello-world

    If Docker is installed correctly, you should see a message indicating that your installation appears to be working.

Step 6: Running Your First Docker Container

Now that Docker is up and running, you may want to run your first container. Here’s how to do it:

  1. Open a Terminal: You can use either Command Prompt, PowerShell, or the integrated terminal in Docker Desktop.

  2. Pull a Docker Image: Start by pulling a simple image from Docker Hub. For this example, let’s pull the official Nginx image:

    docker pull nginx
  3. Run the Container: Once the image is downloaded, run the container using:

    docker run -d -p 80:80 nginx

    This command runs Nginx in detached mode and maps port 80 of your host to port 80 of the container.

  4. Verify: Open your web browser and navigate to http://localhost. You should see the Nginx welcome page, confirming that your container is running successfully.

Step 7: Managing Docker Containers

After running your container, you might want to manage it. Here are some common commands:

  1. List Running Containers: To see currently running containers, use:

    docker ps
  2. Stop a Container: To stop a container, use the following command, replacing “ with the actual ID or name of your container:

    docker stop 
  3. Remove a Container: To remove a container after it has stopped, run:

    docker rm 
  4. View Container Logs: To see logs from a running container, use:

    docker logs 
  5. Access a Container Shell: If you want to access a running container’s shell, you can execute:

    docker exec -it  /bin/bash

Step 8: Docker Images Management

Images serve as the blueprints for your containers. Here’s how to manage them:

  1. List Installed Images: To view all downloaded images on your system, run:

    docker images
  2. Remove Unused Images: If you need to free up space, you can remove images that you no longer need with:

    docker rmi 
  3. Build Your Own Image: To create your own Docker image from a Dockerfile, navigate to the directory containing your Dockerfile and run:

    docker build -t  .

Best Practices and Tips

  1. Keep Docker Updated: Regularly check for updates in Docker Desktop to ensure you have the latest features and security improvements.

  2. Use Docker Compose: For applications requiring multiple containers, consider using Docker Compose. It simplifies the container orchestration process.

  3. Docker Documentation: Familiarize yourself with the Docker Documentation for advanced usage patterns and troubleshooting.

  4. Explore Docker Hub: Browse Docker Hub for pre-built images for use in your projects.

  5. Monitor Resource Usage: Keep an eye on how Docker containers affect your machine’s resources, especially in resource-limited environments.

  6. Data Persistence: Understand that containers are ephemeral. Use Docker volumes to manage persistent data effectively.

Conclusion

Installing Docker on Windows 11 is a straightforward process that opens up a wealth of possibilities for developers and system administrators. By following the steps laid out in this guide, you should have a fully functional Docker environment ready for creating, deploying, and managing applications in containers. As you become more familiar with Docker, you’ll discover its immense capabilities, allowing you to streamline development workflows, improve collaboration, and produce more robust applications with ease.

Whether you’re building small projects or large-scale applications, Docker provides a versatile platform for innovation and efficiency. Happy Dockering!

Installing Docker on Windows 11 is a straightforward process that allows you to efficiently manage and deploy applications within containers. To get started, you’ll need to ensure your system meets the necessary requirements and download the Docker Desktop installer from the official website. Once the installer is running, follow the prompts to complete the setup. After installation, launch Docker Desktop, which allows you to start creating, managing, and running containers in no time. This guide will walk you through each step, ensuring you have Docker up and running smoothly on your Windows 11 machine.

Let’s dive into the steps to install Docker on your Windows 11 system. This guide will help you get Docker Desktop installed and running so you can start working with containers right away.

Step 1: Check System Requirements

Ensure your PC meets the system requirements for Docker Desktop.

Before diving into installation, it’s crucial to verify your computer can handle Docker. It requires Windows 11, WSL 2 backend, and virtualization enabled in your BIOS settings. Without these, Docker won’t operate correctly.

Step 2: Download Docker Desktop

Visit the official Docker website and download Docker Desktop for Windows.

Head over to docker.com and find the Docker Desktop download link. It’s free, and the latest version will ensure you get all the recent updates and features for your container management.

Step 3: Run the Installer

Open the downloaded file and start the Docker Desktop installer.

Double-click the installation file you just downloaded. Follow the on-screen instructions, which typically involve accepting terms and choosing installation options. It’s a breeze, honestly!

Step 4: Complete the Installation

Follow the prompts to finalize the installation process.

Once you’ve set your preferences, the installer will handle the rest. It may take a few minutes, so don’t stress. Grab a coffee, and let it do its thing. Once done, you’re almost ready to go.

Step 5: Launch Docker Desktop

Open Docker Desktop and ensure it is running properly.

Find Docker Desktop in your Start Menu or desktop. Launch it, and let it initialize. If everything’s set up correctly, you should see the Docker Dashboard, where you can start building containers.

After you’ve installed Docker on Windows 11, you’ll be equipped to start building and managing containers. Docker Desktop provides an intuitive interface that simplifies containerization, making it easier to develop, test, and deploy applications across different environments. You’re ready to explore Docker’s vast capabilities!

Tips for Installing Docker on Windows 11

  • Make sure your Windows 11 is up-to-date to avoid any compatibility issues during installation.
  • Consider enabling Hyper-V if you plan to work with Linux containers.
  • Regularly check for Docker Desktop updates to access new features and security patches.
  • Familiarize yourself with Docker commands to make the most out of the CLI utilities.
  • Join Docker communities or forums for additional support and networking with other Docker users.

Frequently Asked Questions

What are the benefits of using Docker on Windows 11?

Docker allows for consistent environments across development, testing, and production, making it easier to deploy applications without compatibility issues.

Can I use Docker on Windows 11 without WSL 2?

No, Docker Desktop on Windows 11 requires WSL 2 to be enabled and installed for better Linux container support.

Is Docker Desktop free to use on Windows 11?

Yes, Docker Desktop is free for personal and educational use. For professional use, check the licensing terms on Docker’s official site.

How do I update Docker Desktop?

To update Docker Desktop, open the application, go to the settings, and check for updates. Docker will notify you if an update is available.

Can Docker impact my system performance?

Docker can consume significant system resources, especially if running multiple containers. Ensure you have adequate RAM and CPU for optimal performance.

Summary

  1. Check system requirements.
  2. Download Docker Desktop.
  3. Run the installer.
  4. Complete the installation.
  5. Launch Docker Desktop.

Conclusion

Docker has revolutionized the way we handle software development and deployment. Installing Docker on Windows 11 is your first step towards mastering this powerful tool. Once installed, the possibilities are as vast as the ocean—you can manage vast networks of containers with relative ease.

Docker provides a consistent environment across all systems, which means fewer headaches and more time for creativity and coding. It’s like having a reliable toolkit that works no matter where you go.

As you get familiar with Docker, you’ll discover how it can streamline your workflow, enhance productivity, and make application deployment as simple as a click of a button.

For those eager to delve deeper, I recommend checking out Docker’s official tutorials and online community forums. They offer a wealth of knowledge that’s both practical and inspiring.

Now that you know how to install Docker on Windows 11, get out there and start building something amazing.

Matthew Burleigh has been writing tech tutorials since 2008. His writing has appeared on dozens of different websites and been read over 50 million times.

After receiving his Bachelor’s and Master’s degrees in Computer Science he spent several years working in IT management for small businesses. However, he now works full time writing content online and creating websites.

His main writing topics include iPhones, Microsoft Office, Google Apps, Android, and Photoshop, but he has also written about many other tech topics as well.

Read his full bio here.

In this tutorial, we will learn how to install Docker on Windows 10 and 11. We will also learn how to start containers and switch between Linux containers and Windows containers.

By the end of this tutorial, you’ll have Docker installed and be ready to start running containerized applications on your Windows computer.

Note that this guide is for Windows 10 and Windows 11. If you want to install Docker on Windows Server, there is a separate tutorial (click the link below).

How to Install Docker on Windows Server 2022

Before We Begin

Before setting up Docker on Windows 11, there are a few things to consider.

  • Docker Desktop is the official way to run Docker on Windows 11.
  • It leverages WSL 2, a Microsoft technology that lets you run Linux environments directly on Windows.
  • WSL 2 relies on a lightweight Hyper-V virtual machine, which can conflict with third-party hypervisors like VirtualBox or VMware Workstation.
  • So, if you rely on these tools for development or testing, installing Docker Desktop might cause issues.
  • An alternative solution is to run Docker on a Linux virtual machine within VirtualBox or VMware Workstation instead of installing Docker Desktop.

System Requirements

To install Docker Desktop, virtualization needs to be enabled. You can click the link below to learn how to check and enable virtualization on your computer.

How to Enable Virtualization on Windows 10 and 11

Docker Installation Guide (Full Walkthrough)

To install Docker Desktop on your computer, complete the following steps:

  1. Check if WSL 2 has been enabled.
  2. Download the Docker installer for Windows.
  3. Run the installer.

Check If WSL 2 Has Been Enabled

Our first step is to check if WSL 2 is enabled. To do that, run the following command in CMD or PowerShell:

wsl --status

If WSL 2 is installed you will see and output like following:

wsl 2 status

If you don’t see any output that means WSL 2 is not installed. In that case you can install WSL 2 by running the wsl --install command.

wsl --install

Before running the command, make sure to open the Command Prompt or PowerShell console as an administrator.

You will need to restart your computer during the process. Once your computer has rebooted, it will install the Ubuntu distribution. This is part of the WSL 2 installation and is unrelated to Docker.

You can read the full WSL 2 installation guide at the bellow link.

How to Install WSL 2 on Windows

Download the Docker Installer for Windows

Ok, the next step is to download the docker desktop installer for Windows 11. To do that click on this link and then download the 86_64 installer at the top of the page.

Download Docker Desktop for Windows

Download Docker Desktop for Windows

Run the Installer

After the download is complete, run the installer. Continue with the recommended configuration and ensure the WSL 2 option is checked.

Install Docker on Windows 11

Once the installation is finished, you will be prompted to restart your computer. After that, it will start the Docker engine for the first time and present you with the Docker Desktop dashboard.

Docker Desktop on Windows 11

Docker Desktop on Windows 11

The Docker Desktop dashboard lets you manage containers visually. However, you also have the flexibility to use the Docker command through Command Prompt or PowerShell for more granular control.

How to Check Docker Version

Running Docker Containers on Windows

To make sure everything is working properly, we will start a test container using the hello-world image.

Open a command prompt and run the following command:

docker run hello-world

A successful setup will display the «Hello from Docker!» message, confirming that your Docker environment is ready to go.

Running Docker Containers on Windows

To learn more about the docker run command and how to create containers, click the link below.

How to start Docker containers using the Docker Run command

Linux Containers vs. Windows Containers

So here’s the thing: Docker on Windows allows you to run two types of containers—Linux containers and Windows containers.

Most containers are based on Linux, but if you need to run a Windows operating system, like Windows Server, you’ll need to use Windows container mode.

By default, Docker Desktop runs in Linux container mode. You can verify this by running the docker version command, which will show «Linux» as the server architecture.

Linux Containers vs. Windows Containers

To switch to Windows mode, right-click the Docker icon in the system tray and select «Switch to Windows containers…».

Switch to Windows containers

Switch to Windows containers

When you first switch to Windows containers, Docker Desktop will check if the Windows containers feature is enabled on your system. If not, it will prompt you to enable it before proceeding.

Enable Windows containers feature

Copy the provided command and run it in a PowerShell console to enable the containers feature.

Enable-WindowsOptionalFeature -Online -FeatureName $("Microsoft-Hyper-V", "Containers") -All

After enabling Windows containers, you’ll need to restart your computer for the changes to take effect. Once restarted, launch Docker Desktop from the desktop icon or Start menu shortcut. Wait for the Docker engine to fully initialize, then open a command prompt and run the docker version command.

docker version

This time, the server architecture should be Windows if you have switched to Windows containers mode.

Windows containers mode

To test Windows mode working properly, start a hello world container by running the following command:

docker run hello-world

A successful setup will display the «Hello from Docker!» message in your terminal, confirming that Windows container mode is functioning correctly.

Switching to Linux containers

While in Windows container mode, you cannot run applications built for Linux. To switch back to Linux containers and run Linux-based applications, right-click the Docker icon in the system tray and select «Switch to Linux containers…».

Switching to Linux containers

What Next?

Alright, that brings us to the end of this tutorial on setting up Docker Desktop on Windows 11! Now that you have Docker up and running, head over to our next tutorial to learn how to create containers using the docker run command.

Docker has revolutionized the way developers and IT professionals build, deploy, and manage applications. By using containerization, Docker allows for portable, lightweight environments that can be easily shared and managed. If you’re using Windows 11 and want to harness the power of Docker, this detailed guide will walk you through the installation process step by step.

Understanding Docker and Its Architecture

Before diving into the installation process, it’s essential to understand what Docker is and its underlying architecture. Docker is a platform that enables developers to automate the deployment of applications in lightweight, portable containers. These containers package an application and its dependencies, ensuring that it runs consistently across different computing environments.

The core components of Docker include:

  1. Docker Engine: The runtime that handles the creation and management of Docker containers.
  2. Docker Hub: A cloud-based registry for sharing Docker images, making it easier to find and distribute applications.
  3. Docker Compose: A tool for defining and managing multi-container Docker applications through a YAML file.

Prerequisites for Installing Docker on Windows 11

Before starting the installation process for Docker on Windows 11, ensure that your system meets the following prerequisites:

  1. Windows 11: Docker Desktop requires Windows 11 versions 21H2 or later.
  2. Hardware Requirements:
    • 64-bit processor with Second Level Address Translation (SLAT).
    • 4GB of RAM (8GB recommended).
    • BIOS-level hardware virtualization support must be enabled in the BIOS settings.
  3. Windows Subsystem for Linux 2 (WSL 2): Docker Desktop uses WSL 2 for Windows-based development. Make sure that WSL 2 is enabled on your system.
  4. Administrative Privileges: You’ll need admin access to your Windows account to install Docker.

Step-by-Step Installation Process

  1. Enable WSL (Windows Subsystem for Linux) and Virtual Machine Platform

    • To enable WSL, open PowerShell as an administrator and run the following command:

      wsl --install
    • This command will install WSL along with the Ubuntu distribution by default. If you want to install a different Linux distribution, you can do so from the Microsoft Store later.

    • After enabling WSL, you also need to enable the Virtual Machine Platform feature. Run:

      dism.exe /Online /Enable-Feature /FeatureName:VirtualMachinePlatform /All /LimitAccess /Source:wsi
    • Reboot your computer to apply the changes.

  2. Update to WSL 2 Backend

    • You might need to set WSL to use version 2 as the default version if it hasn’t been done automatically. You can do it by executing:
      wsl --set-default-version 2
  3. Download Docker Desktop

    • Visit the Docker Desktop Download page and click the download button to get the latest version of Docker Desktop for Windows.
  4. Install Docker Desktop

    • Locate the downloaded installer (usually found in your Downloads folder) and double-click on it to initiate the installation.
    • Follow the prompts in the Docker Desktop Setup Wizard. Make sure to select “WSL 2” as the backend during installation.
    • Once the installation is complete, ensure that the option to start Docker Desktop after installation is checked.
  5. Start Docker Desktop

    • Upon completion, the Docker Desktop application will start automatically. You can also find Docker Desktop in your Start Menu; just type «Docker» to locate it.
    • When Docker starts for the first time, it might take a few moments to initialize. You will see a Docker icon in your taskbar, which indicates its running status.
  6. Login to Docker Hub

    • If you have a Docker Hub account, you can log in directly through Docker Desktop. If you don’t have an account, you can create one on the Docker Hub website.
    • Logging in helps in pulling and managing public images directly from Docker Hub.

Configuration and Settings

Once Docker Desktop is up and running, you may want to tweak some settings according to your development requirements.

  1. Accessing Settings

    • Right-click on the Docker icon in the system tray and click on «Settings.»
  2. General Settings

    • Under the “General” tab, you can configure whether to start Docker Desktop when you log in and to send Docker usage statistics to Docker.
  3. Resources Configuration

    • Navigate to the “Resources” section to allocate CPU, memory, and swap space for Docker containers. By default, Docker allocates a set amount of each resource. Adjust these based on your development needs.
  4. WSL Integration

    • Under the “WSL Integration” section, you can control which WSL distributions can be used with Docker. Enable integration for any installed distributions that you wish to use with Docker.
  5. Network Settings

    • You can also customize network settings and configure DNS options if necessary.
  6. Experimental Features

    • Docker Desktop sometimes provides experimental features. If you want to be part of Docker’s testing environment, enable this feature under the “Experimental Features” tab.

Verifying Docker Installation

To ensure that Docker has been installed correctly, follow these steps:

  1. Open Windows Command Prompt or PowerShell:

    • Open the Start menu, type “cmd” or “PowerShell,” and hit Enter.
  2. Run the Docker Version Command:

    • Type the following command:
      docker --version
    • This command will display the installed Docker version, verifying that Docker is correctly installed on your system.
  3. Run a Test Container:

    • To further ensure everything is functioning well, run a simple test container by executing:
      docker run hello-world
    • If everything goes smoothly, this command will download the hello-world image and run it, displaying a simple message indicating that Docker is running correctly.

Using Docker

Now that Docker is installed, you can begin creating and managing containers. Here are some basic commands:

  1. Pulling an Image:

    docker pull 
  2. Listing Images:

    docker images
  3. Running a Container:

    docker run -it 
  4. Listing Running Containers:

    docker ps
  5. Stopping a Container:

    docker stop 
  6. Removing a Container:

    docker rm 

Troubleshooting Docker Installation

In case you encounter issues during installation or execution, here are some common troubleshooting steps:

  1. Check Virtualization Settings:

    • Ensure that virtualization is enabled in your BIOS. This is crucial for Docker to function properly on Windows.
  2. Update WSL:

    • Sometimes existing WSL installations need updates. You can update WSL by running:
      wsl --update
  3. Firewall and Antivirus:

    • Occasionally, firewalls or antivirus programs may block Docker. Check if any such software has restricted Docker’s network access.
  4. Consult the Logs:

    • You can access Docker logs by right-clicking the Docker icon in the system tray and selecting “Troubleshoot.” This option can provide insights into what might be going wrong.
  5. Reinstall Docker:

    • If all else fails, uninstall Docker using the Windows Settings, reboot your computer, and then attempt the installation again.

Conclusion

Installing Docker on Windows 11 can significantly enhance your development workflow by enabling efficient containerization of applications. By following this comprehensive guide, you should now have Docker Desktop up and running on your Windows 11 machine, allowing you to leverage the full power of Docker and container technology.

As you become more familiar with Docker, consider diving deeper into advanced features like Docker Compose for multi-container applications and utilizing Docker Swarm or Kubernetes for orchestration in a production environment.

In conclusion, the world of Docker is vast, and with your installation complete, you’re just taking your first steps into a powerful tool that can help innovate your development and deployment processes. Happy Dockering!

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Уязвимости windows server 2016
  • Chicony dc 6120 драйвер windows 10
  • Запросите разрешение от trustedinstaller на изменение этого файла windows 10
  • Тема метро 2033 для windows 7
  • Daemon tools windows 7 32bit