Как запустить докер на windows 10

Docker - the open-source application container engine - docker/windows.md at master · microsoft/docker

Note: This release of Docker deprecates the Boot2Docker command line in
favor of Docker Machine. Use the Docker Toolbox to install Docker Machine as
well as the other Docker tools.

You install Docker using Docker Toolbox. Docker Toolbox includes the following Docker tools:

  • Docker Machine for running the docker-machine binary
  • Docker Engine for running the docker binary
  • Kitematic, the Docker GUI
  • a shell preconfigured for a Docker command-line environment
  • Oracle VM VirtualBox

Because the Docker daemon uses Linux-specific kernel features, you can’t run
Docker natively in Windows. Instead, you must use docker-machine to create and attach to a Docker VM on your machine. This VM hosts Docker for you on your Windows system.

The virtual machine runs a lightweight Linux distribution made specifically to
run the Docker daemon. The VirtualBox VM runs completely from RAM, is a small
~24MB download, and boots in approximately 5s.

Requirements

To run Docker, your machine must have a 64-bit operating system running Windows 7 or higher. Additionally, you must make sure that virtualization is enabled on your machine.
To verify your machine meets these requirements, do the following:

  1. Right click the Windows Start Menu and choose System.

    Which version

    If you are using an unsupported version of Windows, you should consider
    upgrading your operating system in order to try out Docker.

  2. Make sure your CPU supports virtualization technology
    and virtualization support is enabled in BIOS and recognized by Windows.

    For Windows 8, 8.1 or 10

    Choose Start > Task Manager. On Windows 10, click more details. Navigate to the Performance tab.
    Under CPU you should see the following:

    Release page

    If virtualization is not enabled on your system, follow the manufacturer’s instructions for enabling it.

    For Windows 7

    Run the Microsoft® Hardware-Assisted Virtualization Detection
    Tool and follow the on-screen instructions.

  3. Verify your Windows OS is 64-bit (x64)

    How you do this verification depends on your Windows version. For details, see the Windows
    article How to determine whether a computer is running a 32-bit version or 64-bit version
    of the Windows operating system.

Note: If you have Docker hosts running and you don’t wish to do a Docker Toolbox
installation, you can install the docker.exe using the unofficial Windows package
manager Chocolatey. For information on how to do this, see Docker package on
Chocolatey.

Learn the key concepts before installing

In a Docker installation on Linux, your machine is both the localhost and the
Docker host. In networking, localhost means your computer. The Docker host is
the machine on which the containers run.

On a typical Linux installation, the Docker client, the Docker daemon, and any
containers run directly on your localhost. This means you can address ports on a
Docker container using standard localhost addressing such as localhost:8000 or
0.0.0.0:8376.

Linux Architecture Diagram

In an Windows installation, the docker daemon is running inside a Linux virtual
machine. You use the Windows Docker client to talk to the Docker host VM. Your
Docker containers run inside this host.

Windows Architecture Diagram

In Windows, the Docker host address is the address of the Linux VM. When you
start the VM with docker-machine it is assigned an IP address. When you start
a container, the ports on a container map to ports on the VM. To see this in
practice, work through the exercises on this page.

Installation

If you have VirtualBox running, you must shut it down before running the
installer.

  1. Go to the Docker Toolbox page.

  2. Click the installer link to download.

  3. Install Docker Toolbox by double-clicking the installer.

    The installer launches the «Setup — Docker Toolbox» dialog.

    Install Docker Toolbox

  4. Press «Next» to install the toolbox.

    The installer presents you with options to customize the standard
    installation. By default, the standard Docker Toolbox installation:

    • installs executables for the Docker tools in C:Program FilesDocker Toolbox
    • install VirtualBox; or updates any existing installation
    • adds a Docker Inc. folder to your program shortcuts
    • updates your PATH environment variable
    • adds desktop icons for the Docker Quickstart Terminal and Kitematic

    This installation assumes the defaults are acceptable.

  5. Press «Next» until you reach the «Ready to Install» page.

    The system prompts you for your password.

    Install

  6. Press «Install» to continue with the installation.

    When it completes, the installer provides you with some information you can
    use to complete some common tasks.

    All finished

  7. Press «Finish» to exit.

Running a Docker Container

To run a Docker container, you:

  • Create a new (or start an existing) Docker virtual machine
  • Switch your environment to your new VM
  • Use the docker client to create, load, and manage containers

Once you create a machine, you can reuse it as often as you like. Like any
VirtualBox VM, it maintains its configuration between uses.

There are several ways to use the installed tools, from the Docker Quickstart Terminal or
from your shell.

Using the Docker Quickstart Terminal

  1. Find the Docker Quickstart Terminal icon on your Desktop and double-click to launch it.

    The application:

    • Opens a terminal window
    • Creates a default VM if it doesn’t exist, and starts the VM after
    • Points the terminal environment to this VM

    Once the launch completes, you can run docker commands.

  2. Verify your setup succeeded by running the hello-world container.

     $ docker run hello-world
     Unable to find image 'hello-world:latest' locally
     511136ea3c5a: Pull complete
     31cbccb51277: Pull complete
     e45a5af57b00: Pull complete
     hello-world:latest: The image you are pulling has been verified.
     Important: image verification is a tech preview feature and should not be
     relied on to provide security.
     Status: Downloaded newer image for hello-world:latest
     Hello from Docker.
     This message shows that your installation appears to be working correctly.
    
     To generate this message, Docker took the following steps:
     1. The Docker client contacted the Docker daemon.
     2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
        (Assuming it was not already locally available.)
     3. The Docker daemon created a new container from that image which runs the
        executable that produces the output you are currently reading.
     4. The Docker daemon streamed that output to the Docker client, which sent it
        to your terminal.
    
     To try something more ambitious, you can run an Ubuntu container with:
     $ docker run -it ubuntu bash
    
     For more examples and ideas, visit:
     http://docs.docker.com/userguide/
    

Using Docker from Windows Command Prompt (cmd.exe)

  1. Launch a Windows Command Prompt (cmd.exe).

    The docker-machine command requires ssh.exe in your PATH environment
    variable. This .exe is in the MsysGit bin folder.

  2. Add this to the %PATH% environment variable by running:

     set PATH=%PATH%;"c:Program Files (x86)Gitbin"
    
  3. Create a new Docker VM.

     docker-machine create --driver virtualbox my-default
     Creating VirtualBox VM...
     Creating SSH key...
     Starting VirtualBox VM...
     Starting VM...
     To see how to connect Docker to this machine, run: docker-machine env my-default
    

    The command also creates a machine configuration in the
    C:USERSUSERNAME.dockermachinemachines directory. You only need to run the create
    command once. Then, you can use docker-machine to start, stop, query, and
    otherwise manage the VM from the command line.

  4. List your available machines.

     C:Usersmary> docker-machine ls
     NAME                ACTIVE   DRIVER       STATE     URL                         SWARM
     my-default        *        virtualbox   Running   tcp://192.168.99.101:2376
    

    If you have previously installed the deprecated Boot2Docker application or
    run the Docker Quickstart Terminal, you may have a dev VM as well.

  5. Get the environment commands for your new VM.

     C:Usersmary> docker-machine env --shell cmd my-default
    
  6. Connect your shell to the my-default machine.

     C:Usersmary> eval "$(docker-machine env my-default)"
    
  7. Run the hello-world container to verify your setup.

     C:Usersmary> docker run hello-world
    

Using Docker from PowerShell

  1. Launch a Windows PowerShell window.

  2. Add ssh.exe to your PATH:

     PS C:Usersmary> $Env:Path = "${Env:Path};c:Program Files (x86)Gitbin"
    
  3. Create a new Docker VM.

     PS C:Usersmary> docker-machine create --driver virtualbox my-default
    
  4. List your available machines.

     C:Usersmary> docker-machine ls
     NAME                ACTIVE   DRIVER       STATE     URL                         SWARM
     my-default        *        virtualbox   Running   tcp://192.168.99.101:2376
    
  5. Get the environment commands for your new VM.

     C:Usersmary> docker-machine env --shell powershell my-default
    
  6. Connect your shell to the my-default machine.

     C:Usersmary> eval "$(docker-machine env my-default)"
    
  7. Run the hello-world container to verify your setup.

     C:Usersmary> docker run hello-world
    

Learn about your Toolbox installation

Toolbox installs the Docker Engine binary in the C:Program FilesDocker Toolbox directory. When you use the Docker Quickstart Terminal or create a
default VM manually, Docker Machine updates the
C:USERSUSERNAME.dockermachinemachinesdefault folder to your
system. This folder contains the configuration for the VM.

You can create multiple VMs on your system with Docker Machine. Therefore, you
may end up with multiple VM folders if you have created more than one VM. To
remove a VM, use the docker-machine rm <machine-name> command.

Migrate from Boot2Docker

If you were using Boot2Docker previously, you have a pre-existing Docker
boot2docker-vm VM on your local system. To allow Docker Machine to manage
this older VM, you can migrate it.

  1. Open a terminal or the Docker CLI on your system.

  2. Type the following command.

     $ docker-machine create -d virtualbox --virtualbox-import-boot2docker-vm boot2docker-vm docker-vm
    
  3. Use the docker-machine command to interact with the migrated VM.

The docker-machine subcommands are slightly different than the boot2docker
subcommands. The table below lists the equivalent docker-machine subcommand
and what it does:

boot2docker docker-machine docker-machine description
init create Creates a new docker host.
up start Starts a stopped machine.
ssh ssh Runs a command or interactive ssh session on the machine.
save Not applicable.
down stop Stops a running machine.
poweroff stop Stops a running machine.
reset restart Restarts a running machine.
config inspect Prints machine configuration details.
status ls Lists all machines and their status.
info inspect Displays a machine’s details.
ip ip Displays the machine’s ip address.
shellinit env Displays shell commands needed to configure your shell to interact with a machine
delete rm Removes a machine.
download Not applicable.
upgrade upgrade Upgrades a machine’s Docker client to the latest stable release.

Upgrade Docker Toolbox

To upgrade Docker Toolbox, download and re-run the Docker Toolbox
installer.

Container port redirection

If you are curious, the username for the Docker default VM is docker and the
password is tcuser. The latest version of docker-machine sets up a host only
network adaptor which provides access to the container’s ports.

If you run a container with a published port:

$ docker run --rm -i -t -p 80:80 nginx

Then you should be able to access that nginx server using the IP address
reported to you using:

Typically, the IP is 192.168.59.103, but it could get changed by VirtualBox’s
DHCP implementation.

Note: There is a known
issue that
may cause files shared with your nginx container to not update correctly as you
modify them on your host.

Login with PUTTY instead of using the CMD

Docker Machine generates and uses the public/private key pair in your
%USERPROFILE%.dockermachinemachines<name_of_your_machine> directory. To
log in you need to use the private key from this same directory. The private key
needs to be converted into the format PuTTY uses. You can do this with
puttygen:

  1. Open puttygen.exe and load («File»->»Load» menu) the private key from (you may need to change to the All Files (*.*) filter)

     %USERPROFILE%.dockermachinemachines<name_of_your_machine>id_rsa
    
  2. Click «Save Private Key».

  3. Use the saved file to login with PuTTY using docker@127.0.0.1:2022.

Uninstallation

You can uninstall Docker Toolbox using Window’s standard process for removing
programs. This process does not remove the docker-install.exe file. You must
delete that file yourself.

Learn more

You can continue with the Docker Engine User Guide. If you are
interested in using the Kitematic GUI, see the Kitematic user
guide.

Рассмотрим установку Docker Desktop for Windows — это Community-версия Docker для систем Microsoft Windows.

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

  • Windows 10 64-bit: Pro, Enterprise, Education (Build 16299 или выше).

Для успешного запуска Client Hyper-V в Windows 10 требуются следующие предварительные требования к оборудованию:

  • 64 bit процессор c поддержкой Second Level Address Translation (SLAT).
  • 4GB системной памяти.
  • Поддержка аппаратной виртуализации на уровне BIOS должна быть включена в настройках BIOS.

Подготовка

Включаем функции Hyper-V Containers Window. Для этого переходим в панель управления — установка и удаление программ — включение или отключение компонентов Windows. Активируем пункт Hyper-V, который включает Hyper-V Managment Tools, Hyper-V Platform.

Также это можно выполнить через powershell или dism (все команды необходимо выполнять с правами администратора).

Powershell:

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

DISM:

DISM /Online /Enable-Feature /All /FeatureName:Microsoft-Hyper-V

Установка

Скачиваем установщик Docker (Docker Desktop Installer) с Docker Hub.

Установка Docker Desktop включает Docker Engine, Docker CLI client, Docker Compose, Notary, Kubernetes и Credential Helper. Контейнеры и образы, созданные с помощью Docker Desktop, используются всеми учетными записями пользователей на компьютерах, на которых он установлен. Это связано с тем, что все учетные записи Windows используют одну и ту же виртуальную машину для создания и запуска контейнеров. При использовании Docker Desktop WSL 2 невозможно обмениваться контейнерами и образами между учетными записями пользователей.

Запускаем установщик Docker Desktop Installer.exe и ожидаем пока он скачает все необходимые компоненты.

После установки система потребует перезагрузки. Перезагружаемся и входим в систему.

После входа может возникнут запрос на установку дополнительного компонента WSL2. Переходим по ссылке и скачиваем необходимый пакет с официального сайта Microsoft.

После скачивания выполняем установку WSL2, после которой снова потребуется перезагрузка.

Настройка и запуск приложения

Входим в систему и ждем запуска всех служб Docker. Когда все службы будут запущены, мы увидим в трее классический значок Docker — это значит что служба установлена и запущена. Далее можно запустить приложение Docker desktop. Далее можно изменить настройки Docker при необходимости:

проверка докер

Рисунок 1 — Изменение параметров Docker desktop

Далее управление Docker выполняется через Powershell. Проверяем версию и выполняем тестовый запуск контейнера:

проверка докер

Рисунок 2 — Проверка версии Docker

После выполнения всех этих действий, Docker готов к использованию.

Нужна помощь? Настройки docker/docker swarm/docker compose мы осуществляем в рамках услуги DevOps-аутсорсинг.

Эта статья даст вам полное представление о Docker Desktop для пользователей Windows и MAC. Мы изучим установку Docker Desktop на компьютерах с Windows и Mac. После установки мы также попытаемся выполнить некоторые операции Docker.

Docker Desktop — это собственное настольное приложение, разработанное Docker для пользователей Windows и MAC. Это самый простой способ запуска, сборки, отладки и тестирования приложений Dockerized.

Docker Desktop предлагает важные и наиболее полезные функции, такие как быстрые циклы редактирования, уведомления об изменениях файлов, встроенная поддержка корпоративной сети и гибкость для работы с собственным выбором прокси и VPN.

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

Скорость, безопасность и выбор — все, что вам нужно для разработки и доставки контейнерных приложений, доступных на вашем рабочем столе, будет представлено вам.

Прежде чем перейти к процессу установки, давайте разберемся с его версиями.

Версии Docker

Docker в основном поставляется в двух версиях, в Community и ENterprise.

Community версия поставляется с бесплатным набором продуктов Docker. ENterprise корпоративная версия представляет собой сертифицированную контейнерную платформу, которая предоставляет коммерческим пользователям дополнительные функции, такие как безопасность образов, управление образами, оркестровка и управление средой выполнения контейнеров, но по разумной цене.

Мы начнем наше обучение с Community Edition. Контейнеры Docker, работающие в конкретной операционной системе, совместно используют ядро ​​ОС. Это означает, что мы не можем использовать ядро ​​Windows (хост) для запуска контейнеров Linux или наоборот. Чтобы проделать это, у нас есть Docker Desktop для Windows и MAC.

Выпуски Docker Desktop

Docker Desktop выпускается в двух вариантах.

  • Stable: как видно из названия, стабильный выпуск тщательно протестирован и может быть использован при разработке более надежных приложений. Его версии полностью синхронизированы с версиями Docker Engine.
  • Edge: эти версии состоят из всех новых и экспериментальных функций Docker Engine. Есть больше шансов ошибок, сбоев и проблем, которые могут возникнуть. Тем не менее, пользователи получат возможность ознакомиться с предстоящими функциями.

Docker на Windows

Есть два варианта Docker на Windows.

1. Использование Docker Toolbox

Docker Toolbox предоставляет набор легких инструментов.

  • Oracle virtual box
  • Docker Engine
  • Docker Machine
  • Docker compose
  • Kitematic GUI

Вышеуказанные инструменты устраняют необходимость развертывания отдельной виртуальной машины для запуска Docker. Просто установите исполняемый файл панели инструментов Docker непосредственно в Windows и начните разработку приложений. Требуется 64-битная ОС и Windows 7 или выше с включенным режимом виртуализации.

Но опять же, панель инструментов Docker — это оригинальная поддержка, предоставляемая в Windows для запуска Docker и его устаревшего решения для всех ОС Windows, которые не соответствуют требуемой конфигурации.

2. Использование Docker Desktop

Docker Desktop — это новейшая технология, используемая для Docker в Windows. Он заменяет виртуальную машину Oracle собственной технологией виртуализации, доступной в Windows, то есть Microsoft Hyper-V.

Он по-прежнему будет запускать Docker на Linux-машине, созданной под ним. Но на этот раз вместо виртуальной машины Oracle мы использовали нативный Microsoft Hyper-V.

Установка Docker на Windows

Вы можете скачать репозиторий Docker Desktop из Docker Hub.

Установка Docker на Windows

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

  • Windows 10 или Windows Server 2016 Professional или Enterprise Edition
  • Поддержка Hyper-V.

Чтобы запустить Hyper-V, оборудование должно соответствовать следующим требованиям:

  • 64-битный процессор
  • > = 4 ГБ ОЗУ
  • Поддержка виртуализации оборудования на уровне BIOS

Следовательно, программная и аппаратная зависимость заключается в запуске Docker Desktop на Windows.

Установка Docker на macOS

Вы можете скачать репозиторий Docker Desktop из Docker Hub.  

Установка Docker на macOS

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

  • MAC Hardware 2010 или новее с аппаратной поддержкой управления памятью и неограниченным режимом. Выполните команду kern.hv_support, чтобы проверить, поддерживает ли оборудование MAC инфраструктуру гипервизора.
  • MAC OS версии 10.13 или новее.
  • > = 4 ГБ ОЗУ
  • Virtual-Box до версии 4.3.30

Работа с образами

После установки проверьте версию установленного Docker Engine.

docker --version

Docker работает с доставкой и запуском контейнерных приложений. Вам либо нужно создать свое собственное контейнерное приложение, либо Docker поддерживает контейнерные образы в Docker Hub, и его можно легко загрузить с помощью простой команды docker run.

Здесь мы будем тянуть образ Redis.

docker pull redis

docker образ redis

С помощью простой команды run образы можно скачивать и загружать на GitHub или Docker Hub, и любой пользователь во всем мире может получить к нему доступ и начать работать с ним.

Docker Container запускает образ Docker. Следующим шагом является запуск контейнера.

docker run -p 6379 Redis

docker запуск redis

Будет создан зашифрованный идентификатор контейнера. Вы можете быстро проверить состояние работающего экземпляра в Docker, нажав на Dashboard option.

Docker Desktop

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

Docker Desktop

Возможности Docker Desktop

Существует множество преимуществ:

  • Поддерживает широкий спектр инструментов разработки.
  • Обеспечьте быстрый и оптимизированный способ создания и публикации контейнерного образа на любой облачной платформе.
  • Простота установки и настройки полной среды Docker
  • Повышение производительности благодаря встроенной виртуализации Hyper-V для Windows и HyperKit для MAC.
  • Возможность работать в Linux через WSL 2 на компьютерах с Windows.
  • Легкий доступ к работающим контейнерам в локальной сети.
  • Возможность поделиться любым приложением на облачной платформе, на разных языках и в разных средах.
  • Для обеспечения безопасности и актуальности выполняются автоматические обновления.
  • Включены последние версии Kubernetes.
  • Возможность переключения между Linux и Windows сервером на Windows.

Docker Desktop — это нативное приложение, разработанное на Windows и MAC OS для запуска, сборки и доставки контейнерных приложений или сервисов.

Однако

Docker Desktop предназначен не для производственной среды, а для рабочего стола и среды разработки.

Также рекомендуем прочитать:

  1. Docker для начинающих — технология контейнеров
  2. В чем разница между Docker и Kubernetes?
  3. Введение в Docker Hub и все, что вы должны знать о нем
  4. Как установить Docker на Ubuntu, Windows, Debian и CentOS?
  5. Kubernetes — Введение для начинающих
  6. Docker посмотреть запущенные контейнеры, запустить или остановить контейнеры

В этой заметке я расскажу как поставить Докер на Windows 10, но сначала я опишу установку Windows Subsystem for Linux. Работу с самим Докером я описывать не буду, сделаю это позже.

Установка WSL2 на Windows 10

Установка элементарная, главное проверьте чтобы ваш компьютер и Windows 10 отвечали минимальным требованиям.

UPD.

Для Windows 11 и Windows 10 (сборка 19041 и выше) для установки WSL достаточно одной команды (PowerShell с правами администратора):

wsl --install

Эта команда включит все необходимые компоненты и установит дистрибутив Linux (по умолчанию Ubuntu), вам нужно будет только перезагрузить компьютер.

Подробный процесс установки описан на сайте Microsoft https://docs.microsoft.com/ru-ru/windows/wsl/install-win10 там же указаны минимальные требования.

Если коротко, то установка WSL2 на Windows 10 сводится к следующим шагам:

1) Запускаем PowerShell с правами администратора и включаем компонент «Подсистема Windows для Linux», для этого вводим команду:

dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart

2) Далее  необходимо включить необязательный компонент «Платформа виртуальных машин», для этого в PowerShell с правами администратора выполняем команду:

dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart

Перезапускаем компьютер.

3) Скачиваем и устанавливаем пакет обновления ядра Linux https://wslstorestorage.blob.core.windows.net/wslblob/wsl_update_x64.msi

4) Выбираем WSL 2 в качестве версии по умолчанию, если этого не сделать новые дистрибутивы Linux будут установлены в WSL 1. Вновь запускаем PowerShell с правами администратора и добавляем команду:

wsl --set-default-version 2

Готово.

Далее нужно выбрать в магазине Microsoft Store нужный нам дистрибутив Linux и установить его, как обычное приложение из магазина. Я установил Ubuntu 18.04 (https://www.microsoft.com/store/apps/9N9TNGVNDL3Q)

После я запускаю установленную Убунту и задаю логин и пароль.

Установленная Убунту через WSL2

Все, Убунту можно закрыть.

Установка Docker на Windows 10

Теперь установим Docker Desktop WSL 2 backend, идем по ссылке https://hub.docker.com/editions/community/docker-ce-desktop-windows/ Скачиваем и устанавливаем Docker Desktop for Windows (stable).

Запускаем скачанный файл и производим обычную установку приложения Windows.

При установке убедитесь что установлена галочка на Enable WSL 2 Windows Features.

Установлена галочка на Enable WSL 2 Windows Features

После установки следуйте инструкциям и перелогиньтесь в Windows, Докер запуститься при следующем входе в Windows, иногда в первый раз может понадобится довольно длительное время.

Когда он запустится, рекомендую в окне приветствия нажать Start и пройти небольшое обучение.

Окно приветствия Docker для Windows 10

После обучающего урока у вас будет запущен ваш первый Docker контейнер.

Запущен ваш первый Docker контейнер.

И теперь по адресу http://localhost/tutorial/ вы можете увидеть инструкцию по дальнейшей работе.

Теперь вы можете заниматься разработкой в Windows 10 использую Docker.

Кстати, я не хочу чтобы Докер запускался каждый раз при включении компьютера, поэтому в настройках я убрал галочку Start Docker Desktop when you log in.

Start Docker Desktop when you log in


WSL

Docker

How to run Docker on Windows 10 Home edition

Recently I have been watching a tutorial where, in order to follow it, you need to have Docker running on your machine. So far, so good.

But it turns out that the latest versions of Docker require Windows 10 Pro, Enterprise, or Education. Which means that if you are like me and have just Windows 10 Home edition on your personal laptop, then you cannot use Docker…or maybe you still can.

Read on below to find out how. ?

Reasoning

First, let’s do a short summary of the situation. What do we want to achieve and what do we currently have?

We have Windows 10 OS Home edition on our machine. We would like to have Docker running on the same machine so that we are able to create docker images, run containers, and learn better and grow faster!

The last one is a bit out of the scope of this article, but we should start from somewhere, no? ?.

Actions

After defining what we want, let’s see how to achieve it. Here are the steps I followed. It worked for me, which make me want to share it with you. And maybe I can save someone a few days of going back and forth to StackOverflow! ?

After some reading, I found this article. It explains that it is possible to use Docker in Windows 10 Home by leveraging a Linux virtual machine and having Docker containers running on it. Let’s see how it works.

Step 1: Installations

First you need to install a software called Oracle VM VirtualBox. It gives you the ability to have multiple virtual machines installed on your physical one. This way we can have a virtual machine which will be running Linux where our Docker will live.

Then use Windows PowerShall and Chocolatey, your Windows package manager, to install a docker-machine by running the following:

choco install docker-machine

Open your favorite bash terminal app and run this:

docker-machine create --driver virtualbox default

This will create a docker virtual machine called ‘default’.

Step 2: Configurations

Next, we need to configure which ports are exposed when running Docker containers. You can do that by going to Oracle VM VirtualBox -> default virtual machine -> Settings -> Network -> Adapter 1 -> Port Forwarding.

VirtualBox Port Forwarding

This was the most critical detail that I forgot . We need to allow Docker to mount volumes located on your hard drive. By default, you can only mount from the C://Users/ directory.

To add a different path, simply go to the Oracle VM VirtualBox GUI. Select default VM and go to Settings > Shared Folders. If you don’t mind to use the default settings, do not forget to put your project under the ‘Users’ directory, e.g. C:Users{your project}.

In my case, I forgot about this and had to spend few days of head banging until I figured out why the heck was I getting a «Couldn’t find package.json» error when trying to run the containers, built through this tutorial.

Start the virtual machine by running the following command in your terminal app:

docker-machine start default

Step 3: Setting up Environment Variables

Next, we need to set up Docker environment variables:

docker-machine env default

This allows the Docker client and Docker Compose to communicate with the Docker Engine running in the Linux VM that we named «default».

You may also need to run:

@FOR /f "tokens=*" %i IN ('"C:ProgramDatachocolateylibdocker-machinebindocker-machine.exe" env') DO @%i

in order to get Docker working properly. Note: the specified path in the above command may vary depending on your setup.

If you are going to use things such as docker-compose up, you will need to install Docker Tools as well. You may do it by running the following commands in PowerShall:

choco install docker-cli
choco install docker-compose

These will install everything you need to start using Docker on your Windows 10 Home OS.

Conclusion

Now that we have all we need, we may spend our time on actual learning, either by following a docker-related tutorial or reading a book. No matter what you want to do next, you have all the tools you will need.

I personally will try to finish the previously mentioned tutorial and then, who knows, may be I will start using Docker for each project I do.

By the way, during the process of researching, I found a very promising book which is specifically about Docker. It’s called «Docker in Practice» by Ian Miell. If this interests you, you might want to take a look.

? Thanks for reading! ?

References

  • https://www.virtualbox.org/
  • https://www.sitepoint.com/docker-windows-10-home
  • https://www.youtube.com/watch?v=6Yfm5gHQjaQ&list=PLnTRniWXnjf8YC9qJFLSVCrXfS6cyj6x6&index=2
  • https://github.com/mihailgaberov/microservices
  • http://support.divio.com/en/articles/646695-how-to-use-a-directory-outside-c-users-with-docker-toolbox-docker-for-windows


Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Понравилась статья? Поделить с друзьями:
  • Как запустить дисциплес 2 на windows 10
  • Как запустить диспетчер устройств от имени администратора windows 10
  • Как запустить диспетчер устройств windows 10 через командную строку
  • Как запустить диспетчер устройств windows 10 с правами администратора
  • Как запустить диспетчер устройств windows 10 cmd