Работа с докером в windows

Search code, repositories, users, issues, pull requests…

Provide feedback

Saved searches

Use saved searches to filter your results more quickly

Sign up

Эта статья даст вам полное представление о 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 посмотреть запущенные контейнеры, запустить или остановить контейнеры

imageДанная публикация является разбором особенностей контейнерной виртуализации Docker под системой Windows.

Она не претендует на роль исчерпывающей и по мере необходимости будет обновляться и дополняться.

За практическим руководством с нуля советую обратиться к этой публикации.

Содержание

  • Предварительные настройки
  • Выбор между Docker Toolbox on Windows или Docker for Windows
  • Windows контейнеры и Linux контейнеры
  • Особенности монтирования папок
  • Монтирование с хост-машины или volume
  • Особенности разметки диска GPT и MBR
  • Docker Toobox to Windows
  • Docker Swarm
  • Проблемы с кодировкой
  • Полезные ссылки
  • Заключение

Предварительные настройки

Контейнерная виртуализация или виртуализация на уровне операционной системы Docker нативно работает только на дистрибутивах Linux и FreeBSD (экспериментально).
На Windows вам понадобится гостевая Linux система либо специальная минималистичная виртуальная машина с ядром Linux от разработчиков Docker, которая и ставится из коробки.
Само собой разумеется, что вы включили виртуализацию у себя в BIOS/UEFI
Пункт настройки может называться по-разному: VT-x, VT-d, Intel VT, AMD-V, Virtualization Technology.

Еще одним минимальным системным требованием будет разрядность системы x64 и версия не ниже Windows 7 Pro.

Выбор между Docker Toolbox on Windows или Docker for Windows

Появление Docker Toolbox on Windows и Docker Toolbox on Mac было большим событием.

Сборка включается в себя сам docker, утилиту docker-compose, утилиту для работы с виртуальной машиной docker-machine и клиент Kitematic.

Используется виртуальная машина (по умолчанию на VirtualBox) с минималистичным Linux окружением.

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

Выбор между версиями не сложный:
— Если у вас Windows 10 x64 Pro, Enterprise или Education то включаем службу Hyper-V и ставим Docker for Windows.

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

— Если же у вас другая версия Windows(7 Pro, 8, 8.1, 10 Home) то ставим VirtualBox и Docker Toolbox on Windows.

Несмотря на то, что Docker Toolbox разработчиками признан устаревшим работа с ним слабо отличается от Docker for Windows.

Вместе с установкой Docker Toolbox будет создана виртуальная машина.
В самом VirtualBox можно будет добавить оперативной памяти и ядер процессора на ваше усмотрение.

Windows контейнеры и Linux контейнеры

Docker for Windows предоставляет возможность переключать контейнеризацию между Linux и Windows версией.

В режиме Windows контейнеризации вы можете запускать только Windows приложения.
Замечу, что на май 2018 года в официальном Docker Hub существует всего 13 образов для Windows.

После включения Windows контейнеризации не забудьте добавить внешнюю сеть.

В конфигурационном файле docker-compose.yml это выглядит так:

networks:
  default:
    external:
      name: nat

Особенности монтирования папок

На примонтированных volume-ах не кидаются события файловой системы, поэтому inotify-tools не работает.
Спасибо пользователю eee

Если вы разрабатываете свой проект и пользуетесь docker-compose вне домашней папки то вам нужно будет проделать некоторые манипуляции.

Используя Docker for Windows для монтирования нового диска у вашего локального пользователя обязательно должен стоять пароль, который будет использоваться для доступа к shared папки.

Особенность заключается в том, что монтируемые внутрь контейнера диск будет монтироваться как от удаленной машины //10.0.75.1/DISK_DRIVE по протоколу SMB.

Для Docker Toolbox диски монтируются в самом VirtualBox на вкладке «Общие папки»
Пример для диска «D»:

Права доступа к монтируемым файлам и папкам

Как бы вам не хотелось, но для всех примонтированных из хост-машины файлов и папок будут стоять права 755 (rwx r-x r-x) и поменять их вы не сможете.

Остро встает вопрос при монтировании внутрь файла закрытого SSH ключа, права на который должны быть только у владельца(например 600).

В данном случае либо генерируют ключ при создании образа, либо прокидывают сокет ssh-agent с хост-машины.

Монтирование с хост-машины или volume

Монтирование внутрь контейнера происходит с использованием сети и протокола SMB, следовательно, внутри контейнера диск «D:\» будет примонтирован из источника //10.0.75.1/D
Использование volume внутри контейнера отображается как монтирование локального диска /dev/sda1, что влияет на скорость работы.

Простым тестом копирование файла на обычном HDD скорость работы получилась следующая:

Такая разница в скорости скорее всего связана с тем, что в volume данные сбрасываются на диск постепенно, задействуя кеш в ОЗУ.

Особенности разметки диска GPT и MBR

Данный пункт не является истинной так как опровергающей или подтверждающей информации в интернете найти не смог.

Если на хост-машине таблица разделов MBR, то контейнер с MySQL/MariaDB может упасть с ошибкой:

InnoDB: File ./ib_logfile101: ‘aio write’ returned OS error 122. Cannot continue operation

По умолчанию в базе данных включеён параметр innodb_use_native_aio, отвечающий за асинхронный ввод/вывод и его надо будет выключить.

Данная проблема также встречается на некоторых версиях MacOS.

Docker Toobox to Windows

Главное правило: начинать работу с запуска ярлыка на рабочем столе «Docker Quickstart Terminal», это решает 80% проблем.

— Бывает возникают проблемы с отсутствия переменных окружения, решается командой:

eval $(docker-machine env default)

— Если все же возникают проблемы из разряда «docker: error during connect», необходимо выполнить:

docker-machine env --shell cmd default 
@FOR /f "tokens=*" %i IN ('docker-machine env --shell cmd default') DO @%i

Название Docker Machine по умолчанию default.

Docker Swarm

Ни в Docker for Mac, ни в Docker for Windows — нет возможности использовать запущенные демоны в качестве клиентов кластера (swarm members).
Спасибо пользователю stychos

Проблемы с кодировкой

Используя Docker Toolbox(на Docker for Windows не удалось воспроизвести) нашлась проблема с тем, что русские комментарии в docker-compose.yml файле приводили к ошибке:

Traceback (most recent call last):
  File "docker-compose", line 6, in <module>
  File "compose\cli\main.py", line 71, in main
  File "compose\cli\main.py", line 124, in perform_command
  File "compose\cli\command.py", line 41, in project_from_options
  File "compose\cli\command.py", line 109, in get_project
  File "compose\config\config.py", line 283, in find
  File "compose\config\config.py", line 283, in <listcomp>
  File "compose\config\config.py", line 183, in from_filename
  File "compose\config\config.py", line 1434, in load_yaml
  File "site-packages\yaml\__init__.py", line 94, in safe_load
  File "site-packages\yaml\__init__.py", line 70, in load
  File "site-packages\yaml\loader.py", line 24, in __init__
  File "site-packages\yaml\reader.py", line 85, in __init__
  File "site-packages\yaml\reader.py", line 124, in determine_encoding
  File "site-packages\yaml\reader.py", line 178, in update_raw
  File "c:\projects\compose\venv\lib\encodings\cp1251.py", line 23, in decode
UnicodeDecodeError: 'charmap' codec can't decode byte 0x98 in position 1702: character maps to <undefined>
[4176] Failed to execute script docker-compose

Полезные ссылки

Docker Toolbox on Windows
Docker for Windows
Практическое руководство по Docker

Заключение

Особенности работы с Docker контейнеризацией на системе Windows не отличается от работы на Linux за исключение разобранных выше.

В статье я умышленно не упомянул заметно низкую скорость работы контейнеров и overhead используя систему Windows как само собой разумеющееся.

Буду рад услышать ваши отзывы. Не стесняйтесь предлагать улучшения или указывать на мои ошибки.

Только зарегистрированные пользователи могут участвовать в опросе. Войдите, пожалуйста.

Какой версией Docker вы пользуетесь?


32.47%
Docker Toolbox on Windows
88


67.53%
Docker for Windows
183

Проголосовал 271 пользователь.

Воздержался 191 пользователь.

If you’re looking for simple and painless software deployment, Docker is the right tool for you. It is the best containerization platform and in this blog on Docker for Windows we’ll specifically focus on how Docker works on Windows.

To get in-depth knowledge on Docker, you can enroll for live DevOps Certification Training by Edureka with 24/7 support and lifetime access.

I’ll be covering the following topics in this blog:

  1. Why use Docker For Windows?
  2. Docker for Windows prerequisites 
  3. Components installed with Docker 
  4. What is Docker?
  5. Docker Terminologies
  6. Hands-On

Why use Docker for Windows?

Why use Docker for Windows - Docker for Windows - Edureka

Why use Docker for Windows – Docker for Windows

  • Avoids the work on my machine but doesn’t work on production problem: This problem occurs due to the inconsistent environment throughout the software development workflow. With Docker you can run an application within a container which contains all the dependencies of the application and the container can be run throughout the software development cycle. This practice provides a consistent environment throughout the software development life cycle
  • Improves productivity: By installing Docker on windows we’re running Docker natively. If you’ve been following Docker for a while, you know that Docker containers originally supported only Linux operating systems. But thanks to the recent release, Docker can now natively run on windows, which means that Linux support is not needed, instead the  Docker container will run on the windows kernel itself
  • Supports native networking: Not only the Docker container, the entire Docker tool set is now compatible with windows. This includes the Docker CLI (client), Docker compose, data volumes and all the other building blocks for Dockerizied infrastructure are now compatible with windows. But how is this advantageous? Since all the Docker components are locally compatible with windows, they can now run with minimal computational overhead.

    You can get a better understanding with this Online Docker Training Course.

Docker For Windows Prerequisites

Docker for Windows - Prerequisites - Edureka

Docker for Windows – Prerequisites

The following requirements need to be met before installing Docker on windows:

  1. Check if you’re using Windows 10, either pro edition or enterprise edition, 64-bit system. Docker will not run on any other windows version. So if you’re running on an older windows version, you can install the Docker toolbox instead. 
  2. Docker for windows requires a Type-1 hypervisor and in the case of windows, it’s called the Hyper-V. Hyper-V is basically a lightweight virtualization solution build on top of the hypervisor framework. So you don’t need a virtual box, you just have to enable the hypervisor.
  3. And also you need to enable the virtualization in BIOS. Now when you install Docker for windows, by default of this is enabled. But in case you’re facing any issue during installation, please check if your Hyper-V and virtualization is enabled.

Components Installed With Docker

Components installed with Docker - Docker for Windows - Edureka

Components installed with Docker – Docker for Windows

  1. Docker Engine: When we say Docker, we actually mean Docker engine. The Docker engine contains the Docker daemon, REST API for interacting with the Docker daemon and a command line interface client that communicates with the daemon. Docker daemon accepts Docker commands such as Docker run, Docker build, etc, from the Docker client.
  2. Docker Compose: Docker compose is used to run multiple Docker containers at once by using a single command, which is docker-compose up.
  3. Docker Machine: Docker machine is used to install Docker engine. It is basically what you install on your local system. The Docker machine has it’s own CLI client known as the Docker machine and a Docker engine client called Docker.
  4. Kitematic: Kitematic is an open source project built to simplify the use of Docker on Windows. It helps to automate the installation of Docker and it provides a very interactive user interface for running Docker containers.

If you want to learn more about Docker for Windows, check out this video by our DevOps experts.

Docker For Windows | Setting Up Docker On Windows | Docker Tutorial For Beginners | Edureka

This Edureka video on Docker For Windows we’ll discuss Docker which is one of the best containerization platforms out there.

What Is Docker?

Docker is a containerization platform that runs applications within containers called Docker containers. Docker containers are light weighted when compared to virtual machines. When you install a Virtual machine on your system, it uses the guest operating system on top of your host operating system.  This obviously takes up a lot of resources like disk space, RAM, etc. On the other hand, Docker containers make use of the host operating system itself.

What is Docker - Docker for Windows - Edureka

What is Docker – Docker for Windows

In the above image, you can see that, there’s a host operating system on top of which the Docker engine is mounted. The Docker engine runs container #1 and container #2. Both of these containers have different applications and each application has its own libraries and packages installed within the container.

I hope you have a good idea about what Docker is if you still have doubts check out this blog to learn more!

Let’s discuss some Docker terminologies now:

  • Docker Images

Docker images are read-only templates to build Docker images. Docker images are created from a file called Dockerfile. Within the Dockerfile, you define all the dependencies and packages that are needed by your application.

  • Docker Containers

Every time you run a Docker image, it runs as a Docker container. Therefore, a Docker container is the run time instance of a Docker image.

  • Docker’s Registry

Docker’s registry, known as DockerHub is used to store Docker images. These images can be pulled from the remote server and can be run locally. DockerHub allows you to have Public/Private repositories.

  • Docker Swarm

Docker swarm is a technique to create and maintain a cluster of Docker engines. A cluster of Docker engines comprises of multiple Docker engines connected to each other, forming a network. This network of Docker engines is called a Docker swarm. A Docker manager initiates the whole swarm and the other Docker nodes have services running on them. The main goal of the Docker manager is to make sure that the applications or services are running effectively on these Docker nodes.

  • Docker Compose

Docker compose is used to run multiple containers at once. Let’s say that you have 3 applications in 3 different containers and you want to execute them at once. This is where Docker compose comes in, you can run multiple applications in different containers at once, with a single command, which is docker-compose up.

Hands-On

We’ll begin our demo by installing Docker for windows. But before we do that, check if you’ve met the prerequisites.

One more thing to note is since Docker for Windows requires Microsoft’s Hyper-V and once it’s enabled, VirtualBox will no longer be able to run virtual machines. So you can’t run Docker for Windows and a VirtualBox on the same system, side by side.

Install Docker On Windows:

  1. Download Docker for Windows installer from the official website
  2. Double-click on the installer to run it
  3. Go through the Install Wizard, accept the license and proceed with the install
  4. After installation, open the Docker for Windows app and wait till the whale icon on the status bar becomes stable
  5. Open up any terminal like Windows PowerShell and start running Docker

Installation - Docker for Windows - EdurekaInstallation – Docker for Windows

Enough of theory, let’s get our hands dirty and create a simple Python web application by using Docker Compose. This application uses the Flask framework and maintains a hit counter on Redis.

Flask is a web development framework, written in Python and Redis is an in-memory storage component, used as a database. You don’t have to install Python or Redis, we’re simply going to use Docker images for Python and Redis.

In this demo we’re going to use Docker compose to run two services, namely:

  1. Web service
  2. Redis service.

What does the application do? It maintains a hit counter every time you access a web page. So each time you access the website the hit counter gets incremented. It’s simple logic, just increment the value of the hit counter when the web page is accessed.

For this demo, you’ll need to create four files:

  1. Python file
  2. Requirements.txt
  3. Dockerfile
  4. Docker compose file

Below is the Python file (webapp.py) that creates an application by using the Flask framework and it maintains a hit counter on Redis. 

import time
import redis
from flask import Flask
app = Flask(__name__)
cache = redis.Redis(host='redis', port=6379)
def get_hit_count():
retries = 5
while True:
try:
return cache.incr('hits')
except redis.exceptions.ConnectionError as exc:
if retries == 0:
raise exc
retries -= 1
time.sleep(0.5)
@app.route('/')
def hello():
count = get_hit_count()
return 'Hello World! I have been seen {} times.
'.format(count)
if __name__ == "__main__":
app.run(host="0.0.0.0", debug=True)

The requirements.txt file has the name of the two dependencies, i.e. Flask and Redis that we’ll be installing in the Dockerfile.

flask
redis

The Dockerfile is used to create Docker images. Here, I’m installing python and the requirements mentioned in the requirements.txt file.

 
FROM python:3.4-alpine 
ADD . /code 
WORKDIR /code 
RUN pip install -r requirements.txt 
CMD ["python", "webapp.py"] 

The Docker compose file or the YAML file contains two services:

  1. Web service: Builds the Dockerfile in the current directory
  2. Redis service: Pulls a Redis image from DockerHub
version: '3'
services:
web:
build: .
ports:
- "5000:5000"
redis:
image: "redis:alpine"

You can now run these two services or containers by using the following command:

docker-compose up

To view the output you can use Kitematic. To open Kitematic, right click on the whale icon on the status bar.

Kitematic -Docker For Windows - Edureka

Kitematic – Docker for Windows

On the top left-hand corner, you can see the two services running. 

Kitematic -Docker For Windows - Edureka

Kitematic – Docker for Windows

This is what the output looks like. When you refresh the page, the hit count gets incremented.  

Output -Docker For Windows - EdurekaOutput – Docker for Windows

With this, we come to the end of this blog. I hope you have a better understanding of how Docker works on Windows. Stay tuned for more blogs on the most trending technologies.

If you found this Docker for Windows blog relevant, check out the DevOps training by Edureka, a trusted online learning company with a network of more than 450,000 satisfied learners spread across the globe. The Edureka DevOps Certification Training course helps learners gain expertise in various DevOps processes and tools such as Puppet, Jenkins, Docker, Nagios, Ansible, and GIT for automating multiple steps in SDLC.

Getting Started with Docker for Windows

Welcome to Docker for Windows!

Please read through these topics on how to get started. To give us your feedback on your experience with the app and report bugs or problems, log in to our Docker for Windows forum.

Already have Docker for Windows? If you already have Docker for Windows installed, and are ready to get started, skip over to the Getting Started with Docker tutorial.

Download Docker for Windows

If you have not already done so, please install Docker for Windows. You can download installers from the stable or beta channel. For more about stable and beta channels, see the FAQs.

Stable channel Beta channel
This installer is fully baked and tested, and comes with the latest GA version of Docker Engine.

This is the best channel to use if you want a reliable platform to work with.

These releases follow a version schedule with a longer lead time than the betas, synched with Docker Engine releases and hotfixes.

This installer offers cutting edge features and comes with the experimental version of Docker Engine, which is described in the Docker Experimental Features README on GitHub.

This is the best channel to use if you want to experiment with features we are working on as they become available, and can weather some instability and bugs. This channel is a continuation of the beta program, where you can provide feedback as the apps evolve. Releases are typically more frequent than for stable, often one or more per month.

Get Docker for Windows (stable)Download checksum: InstallDocker.msi SHA256 Get Docker for Windows (beta)Download checksum: InstallDocker.msi SHA256

Important Notes:

  • Docker for Windows requires 64bit Windows 10 Pro, Enterprise and Education
    (1511 November update, Build 10586 or later) and Microsoft Hyper-V. Please
    see What to know before you install
    for a full list of prerequisites.

  • You can switch between beta and stable versions, but you must have only one
    app installed at a time. Also, you will need to save images and export
    containers you want to keep before uninstalling the current version before
    installing another. For more about this, see the
    FAQs about beta and stable channels.

What to know before you install

  • README FIRST for Docker Toolbox and Docker Machine users: Docker for Windows requires Microsoft Hyper-V to run. After Hyper-V is enabled,
    VirtualBox will no longer work, but any VirtualBox VM images will remain.
    VirtualBox VMs created with docker-machine (including the default one
    typically created during Toolbox install) will no longer start. These VMs cannot
    be used side-by-side with Docker for Windows. However, you can still use
    docker-machine to manage remote VMs.
  • The current version of Docker for Windows runs on 64bit Windows 10 Pro, Enterprise and Education (1511 November update, Build 10586 or later). In the future we will support more versions of Windows 10.
  • Containers and images created with Docker for Windows are shared between all user accounts on machines where it is installed. This is because all
    Windows accounts will use the same VM to build and run containers. In the
    future, Docker for Windows will better isolate user content.
  • The Hyper-V package must be enabled for Docker for Windows to work. The Docker for Windows installer will enable it for you, if needed. (This requires a
    reboot). If your system does not satisfy these requirements, you can install
    Docker Toolbox, which uses Oracle Virtual Box instead of
    Hyper-V.
  • Virtualization must be enabled. Typically, virtualization is enabled by default. (Note that this is different from having Hyper-V enabled.) For more
    detail see Virtualization must be
    enabled in Troubleshooting.
  • What the Docker for Windows install includes: The installation provides Docker Engine, Docker CLI client, Docker Compose, and Docker Machine.

About Windows containers and Windows Server 2016

Looking for information on using Windows containers?

  • Getting Started with Windows Containers (Lab)
    provides a tutorial on how to set up and run Windows containers on Windows 10 or
    with Windows Server 2016. It shows you how to use a MusicStore application with
    Windows containers.
  • Setup — Windows Server 2016 (Lab) specifically describes environment setup.
  • Switch
    between Windows and Linux containers (Beta
    feature) describes the Linux / Windows containers toggle in Docker for Windows and points you to the tutorial mentioned above.
  • Docker Container Platform for Windows Server 2016 articles and blog posts on the Docker website

Step 1. Install Docker for Windows

  1. Double-click InstallDocker.msi to run the installer.

    If you haven’t already downloaded the installer (InstallDocker.msi), you can get it here. It typically downloads to your Downloads folder, or you can run it from the recent downloads bar at the bottom of your web browser.

  2. Follow the install wizard to accept the license, authorize the installer, and proceed with the install.

    You will be asked to authorize Docker.app with your system password during the install process. Privileged access is needed to install networking components, links to the Docker apps, and manage the Hyper-V VMs.

  3. Click Finish on the setup complete dialog to launch Docker.

    Install complete>

Step 2. Start Docker for Windows

When the installation finishes, Docker starts automatically.

The whale in the status bar indicates that Docker is running, and accessible from a terminal.

If you just installed the app, you also get a popup success message with suggested next steps, and a link to this documentation.

Install success

When initialization is complete, select About Docker from the notification area icon to verify that you have the latest version.

Congratulations! You are up and running with Docker for Windows.

Step 3. Check versions of Docker Engine, Compose, and Machine

Start your favorite shell (cmd.exe, PowerShell, or other) to check your versions of docker and docker-compose, and verify the installation.

  PS C:\Users\samstevens> docker --version
  Docker version 1.12.0, build 8eab29e, experimental

  PS C:\Users\samstevens> docker-compose --version
  docker-compose version 1.8.0, build d988a55

  PS C:\Users\samstevens> docker-machine --version
  docker-machine version 0.8.0, build b85aac1

Step 4. Explore the application and run examples

The next few steps take you through some examples. These are just suggestions for ways to experiment with Docker on your system, check version information, and make sure docker commands are working properly.

  1. Open a shell (cmd.exe, PowerShell, or other).

  2. Run some Docker commands, such as docker ps, docker version, and docker info.

    Here is the output of docker ps run in a powershell. (In this example, no containers are running yet.)

       PS C:\Users\samstevens> docker ps
       CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
    

    Here is an example of command output for docker version.

       PS C:\Users\Vicky> docker version
       Client:
       Version:      1.12.0
       API version:  1.24
       Go version:   go1.6.3
       Git commit:   8eab29e
       Built:        Thu Jul 28 21:04:48 2016
       OS/Arch:      windows/amd64
       Experimental: true
    
       Server:
       Version:      1.12.0
       API version:  1.24
       Go version:   go1.6.3
       Git commit:   8eab29e
       Built:        Thu Jul 28 21:04:48 2016
       OS/Arch:      linux/amd64
       Experimental: true
    

    Here is an example of command output for docker info.

       PS C:\Users\Vicky> docker info
       Containers: 0
       Running: 0
       Paused: 0
       Stopped: 0
       Images: 0
       Server Version: 1.12.0
       Storage Driver: aufs
       Root Dir: /var/lib/docker/aufs
       Backing Filesystem: extfs
       Dirs: 0
       Dirperm1 Supported: true
       Logging Driver: json-file
       Cgroup Driver: cgroupfs
       Plugins:
       Volume: local
       Network: host bridge null overlay
       Swarm: inactive
       Runtimes: runc
       Default Runtime: runc
       Security Options: seccomp
       Kernel Version: 4.4.16-moby
       Operating System: Alpine Linux v3.4
       OSType: linux
       Architecture: x86_64
       CPUs: 2
       Total Memory: 1.95 GiB
       Name: moby
       ID: BG6O:2VMH:OLNV:DDLF:SCSV:URRH:BW6M:INBW:OLAC:J7PX:XZVL:ADNB
       Docker Root Dir: /var/lib/docker
       Debug Mode (client): false
       Debug Mode (server): false
       Registry: https://index.docker.io/v1/
       Experimental: true
       Insecure Registries:
       127.0.0.0/8
    

    Note: The outputs above are examples. Your output for commands like docker version and docker info will vary depending on your product versions (e.g., as you install newer versions).

  3. Run docker run hello-world to test pulling an image from Docker Hub and starting a container.

      PS C:\Users\samstevens> docker run hello-world
    
      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.
      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.
    

  4. Try something more ambitious, and run an Ubuntu container in a Bash shell.

       $ docker run -it ubuntu bash
    
       PS C:\Users\samstevens> docker run -it ubuntu bash
       Unable to find image 'ubuntu:latest' locally
       latest: Pulling from library/ubuntu
       5a132a7e7af1: Pull complete
       fd2731e4c50c: Pull complete
       28a2f68d1120: Pull complete
       a3ed95caeb02: Pull complete
       Digest: sha256:4e85ebe01d056b43955250bbac22bdb8734271122e3c78d21e55ee235fc6802d
       Status: Downloaded newer image for ubuntu:latest
    

    Type exit to stop the container and close the Bash shell.

  5. For the pièce de résistance, start a Dockerized webserver with this command:

       docker run -d -p 80:80 --name webserver nginx
    

    This will download the nginx container image and start it. Here is the output of running this command in a powershell.

       PS C:\Users\samstevens> docker run -d -p 80:80 --name webserver nginx
       Unable to find image 'nginx:latest' locally
       latest: Pulling from library/nginx
    
       fdd5d7827f33: Pull complete
       a3ed95caeb02: Pull complete
       716f7a5f3082: Pull complete
       7b10f03a0309: Pull complete
       Digest: sha256:f6a001272d5d324c4c9f3f183e1b69e9e0ff12debeb7a092730d638c33e0de3e
       Status: Downloaded newer image for nginx:latest
       dfe13c68b3b86f01951af617df02be4897184cbf7a8b4d5caf1c3c5bd3fc267f
    

  6. Point your web browser at http://localhost to display the start page.

    (Since you specified the default HTTP port, it isn’t necessary to append :80 at the end of the URL.)

    Run nginx edge>

  7. Run docker ps while your webserver is running to see details on the container.

      PS C:\Users\samstevens> docker ps
      CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS
      NAMES
      dfe13c68b3b8        nginx               "nginx -g 'daemon off"   3 days ago          Up 45 seconds       0.0.0.0:80->80/tcp, 443/tc
      p   webserver
    

  8. Stop or remove containers and images.

    The nginx webserver will continue to run in the container on that port until you stop and/or remove the container. If you want to stop the webserver, type: docker stop webserver and start it again with docker start webserver.

    To stop and remove the running container with a single command, type: docker rm -f webserver. This will remove the container, but not the nginx image. You can list local images with docker images. You might want to keep some images around so that you don’t have to pull them again from Docker Hub. To remove an image you no longer need, use docker rmi <imageID>|<imageName>. For example, docker rmi nginx.

Want more example applications? — For more example walkthroughs that include setting up services and databases with Docker Compose, see Example Applications.

Docker Settings

When Docker is running, the Docker whale is displayed in the system tray. If it is hidden, click the up arrow in the tray to show it.

Showing hidden apps in the system tray

To get a popup menu with application options, right-click the whale:

Docker for Windows popup menu

The Settings dialogs provide options to allow Docker auto-start, automatically check for updates, share local drives with Docker containers, enable VPN compatibility, manage CPUs and memory Docker uses, restart Docker, or perform a factory reset.

Beta 26 and newer include an option to switch between Windows and Linux conatiners. See Switch between Windows and Linux containers (Beta feature). This is not yet available on stable builds.

Beta 26 popup with switch for Windows or Linux containers

General

Settings

  • Start Docker when you log in — Automatically start the Docker for Windows application upon Windows system login.

  • Check for updates when the application starts — Docker for Windows is set to automatically check for updates and notify you when an update is available. If an update is found, click OK to accept and install it (or cancel to keep the current version). Uncheck this option if you do not want notifications of version upgrades. You can still find out about updates manually by choosing Check for Updates from the menu.

  • Send usage statistics — You can set Docker for Windows to auto-send diagnostics, crash reports, and usage data. This information can help Docker improve the application and get more context for troubleshooting problems.

    Uncheck any of the options to opt out and prevent auto-send of data. Docker may prompt for more information in some cases, even with auto-send enabled. Also, you can enable or disable these auto-reporting settings with one click on the information popup when you first start Docker.

    Startup information

Shared Drives

Share your local drives (volumes) with Docker for Windows, so that they are available to your containers.

Shared Drives

You will be asked to provide your Windows system username and password (domain user) to apply shared drives. You can select an option to have Docker store the credentials so that you don’t have to re-enter them every time.

Permissions to access shared drives are tied to the credentials you provide here. If you run docker commands and tasks under a different username than the one used here to set up sharing, your containers will not have permissions to access the mounted volumes.

Tip: Shared drives are only required for volume mounting Linux containers, not Windows containers.

See also Verify domain user has permissions for shared drives in Troubleshooting.

Firewall rules for shared drives

Shared drives require port 445 to be open between the host machine and the virtual
machine that runs Linux containers.

Note: In Docker for Windows Beta 29 and higher,
Docker detects if port 445 is closed and shows the following message when you
try to add a shared drive: Port 445 blocked

To share the drive, allow connections between the Windows host machine and the
virtual machine in Windows Firewall or your third party firewall software. You
do not need to open port 445 on any other network. By default, allow connections
to 10.0.75.1 port 445 (the Windows host) from 10.0.75.2 (the virtual machine).

Advanced

CPU and Memory settings

  • CPUs — Change the number of processors assigned to the Linux VM.

  • Memory — Change the amount of memory the Docker for Windows Linux VM uses.

Please note, updating these settings requires a reconfiguration and reboot of the Linux VM. This will take a few seconds.

Network

You can configure Docker for Windows networking to work on a virtual private network (VPN).

  • Internal Virtual Switch — You can specify a network address translation (NAT) prefix and subnet mask to enable internet connectivity.

  • DNS Server — You can configure the DNS server to use dynamic or static IP addressing.

Network settings

Note: Some users reported problems connecting to Docker Hub on Docker for Windows stable version. This would manifest as an error when trying to run docker commands that pull images from Docker Hub that are not already downloaded, such as a first time run of docker run hello-world. If you encounter this, reset the DNS server to use the Google DNS fixed address: 8.8.8.8. For more information, see Networking issues in Troubleshooting.

Note that updating these settings requires a reconfiguration and reboot of the Linux VM.

Proxies

Docker for Windows lets you configure HTTP/HTTPS Proxy Settings and automatically propagate these to Docker and to your containers.
For example, if you set your proxy settings to http://proxy.example.com, Docker will use this proxy when pulling containers.

Proxies

When you start a container, you will see that your proxy settings propagate into the containers. For example:

$ docker run -it alpine env
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=b7edf988b2b5
TERM=xterm
HOME=/root
HTTP_PROXY=http://proxy.example.com:3128
http_proxy=http://proxy.example.com:3128
no_proxy=*.local, 169.254/16

You can see from the above output that the HTTP_PROXY, http_proxy and no_proxy environment variables are set.
When your proxy configuration changes, Docker restarts automatically to pick up the new settings.
If you have containers that you wish to keep running across restarts, you should consider using restart policies

Docker daemon

You can configure options on the Docker daemon in the given JSON configuration file, and determine how your containers will run.

For a full list of options on the Docker daemon, see daemon in the Docker Engine command line reference.

Docker Daemon

Note that updating these settings requires a reconfiguration and reboot of the Linux VM.

Switch between Windows and Linux containers (Beta feature)

Starting with Beta 26, you can select which daemon (Linux or Windows) the Docker CLI talks to. Select Switch to Windows containers to toggle to Windows containers. Select Switch to Linux containers.

Microsoft Developer Network has preliminary/draft information on Windows containers here.

This feature is not yet available on stable builds.

See also Shared Drives

Getting started with Windows containers (Beta feature)

If you are interested in working with Windows containers, here are some guides to help you get started.

  • Build and Run Your First Windows Server Container (Blog Post) gives a quick tour of how to build and run native Docker Windows containers on Windows 10 and Windows Server 2016 evaluation releases.

  • Getting Started with Windows Containers (Lab) shows you how to use the MusicStore application with Windows containers. The MusicStore is a standard .NET application and, forked here to use containers, is a good example of a multi-container application.

    Disclaimer: This lab is still in work, and is based off of the blog, but you can test and leverage the example walkthroughs now, if you want to start experimenting. Please checking back as the lab evolves.

Diagnose and Feedback

If you encounter problems for which you do not find solutions in this documentation, searching Docker for Windows issues on GitHub already filed by other users, or on the Docker for Windows forum, we can help you troubleshoot the log data.

Select Upload a diagnostic.

This uploads (sends) the logs to Docker.

Diagnose problems and Feedback

To create a new issue directly on GitHub, open Docker for Windows issues on GitHub in your web browser and follow the instructions in the README. Click New Issue on that page to get a “create new issue” template prepopulated with sections for the ID and summary of your diagnostics, system and version details, description of expected and actual behavior, and steps to reproduce the issue.

issue template

Reset

Reset

  • Restart Docker — Shuts down and restarts the Docker application.

  • Reset to Toolbox default machine content — Imports containers and images from the existing Docker Toolbox machine named default. (This option is enabled only if you have Toolbox installed.) The VirtualBox VM will not be removed.

  • Reset to factory defaults — Resets Docker to factory defaults. This is useful in cases where Docker stops working or becomes unresponsive.

Where to go next

  • Try out the Getting Started with Docker tutorial.

  • Dig in deeper with learn by example tutorials on building images, running containers, networking, managing data, and storing images on Docker Hub.

  • See Example Applications for example applications that include setting up services and databases in Docker Compose.

  • Interested in trying out the new swarm mode on Docker Engine v1.12?

    See Get started with swarm mode, a tutorial which includes specifics on how to leverage your Docker for Windows installation to run single and multi-node swarms.

    Also, try out the Swarm examples in docker labs. Run the bash script and follow the accompanying Docker Swarm Tutorial. The script uses Docker Machine to create a multi-node swarm, then walks you through various Swarm tasks and commands.

  • For a summary of Docker command line interface (CLI) commands, see Docker CLI Reference Guide.

  • Check out the blog posts on Docker for Mac and Docker for Windows public betas, and earlier posts on the initial private beta.

  • Please give feedback on your experience with the app and report bugs and problems by logging into our Docker for Windows forum.

  • Работа с дисками при установке windows 10
  • Работа с hyper v на windows 10
  • Работа с img образами в windows
  • Работа с дисками из командной строки windows 10
  • Работа с github на windows