На днях столкнулся с тем, что Docker под Windows очень медленно работает и тормозит при открытии самой простой страницы по 3-4 секунды.
Погуглив, а также пообщавшись с коллегами, я нашел целую кучу решений, которая по итогу решила вопрос, поехали!
Честно говоря, основные советы в интернете сводятся в переквалификации в DevOps, например рекомендуется «Docker Volumes для директорий кеша» и т.д., но мы же привыкли «херак и в продакшен», верно 🙂 ?
Итак вариант №1 (подсказали коллеги) — не работать через хваленый WSL2.
Для этого нужно перейти в настройки и снять галочку с «Use the WSL 2 based engine (Windows Home can only run the WSL 2 backend)», а затем установить компонент Windows «Hyper-V». После чего Docker должен перестать так сильно тормозить и ускорится в работе.
Однако … у меня этот вариант не сработал, потому что такая фишка доступна только Windows 10 Pro, а если у вас Home, как и у меня — то такой вариант не не сработает (ну или надо будет апнуть версию Windows, что не всегда возможно)
Вариант №2 — перекинуть весь проект в файловую систему WSL2
Как написали в стаке — такая медленная работа и тормоза из за того, что WSL используют файловую систему линукса, а тома винды просто подмонтированы, и процесс чтения с NTFS намного медленнее. На единичном файле это незаметно, но если у вас сотня файлов (а во фреймворках это так и есть), то сей процесс и занимает несколько секунд.
Решение простое — перекидываем весь проект в WSL2, для этого открываем сетевую шару \\WSL$ в проводнике, там будет находится папка с названием вашего WSL дистрибутива, например у меня это Ubuntu
Затем перекидываем туда проект, например в папку /home/, и запускаем docker-compose up, скорость ответа вас приятно удивит.
Каких то неудобств при работе нету, тот же PhpStorm отлично грузит проекты через сетевую шару (тем более формально это на этом же ПК), единственный минус, что все по дефолту размещается на диске С, ну это такое.
Так что смело перекидывайте проекты Docker в файловую систему WLS и тормоза пропадут.
CHALLENGE: Incorrectly configured Docker leads to slow Docker on Windows performance
SOLUTION: Run Docker Windows from Ubuntu 20.04 LTS with WSL2 enabled
Docker Windows performance problems
If you want to use Docker on Windows, the Docker Desktop application needs to be installed. However, installation with default settings usually causes Docker performance poor and not very fast.
One of the more common problems for Developers that use Windows is that the projects with Docker configuration work really slowly, to a point when sometimes a single browser request needs to wait 30-60 seconds to be completed. This is obviously a problem, one that negatively affects project progression and generally makes the life of developers more difficult.
Why is Docker slow on Windows?
The root of the issue is that Windows 10 is (was) using WSL (Windows Subsystem for Linux), which is a layer between Windows and Linux. Communication between these two (Hard Drive operations) can be quite slow
Solution for slow Docker on Windows performance improvement
The suggested solution is:
- use WSL 2 in Windows 10
- and start Docker directly from Ubuntu in Windows
Check out the step-by-step tutorial below. The “WSL 2” feature, released as Windows Update in mid 2020, was designed to increase file system performance and support full system call compatibility. Properly configured Docker and Windows WSL2 will give you really good performance in terms of speed.
Explanation: Windows Subsystem for Linux (WSL) 2 introduces a significant architectural change as it is a full Linux kernel, allowing Linux containers to run natively without emulation. To get the best out of the file system performance when bind-mounting files, we recommend storing the source code in the Linux file system, rather than the Windows file system.
Step 1: ENABLE WSL2 on Windows
A. Enable WSL 2 on your Windows
B. Install Linux on Windows 10 (Ubuntu 20.04 LTS from Microsoft store)
C. Enable WSL 2 on Ubuntu 20.04
D. Install Docker Desktop
E. Enable WSL 2 for Docker
More info: https://www.padok.fr/en/blog/docker-windows-10
Step 2: Install SSH on Ubuntu
We want to enable SSH connection to Ubuntu and we will be using it for local files’ “deployment”. Our goal here is:
– We have a GIT project cloned on the main Windows hard drive (SSD)
– We’re developing using PHPStorm
– PHPStorm Files’ deployment is configured in a way to automatically send files to Ubuntu.
– With this setup, we will instantly see the changes to our code in the browser.
How to configure SSH on Ubuntu:
https://linuxize.com/post/how-to-enable-ssh-on-ubuntu-18-04/
Step 3: Configure PHPStorm Deployment
A. File / Settings / Build, Execution, Deployment – Deployment
B. Click + (to add a new deployment config) – choose SFTP
C. Fill in ‘SSH configuration’
– Host: your Ubuntu public IP
(to find the proper IP address, type the following command in your Ubuntu: ip a)
– User name: your ubuntu username
– Authentication type: Password
– Password: your ubuntu pass
D. Set proper directories mapping in: Deployment / Mappings
E. Deployment / Options:
– find the option ‘Upload change files automatically to the default server’ and set to ‘Always’
Step 4: ssh to Ubuntu, run Docker
A. Open your SSH Client (ex: Cmder ) and connect to Ubuntu using SSH connection:
$ ssh myusername@111.222.33.44
(use your Ubuntu credentials here, we were using the ones in PHPStorm Deployment configuration)
B. Log in to the root account:
$ sudo su
C. Run Docker:
$ docker-compose up -d
Step 5: Connect to the database
- Log into your Docker container:
$ docker exec -it myproject_php bash
$ cd /var/www/html/public/
B. Download MYSQL Client:
$ wget https://github.com/vrana/adminer/releases/download/v4.7.7/adminer-4.7.7-mysql.php
C. Find database credentials (in Docker configuration files), ex:
DATABASE_URL=mysql://root:mypass@mysql:3306/mydatabasename
C. Open the following link in the browser: http://localhost/adminer-4.7.7-mysql.php
Server: mysql
Username: root
Password: mypass
Database name: mydatabasename
Docker WordPress with 50ms response
Docker on Windows where commands are run from the Ubuntu App has a really good response time. Instead of using emulation, the container runs natively on Linux. A single blog post page in WordPress response (TTFB) is 50ms, which is quite a good result!
This Docker solution is not only for WordPress
This solution for fast Docker in Windows is not only restricted to WordPress CMS. There is no difference if you’re using PHP Symfony, React Node server or Ruby on Rails – you will see the difference in performance speed.
Summary
That’s it. We’ve configured:
– WSL2 on Windows
– Ubuntu Linux on Windows
– PHPStorm Deployment
– Running Docker from Ubuntu
– Have ability to access Docker database
This configuration allows Docker to run really fast. Instead of waiting 60 seconds, now the browser request will run faster than 1 second!
Troubleshooting
* Error after trying to start Docker, ex: ERROR: Encountered errors while bringing up the project.
– always use Ubuntu being logged in as a root:
$ sudo su
* I see an error related to “not sufficient permissions”
– Run Powershell or the SSH Client using the ‘Run as administrator’ option
* I can’t install SSH on Win Ubuntu:
sudo su
apt install openssh-server
service ssh start
service ssh status
If you get the following error: sshd: no hostkeys available – exiting :
https://www.garron.me/en/linux/sshd-no-hostkeys-available-exiting.html
If you get the following error: Permission denied (publickey):
nano /etc/ssh/sshd_config
Find: PasswordAuthentication
Set it to: yes
#and then restart the ssh service:
service ssh restart
https://askubuntu.com/questions/311558/ssh-permission-denied-publickey/881518#881518
* hyper-v is not enabled
To Enable Hyper-V
Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V –All
To Disable Hyper-V
Disable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V-All
https://www.poweronplatforms.com/enable-disable-hyper-v-windows-10-8/ 1
* Check if hyper-v is enabled:
Run WIN Powershell (with Admin rights) and execute:
$hyperv = Get-WindowsOptionalFeature -FeatureName Microsoft-Hyper-V-All -Online
if($hyperv.State -eq “Enabled”) {
Write-Host “Hyper-V is enabled.”
} else {
Write-Host “Hyper-V is disabled.”
}
Do you need someone to implement this solution for you? Check out our specialists for hire in the outsourcing section.
Are you considering a global project and need custom web application development? Check out our offer!
Please, check https://docs.docker.com/docker-for-win/troubleshoot/.
Issues without logs and details cannot be debugged, and will be closed.
- I have tried with the latest version of my channel (Stable or Edge)
- I have submitted Diagnostics
- I have included the Diagnostics ID in this Issue
- Windows Version: Windows 10 Pro
- Docker for Windows Version: 10.03.0-ce
Expected behavior
Be able to run all the commands with relatively good response time.
Actual behavior
The response times are pretty awful. They are on at least 25x slower than the Docker Toolbox.
Information
Diagnostic ID: E8F1D8B2-B010-4076-BF6D-E78E749871E8/2018-04-10_13-17-34
Currently running Windows 10 Pro, with 32GB memory, 1TB SSD, Intel quad-core at 2.8GHz (not hyperthreading processes), so pretty good hardware.
Using Docker for Windows with Hyper-V enabled.
Equally slow on Windows and Linux Containers.
Reset to default and failed to achieve any difference.
Equally slow with cmd, powershell, and git bash terminals.
Settings for Docker increased to 10GB memory and 4 CPU cores with no improvement.
Already up to date, so updating won’t help.
Steps to reproduce the behavior
- … Download Docker for Windows
- … Use it and cry
Еще не опытен в докере, поэтому возможно чего то не знаю
Проблема в следующем:
Установил докер, написал небольшой docker-compose с обычным nginx и php-fpm
Все работает, с этим проблем нет
Но то КАК это работает вызывает кучу вопросов
Используется composer, если использовать «нативный» композер, то он устанавливает все зависимости за уловные секунд 40-50
Если устанавливать зависимости из под контейнера, то это спокойно можно идти заваривать чай. Все устанавливается минуты за 2 если не больше
То же самое с npm. За время которое работает npm run dev можно спокойно идти по своим делам
Так же при открытии обычной страницы
Если делать это «по старому»(не через докер) то все грузится за пару секунд
Если заходить через докер, то это не менее вечных секунд 30
Все это дело происходит на маке:
MacBook Pro (Retina, 13-inch, Late 2013)
2,6 GHz 2‑ядерный процессор Intel Core i5
8 ГБ 1600 MHz DDR3
Macintosh HD
Intel Iris 1536 МБ
Думал что может дело в системе, тк до этого не пользовался докером и была целая куча разных пакетов установлено. Решил почистить систему, но результата это не принесло
Tl;dr Increase Docker speed when developing on Linux containers in Windows by installing a preview version of Windows, installing WSL 2 and by using the Edge version of Docker.
When working with Docker, even in a Windows development environment, the default option is to use Linux containers. Microsoft have made it possible to run Linux containers in Windows through what is called Windows Subsystem for Linux (WSL), which is a layer between Windows and Linux distros like Ubuntu.
All calls to from Windows to the Docker container are translated on the way, and especially operations that read and write to disk have been quite slow. This causes a significant overhead compared to running Linux containers on a Linux machine.
Earlier this year Microsoft released version 2 of WSL, which was a major rewrite of the WSL architecture. WSL 2 works by running a custom Linux kernel inside Windows. This kernel has direct access to Windows’ file system, which means the file handling is a lot faster in WSL 2 compared to WSL.
Read more about the release of WSL 2 on Microsoft’s developer blog:
https://devblogs.microsoft.com/commandline/announcing-wsl-2/
The Docker developers have since released a preview (Edge) version of their Windows application, to take advantage of WSL 2.
As a developer working in Windows, there are 3 steps you need to take to use the faster Docker version:
- Install Windows 10 Preview
- Install WSL 2
- Install Docker Edge
Install Windows 10 preview
To install preview versions of Windows, you need to join the insider program:
- Open Settings from the start menu
- Open Update & Security
- Open Windows Insider Program
Follow the wizard to join the insider program, you need to have a personal Microsoft account to join. To be able to install WSL 2, you only need the «Slow» setting, meaning you will get a pretty stable preview version of Windows.
After you have joined the insider program, go to Windows Update to install the next preview version of Windows.
This takes a while, go grab a coffee while you wait.
Install WSL 2
In a command window, run the following command to see what version of WSL you have:
C:\> wsl --list --verboseCommand for displaying version of WSL distros
If you don’t get anything here, you probably don’t have WSL installed or enabled at all.
Follow this guide to set up WSL:
https://docs.microsoft.com/en-us/windows/wsl/install-win10
If you get a list with one or more Linux distros, like Ubuntu, and version 1, follow this guide to enable WSL version 2 and update your distro to take advantage of it:
https://docs.microsoft.com/en-us/windows/wsl/wsl2-install
When you run the command again, you should see something like this:
C:\> wsl -l -v
NAME STATE VERSION
Ubuntu Stopped 2Command line showing Ubuntu with WSL 2 installed
Install Docker Edge
- Install Docker Desktop for Windows
- Run it
- Right click the Docker icon on the taskbar and select Settings
On the settings page in Docker, you should have a link at the bottom, like this:
Click the link to switch to another version.
Select «Docker Desktop Edge» and install it.
NB! If the installation of Edge through Docker doesn’t work (it didn’t for me), download Docker Edge directly and run the installer.
The easiest place to find the newest Edge release at the moment, is through the Docker Edge release notes here:
https://docs.docker.com/docker-for-windows/edge-release-notes/
If you run into any problems, have a look at the Docker documentation for enabling WSL 2:
https://docs.docker.com/docker-for-windows/wsl-tech-preview/
Enable WSL 2 support in Docker Edge
Open the Docker settings, by right-clicking the Docker icon on the taskbar.
Enable WSL 2:
If you got this far, good job!
Lean back and enjoy faster startup times and faster file reading and writing when running your Docker Linux containers in Windows.
