как пользоваться docker windows
Docker Desktop for Windows user manual
Estimated reading time: 18 minutes
Welcome to Docker Desktop! The Docker Desktop for Windows user manual provides information on how to configure and manage your Docker Desktop settings.
For information about Docker Desktop download, system requirements, and installation instructions, see Install Docker Desktop.
Settings
The Docker Desktop menu allows you to open the Docker Dashboard, run the Quick Start Guide, configure your Docker settings such as installation, updates, version channels, Docker Hub login, and more.
This section explains the configuration options accessible from the Settings dialog.
To open the Docker Desktop menu, right-click the Docker icon in the Notifications area (or System tray):
Select Settings to open the Settings dialog:
General
On the General tab, you can configure when to start Docker and specify other settings.
Start Docker when you log in: Select this option to automatically start Docker Desktop when you log into your Windows machine.
Expose daemon on tcp://localhost:2375 without TLS: Click this option to enable legacy clients to connect to the Docker daemon. You must use this option with caution as exposing the daemon without TLS can result in remote code execution attacks.
Use the WSL 2 based engine: WSL 2 provides better performance than the legacy Hyper-V backend. For more information, see Docker Desktop WSL 2 backend.
Send usage statistics: By default, Docker Desktop sends diagnostics, crash reports, and usage data. This information helps Docker improve and troubleshoot the application. Clear the check box to opt out. Docker may periodically prompt you for more information.
Show weekly tips: Displays useful advice and suggestions about using Docker.
Open Docker Desktop dashboard at startup: Automatically opens the dashboard when starting Docker Desktop.
Use Docker Compose V2: Select this option to enable the docker-compose command to use Docker Compose V2. For more information, see Docker Compose V2.
Resources
The Resources tab allows you to configure CPU, memory, disk, proxies, network, and other resources. Different settings are available for configuration depending on whether you are using Linux containers in WSL 2 mode, Linux containers in Hyper-V mode, or Windows containers.
Advanced
The Advanced tab is only available in Hyper-V mode, because in WSL 2 mode and Windows container mode these resources are managed by Windows. In WSL 2 mode, you can configure limits on the memory, CPU, and swap size allocated to the WSL 2 utility VM.
Use the Advanced tab to limit resources available to Docker.
CPUs: By default, Docker Desktop is set to use half the number of processors available on the host machine. To increase processing power, set this to a higher number; to decrease, lower the number.
Memory: By default, Docker Desktop is set to use 2 GB runtime memory, allocated from the total available memory on your machine. To increase the RAM, set this to a higher number. To decrease it, lower the number.
Swap: Configure swap file size as needed. The default is 1 GB.
Disk image size: Specify the size of the disk image.
Disk image location: Specify the location of the Linux volume where containers and images are stored.
You can also move the disk image to a different location. If you attempt to move a disk image to a location that already has one, you get a prompt asking if you want to use the existing image or replace it.
File sharing
The File sharing tab is only available in Hyper-V mode, because in WSL 2 mode and Windows container mode all files are automatically shared by Windows.
Use File sharing to allow local directories on Windows to be shared with Linux containers. This is especially useful for editing source code in an IDE on the host while running and testing the code in a container. Note that configuring file sharing is not necessary for Windows containers, only Linux containers. If a directory is not shared with a Linux container you may get file not found or cannot start service errors at runtime. See Volume mounting requires shared folders for Linux containers.
File share settings are:
Add a Directory: Click + and navigate to the directory you want to add.
Tips on shared folders, permissions, and volume mounts
Share only the directories that you need with the container. File sharing introduces overhead as any changes to the files on the host need to be notified to the Linux VM. Sharing too many files can lead to high CPU load and slow filesystem performance.
Shared folders are designed to allow application code to be edited on the host while being executed in containers. For non-code items such as cache directories or databases, the performance will be much better if they are stored in the Linux VM, using a data volume (named volume) or data container.
Docker Desktop sets permissions to read/write/execute for users, groups and others 0777 or a+rwx. This is not configurable. See Permissions errors on data directories for shared volumes.
Shared folders on demand
You can share a folder “on demand” the first time a particular folder is used by a container.
If you run a Docker command from a shell with a volume mount (as shown in the example below) or kick off a Compose file that includes volume mounts, you get a popup asking if you want to share the specified folder.
You can select to Share it, in which case it is added your Docker Desktop Shared Folders list and available to containers. Alternatively, you can opt not to share it by selecting Cancel.
Proxies
Your proxy settings, however, will not be propagated into the containers you start. If you wish to set the proxy settings for your containers, you need to define environment variables for them, just like you would do on Linux, for example:
For more information on setting environment variables for running containers, see Set environment variables.
Network
The Network tab is not available in Windows container mode because networking is managed by Windows.
You can configure Docker Desktop networking to work on a virtual private network (VPN). 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.
Updating these settings requires a reconfiguration and reboot of the Linux VM.
WSL Integration
In WSL 2 mode, you can configure which WSL 2 distributions will have the Docker WSL integration.
You can also select any additional distributions you would like to enable the WSL 2 integration on.
For more details on configuring Docker Desktop to use WSL 2, see Docker Desktop WSL 2 backend.
Docker Engine
The Docker Engine page allows you to configure the Docker daemon to determine how your containers run.
Type a JSON configuration file in the box to configure the daemon settings. For a full list of options, see the Docker Engine dockerd commandline reference.
Click Apply & Restart to save your settings and restart Docker Desktop.
Command Line
On the Command Line page, you can specify whether or not to enable experimental features.
You can toggle the experimental features on and off in Docker Desktop. If you toggle the experimental features off, Docker Desktop uses the current generally available release of Docker Engine.
Experimental features
Experimental features provide early access to future product functionality. These features are intended for testing and feedback only as they may change between releases without warning or can be removed entirely from a future release. Experimental features must not be used in production environments. Docker does not offer support for experimental features.
For a list of current experimental features in the Docker CLI, see Docker CLI Experimental features.
Kubernetes
The Kubernetes tab is not available in Windows container mode.
Docker Desktop includes a standalone Kubernetes server that runs on your Windows machine, so that you can test deploying your Docker workloads on Kubernetes. To enable Kubernetes support and install a standalone instance of Kubernetes running as a Docker container, select Enable Kubernetes.
For more information about using the Kubernetes integration with Docker Desktop, see Deploy on Kubernetes.
Software Updates
The Software Updates section notifies you of any updates available to Docker Desktop. When there’s a new update, you can choose to download the update right away, or click the Release Notes option to learn what’s included in the updated version.
Disable automatic check for updates
Starting with Docker Desktop 4.2.0, the option to turn off the automatic check for updates is available for users on all Docker subscriptions, including Docker Personal and Docker Pro. Update to Docker Desktop 4.2.0 to start using this feature.
Turn off the check for updates by clearing the Automatically Check for Updates check box. This disables notifications in the Docker menu and also the notification badge that appears on the Docker Dashboard. To check for updates manually, select the Check for updates option in the Docker menu.
To allow Docker Desktop to automatically download new updates in the background, select Always download updates. This downloads newer versions of Docker Desktop when an update becomes available. After downloading the update, click Apply and Restart to install the update. You can do this either through the Docker menu or in the Updates section in the Docker Dashboard.
Dashboard
The Docker Dashboard enables you to interact with containers and applications and manage the lifecycle of your applications directly from your machine. The Dashboard UI shows all running, stopped, and started containers with their state. It provides an intuitive interface to perform common actions to inspect and manage containers and existing Docker Compose applications. For more information, see Docker Dashboard.
Add TLS certificates
You can add trusted Certificate Authorities (CAs) (used to verify registry server certificates) and client certificates (used to authenticate to registries) to your Docker daemon.
Reset
The Restart Docker Desktop and Reset to factory defaults options are now available on the Troubleshoot menu. For information, see Logs and Troubleshooting.
Troubleshoot
Visit our Logs and Troubleshooting guide for more details.
Log on to our Docker Desktop for Windows forum to get help from the community, review current user topics, or join a discussion.
Log on to Docker Desktop for Windows issues on GitHub to report bugs or problems and review community reported issues.
For information about providing feedback on the documentation or update it yourself, see Contribute to documentation.
Switch between Windows and Linux containers
From the Docker Desktop menu, you can toggle which daemon (Linux or Windows) the Docker CLI talks to. Select Switch to Windows containers to use Windows containers, or select Switch to Linux containers to use Linux containers (the default).
For more information on Windows containers, refer to the following documentation:
Microsoft documentation on Windows containers.
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.
To understand how to connect to Windows containers from the local host, see I want to connect to a container from Windows
Settings dialog changes with Windows containers
When you switch to Windows containers, the Settings dialog only shows those tabs that are active and apply to your Windows containers:
If you set proxies or daemon configuration in Windows containers mode, these apply only on Windows containers. If you switch back to Linux containers, proxies and daemon configurations return to what you had set for Linux containers. Your Windows container settings are retained and become available again when you switch back.
Dashboard
The Docker Dashboard enables you to interact with containers and applications and manage the lifecycle of your applications directly from your machine. The Dashboard UI shows all running, stopped, and started containers with their state. It provides an intuitive interface to perform common actions to inspect and manage containers and Docker Compose applications. For more information, see Docker Desktop Dashboard.
Docker Hub
Select Sign in /Create Docker ID from the Docker Desktop menu to access your Docker Hub account. Once logged in, you can access your Docker Hub repositories directly from the Docker Desktop menu.
For more information, refer to the following Docker Hub topics:
Two-factor authentication
Docker Desktop enables you to sign into Docker Hub using two-factor authentication. Two-factor authentication provides an extra layer of security when accessing your Docker Hub account.
You must enable two-factor authentication in Docker Hub before signing into your Docker Hub account through Docker Desktop. For instructions, see Enable two-factor authentication for Docker Hub.
After you have enabled two-factor authentication:
Go to the Docker Desktop menu and then select Sign in / Create Docker ID.
Enter your Docker ID and password and click Sign in.
After you have successfully signed in, Docker Desktop prompts you to enter the authentication code. Enter the six-digit code from your phone and then click Verify.
After you have successfully authenticated, you can access your organizations and repositories directly from the Docker Desktop menu.
Pause/Resume
Starting with the Docker Desktop 4.2 release, you can pause your Docker Desktop session when you are not actively using it and save CPU resources on your machine. When you pause Docker Desktop, the Linux VM running Docker Engine is paused, the current state of all your containers are saved in memory, and all processes are frozen. This reduces the CPU usage and helps you retain a longer battery life on your laptop. You can resume Docker Desktop when you want by clicking the Resume option.
The Pause/Resume feature is currently not available in the Windows containers mode.
To pause Docker Desktop, right-click the Docker icon in the notifications area (or System tray) and then click Pause.
Docker Desktop now displays the paused status on the Docker menu and on all screens on the Docker Dashboard. You can still access the Preferences and the Troubleshoot menu from the Dashboard when you’ve paused Docker Desktop.
Select > Resume to resume Docker Desktop.
When Docker Desktop is paused, running any commands in the Docker CLI will automatically resume Docker Desktop.
Adding TLS certificates
You can add trusted Certificate Authorities (CAs) to your Docker daemon to verify registry server certificates, and client certificates, to authenticate to registries.
How do I add custom CA certificates?
Docker Desktop supports all trusted Certificate Authorities (CAs) (root or intermediate). Docker recognizes certs stored under Trust Root Certification Authorities or Intermediate Certification Authorities.
Docker Desktop creates a certificate bundle of all user-trusted CAs based on the Windows certificate store, and appends it to Moby trusted certificates. Therefore, if an enterprise SSL certificate is trusted by the user on the host, it is trusted by Docker Desktop.
To learn more about how to install a CA root certificate for the registry, see Verify repository client with certificates in the Docker Engine topics.
How do I add client certificates?
You can add your client certificates in
When the Docker Desktop application starts, it copies the
/.docker/certs.d folder on your Windows system to the /etc/docker/certs.d directory on Moby (the Docker Desktop virtual machine running on Hyper-V).
You need to restart Docker Desktop after making any changes to the keychain or to the
/.docker/certs.d directory in order for the changes to take effect.
The registry cannot be listed as an insecure registry (see Docker Daemon). Docker Desktop ignores certificates listed under insecure registries, and does not send client certificates. Commands like docker run that attempt to pull from the registry produce error messages on the command line, as well as on the registry.
To learn more about how to set the client TLS certificate for verification, see Verify repository client with certificates in the Docker Engine topics.
Where to go next
Try out the walkthrough at Get Started.
Dig in deeper with Docker Labs example walkthroughs and source code.
Подсистема Docker в Windows
Подсистема и клиент Docker не входят в состав Windows, потому их нужно устанавливать и настраивать отдельно. Кроме того, подсистема Docker может принимать множество пользовательских конфигураций. Например, можно настроить то, как управляющая программа принимает входящие запросы, сетевые параметры по умолчанию и параметры ведения журнала и отладки. В ОС Windows эти конфигурации можно указать в файле конфигурации или с помощью диспетчера служб Windows. В этом документе объясняется установка и настройка подсистемы Docker; также представлены примеры некоторых часто используемых конфигураций.
Установка Docker
Для работы с контейнерами Windows требуется Docker. Docker состоит из подсистемы Docker (dockerd.exe) и клиента Docker (docker.exe). Самый простой способ установить все необходимые компоненты изложен в кратком руководстве, которое поможет настроить и запустить первый контейнер.
Сведения об установке с помощью сценария см. в разделе Использование сценария для установки Docker EE.
Прежде чем использовать Docker, необходимо установить образы контейнеров. Дополнительные сведения см. в документации по образам контейнеров.
Настройка Docker с помощью файла конфигурации
Предпочтительным способом настройки подсистемы Docker в Windows является использование файла конфигурации. Путь к файлу конфигурации — C:\ProgramData\Docker\config\daemon.json. Если этот файл еще не существует, его можно создать.
Не все доступные параметры конфигурации Docker применяются к Docker в Windows. В примере ниже показаны параметры конфигурации, которые применяются. Дополнительные сведения о конфигурации подсистемы Docker см. в статье Docker daemon configuration file (Файл конфигурации управляющей программы Docker).
Достаточно только внести необходимые изменения в файл конфигурации. Например, в этом случае подсистема Docker настраивается на прием входящих подключений через порт 2375. В других параметрах конфигурации будут использоваться значения по умолчанию.
В примере ниже управляющая программа Docker настраивается на прием только защищенных подключений через порт 2376.
Настройка Docker в службе Docker
Распространенные конфигурации
В следующих примерах файла конфигурации представлены распространенные конфигурации Docker. Их можно объединить в один файл конфигурации.
Создание сети по умолчанию
Чтобы настроить подсистему Docker таким образом, чтобы не была создана сеть NAT по умолчанию, используйте следующую конфигурацию.
Дополнительные сведения см. в статье Управление сетями Docker.
Задание группы безопасности для Docker
Конфигурация прокси-сервера
После задания переменной перезапустите службу Docker.
Дополнительные сведения см. в разделе Windows Configuration File (Файл конфигурации Windows) на сайте Docker.com.
Удаление Docker
В этом разделе описывается, как удалить Docker и выполнить полную очистку компонентов системы Docker в Windows 10 или Windows Server 2016.
Все команды в этих инструкциях необходимо выполнять из сеанса PowerShell с повышенными привилегиями.
Подготовка системы к удалению Docker
Перед удалением Docker убедитесь, что в системе не запущены контейнеры.
Выполните следующие командлеты, чтобы найти работающие контейнеры:
Кроме того, перед удалением Docker рекомендуется удалить все контейнеры, образы контейнеров, сети и тома из системы. Это можно сделать, выполнив следующий командлет:
Удаление Docker
Затем необходимо начать собственно удаление Docker.
Удаление Docker в Windows 10
Удаление Docker в Windows Server 2016
В сеансе PowerShell с повышенными привилегиями используйте командлеты Uninstall-Package и Uninstall-Module, чтобы удалить модуль Docker и соответствующий ему поставщик Управление пакетами из системы, как показано в следующем примере:
Очистка данных и системных компонентов Docker
После удаления Docker необходимо удалить сети Docker по умолчанию, чтобы их конфигурация не оставалась в системе после того, как Docker будет удален. Это можно сделать, выполнив следующий командлет:
Удалите сети по умолчанию Docker в Windows Server 2016.
Выполните следующий командлет, чтобы удалить программные данные Docker из системы:
Можно также удалить необязательные компоненты Windows, связанные с Docker и контейнерами в Windows.
К ним относится компонент «Контейнеры», который автоматически включается в любом экземпляре Windows 10 или Windows Server 2016 при установке Docker. Это также может быть компонент «Hyper-V», который автоматически включается в Windows 10 при установке Docker, однако в Windows Server 2016 он включается вручную.
Компонент Hyper-V является общим компонентом виртуализации, который обеспечивает гораздо большую функциональность, чем при использовании одних только контейнеров. Прежде чем отключить Hyper-V, убедитесь, что в системе нет других виртуальных компонентов, которые зависят от Hyper-V.
Удаление компонентов Windows 10
Удаление компонентов Windows Server 2016
В сеансе PowerShell с повышенными привилегиями выполните следующие командлеты, чтобы отключить компоненты Контейнеры и (необязательно) Hyper-V.
Перезагрузка системы
Чтобы завершить удаление компонентов и очистить систему, выполните следующий командлет из сеанса PowerShell с повышенными привилегиями для перезагрузки системы:
Установка и правильная настройка Docker на Windows Subsystem Linux (WSL)
Предварительные требования
Прежде чем начать, убедитесь, что ваша система имеет примерно следующую конфигурацию:
Установка Docker-CE 17.09.0
Мы будем устанавливать Docker Community Edition 17.09.0 (потому что на момент написания этой статьи более свежие версии падали при установке на WSL).
Первое, что мы сделаем — избавимся от всех предыдущих установок Docker (если таковые были). Для этого запустим bash-терминал и напишем следующее:
Теперь установим репозиторий для Docker CE. Через apt-get мы можем установить нужную версию, самостоятельно не занимаясь её сборкой из исходников. Следуя рекомендациям на официальном сайте Docker, мы пишем следующие команды:
Если вы когда либо добавляли новый репозиторий с помощью apt, всё это вам в целом знакомо. Если нет — надеюсь, вы всё равно остались со мной 🙂
Далее устанавливаем Docker:
Если вы не используете WSL в стиле Ubuntu, список доступных версий можно посмотреть так:
… или использовать аналогичную команду какой-то другой библиотеки, если вы отказались от APT
В конце нужно добавить своего текущего пользователя в группу ‘docker’, чтобы получить возможность правильно использовать Docker Engine («движок»), который должен быть запущен в вашей системе с правами root.
Запуск Docker на Windows
Теперь, когда Docker установлен, нам нужно использовать довольно хитрый метод, чтобы запускать его как службу в WSL каждый раз при загрузке Windows. Это не так легко, как может показаться. Нам нужно действовать от имени суперпользователя и запустить командную оболочку с повышенными привилегиями, что немного усложняет задачу.
Чтобы немного упростить процесс, создайте в /usr /local/sbin/ новый файл — скрипт, который содержит соответствующие команды для запуска сервиса Docker:
со следующим содержимым:
Первая команда sudo — это монтирование cgroups (оно выполнится при перезагрузке), а вторая отдает сервис docker в руки systemd (это подсистема Ubuntu для инициализации и управления службами).
Теперь разрешите скрипту запуститься и выполните его:
Однако сервис Docker не запустится по двум причинам:
Запуск скрипта с правами root без пользовательского ввода
В ОС семейства Linux файл /etc /sudoers определяет, кто и что может запускать с правами суперпользователя. Давайте модифицируем его так, чтобы ваш пользователь смог вызывать скрипт без необходимости постоянного ввода пароля root. (Но будьте очень осторожны с этим файлом! Очень легко выпилить себя из системы, если вы не знаете, что делаете!)
Теперь мы можем запустить сервис Docker с правами root без пользовательского ввода:
Правильный запуск Docker при загрузке Windows
Теперь при загрузке системы мы сможем запустить Docker от имени администратора с помощью отдельной команды, не требующей взаимодействия с пользователем.
Запустите Планировщик задач Windows и выберите Task Scheduler Library на левой панели. Затем выберите Create Task (создать задачу) на правой панели.
Далее вам предложат отредактировать основные настройки задачи. Дайте вашей задаче понятное название и убедитесь, что остальные настройки соответствуют моим. Важно, чтобы вы выбрали «Запуск с повышенными привилегиями» (Run with highest privileges).
Во вкладке Triggers добавьте новый триггер, который будет запускать задачу сразу же, как только локальный пользователь выполнит вход.
Обратите внимание, что это нужно делать с повышенными привилегиями, поэтому проверьте галочку Run with highest privileges на вкладке General.
Остальные параметры в основном зависят от индивидуальных предпочтений, но я покажу свои настройки. Если хотите — можете их скопировать. Некоторые параметры питания могут не отображаться, если вы сидите на стационарной машине. Лично я пользуюсь ноутбуком.
Ну вот, всё идёт так, как мы задумали. Если вы на предыдущих этапах еще не запускали Docker, используя команды с повышенными привилегиями, просто щёлкните правой кнопкой мыши по задаче, созданной нами в Планировщике задач, и выберите «Выполнить»! Вот и всё!
Проверьте, что всё работает
Если хотите перестраховаться — перезагрузите свою машину (да, ради этого вам придётся в кое веки закрыть вкладки вашего браузера), запустите bash и введите:
Если всё пройдёт хорошо, то вы увидите стандартное приветствие Docker’а. Сервис запустится автоматически и прямо в WSL! Мои поздравления!
Закругляемся
Вы только что установили и запустили Docker в WSL. Это означает, что ваши контейнеры теперь могут совместно использовать Ubuntu, уже работающую в вашей системе. Таким образом отпадает необходимость разворачивать новую (виртуализированную) ОС, как это делает обычный Docker для Windows.
Производительность работы Docker в WSL пока [на момент написания оригинальной статьи] оставляет желать лучшего, но по мере развития платформы и выпуска обновлений Windows она будет только улучшаться.