If you’re curious about Docker but haven’t used it, you’re at the right place. While Docker is technical at its core, our goal is to make our tools approachable for all users regardless of their familiarity with containers. This blog introduces Docker technology, Docker Desktop, and why you should care about both.
What is Docker?
Before talking about Docker, let’s take a moment to highlight containers. A container packages code and all its dependencies into a single unit, thus letting an application run quickly and reliably from one computing environment to another. This makes such applications easily portable between machines and solves the “it works on my machine” problem. Though the technology behind containers has been around for a while, Docker made it easier to work with containers. Since its debut in 2013, Docker has become an industry standard. Currently, the core technology exists as a popular, open-source container runtime called Docker Engine.
To create Docker containers, you’ll first need a Docker image. If you’re familiar with object-oriented programming concepts, think of images as classes and containers as objects. Images include everything needed to run an application: code, runtime, system tools, system libraries, and settings.
What can I use Docker for?
Docker simplifies application development and removes complexities for you and many other developers around the world. This allows you to be more productive and devote more time to your actual development process. You can deploy both simple and complex applications more easily. Docker is ideal for the following use cases, and many more:
- Software prototyping and packaging
- Microservice architecture implementation
- Network modeling
- Continuous integration and delivery
- Reducing debugging overhead
- Running more workloads on the same hardware
What is Docker Desktop?
One of the best ways to get started with Docker is by installing Docker Desktop—especially if you’re a developer using Mac or Windows. That said, you might be wondering, “What’s Docker Desktop, and how’s it different from the open-source Docker Engine?”
While some developers envision Docker Desktop as just a GUI on top of Docker Engine, that characterization barely scratches the surface. Docker Desktop is an easy-to-install application and includes Docker Engine, Docker CLI client, Docker Compose, Docker Content Trust, Kubernetes, and Credential Helper. Docker Desktop still uses Docker Engine at its core. However, the seamless integration and interoperability of these tools makes Docker Desktop user-friendly—regardless of your experience with Docker.
By installing and using Docker Desktop, you’ll enjoy the following features:
- Simple and easy-to-install environment to build, ship, and run your containers
- Easy way to create and manage using volumes
- Local and remote management of Docker images
- Better collaboration by sharing repeatable and reproducible development from your local machine to the container
- Simple, one-click Kubernetes setup for your local machine
- A dashboard for a quick overview of running containers, images, and volumes
- Support for building and using multi-architecture images
Docker Desktop adds these additional features atop existing open-source tooling, allowing you to easily maintain, monitor, and update Docker tooling. It also provides you with a consistent experience across different OSes. Docker Desktop makes collaboration easy using Docker Dev Environments, allowing teams to share their work with one click via Git or Docker Hub. It also has an easy-to-use UI for many common actions:
- Starting a container
- Pausing and resuming a container
- Stopping a container
- Setting up a single-node local Kubernetes cluster
- Creating or deleting volumes
Additionally, both the GUI and CLI are always available to you based on your preferences.
How do I get started?
Check out our official documentation to learn more about best practices. The documentation has helpful quickstart resources and language-specific guides. The Docker Desktop documentation also provides an overview of key features with usage instructions.
Additionally, Docker users can learn, connect, and collaborate with each other via our Docker Community Slack channel. You can chat with Docker community leaders, Docker Captains, and your fellow local developers in the channel. You’ll also get up-to-date information about Docker-related events, conferences around the world, and Docker community all-hands events. Docker is also the most-loved tool according to Stack Overflow’s 2021 Developer Survey. Other users are always willing to lend a helping hand.
Hoping to learn at your own pace? A list of comprehensive hosted labs, self-guided tutorials, books, and self-guided online courses are summarized in the documentation under the education resources section.
Exploring Docker Desktop with a quick example
If you’ve installed Docker Desktop and want to explore more, here’s a quick example to get you started:
- Open Docker Desktop.
- Type the following command in your terminal:
docker run -d -p 80:80 docker/getting-started
- Open your browser to http://localhost
- Follow the instructions for either Mac or Windows to access your dashboard
You should see something like the screenshot below, where a container called objective_merkle is visibly running. Container names are randomly generated—with the first word being an adjective, and the last name referencing either a notable scientist or hacker (more information in this GitHub repo).
If you look at the command, there are a few flags after the command “docker run” to get the container running. A simple explanation for them is:
-d
runs the application in the background-p 80:80
provides the mapping from the host port to the container port. You can learn more about port mapping here.docker/getting-started
is the container image being used
Once you type the command, Docker recognizes the flags, executes the command, and looks for the image locally. If you don’t have an image by this name on your system, Docker will automatically find and retrieve it from Docker Hub. If you’re new to Docker, just think that Docker Hub is to Docker what GitHub is to Git.
The image that you pulled is on Docker Hub. Another way to pull this using the following command on your terminal
docker pull docker/getting-started
The image is a simple to-do list manager running on Node.Js. This tutorial does not require any JavaScript experience. Detailed information can be found on the tutorial page or by clicking on http://localhost after running the container. This tutorial dives much deeper into various aspects of Docker and Docker Desktop than this blog.
One More Thing
This blog centers primarily on Docker Desktop for Mac and Windows, but we’re thrilled to announce that Docker Desktop for Linux is coming soon. Docker Desktop for Linux (DD4L) is the second-most popular feature request in our public roadmap. If you want to become an early adopter, check out our guide for installing the Docker Desktop for Linux Tech Preview. You can play a key role in helping improve Docker Desktop for Linux prior to launch.
Check out the hands-on demo of Docker Desktop for Linux at our Community All Hands event on March 31, 2022. You’re also invited to join other developers—and boost your development skills—at DockerCon 2022. Pre-event training kicks off on May 9th, while our virtual event begins on May 10th. See you there!
Эта статья даст вам полное представление о 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.
истемные требования:
- Windows 10 или Windows Server 2016 Professional или Enterprise Edition
- Поддержка Hyper-V.
Чтобы запустить Hyper-V, оборудование должно соответствовать следующим требованиям:
- 64-битный процессор
- > = 4 ГБ ОЗУ
- Поддержка виртуализации оборудования на уровне BIOS
Следовательно, программная и аппаратная зависимость заключается в запуске Docker Desktop на Windows.
Установка Docker на macOS
Вы можете скачать репозиторий Docker Desktop из Docker Hub.
Системные требования:
- 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
С помощью простой команды run
образы можно скачивать и загружать на GitHub или Docker Hub, и любой пользователь во всем мире может получить к нему доступ и начать работать с ним.
Docker Container запускает образ Docker. Следующим шагом является запуск контейнера.
docker run -p 6379 Redis
Будет создан зашифрованный идентификатор контейнера. Вы можете быстро проверить состояние работающего экземпляра в Docker, нажав на Dashboard option.
Обязательно остановите контейнер, прежде чем удалять его из Docker Engine.
Возможности Docker Desktop
Существует множество преимуществ:
- Поддерживает широкий спектр инструментов разработки.
- Обеспечьте быстрый и оптимизированный способ создания и публикации контейнерного образа на любой облачной платформе.
- Простота установки и настройки полной среды Docker
- Повышение производительности благодаря встроенной виртуализации Hyper-V для Windows и HyperKit для MAC.
- Возможность работать в Linux через WSL 2 на компьютерах с Windows.
- Легкий доступ к работающим контейнерам в локальной сети.
- Возможность поделиться любым приложением на облачной платформе, на разных языках и в разных средах.
- Для обеспечения безопасности и актуальности выполняются автоматические обновления.
- Включены последние версии Kubernetes.
- Возможность переключения между Linux и Windows сервером на Windows.
Docker Desktop — это нативное приложение, разработанное на Windows и MAC OS для запуска, сборки и доставки контейнерных приложений или сервисов.
Однако
Docker Desktop предназначен не для производственной среды, а для рабочего стола и среды разработки.
Также рекомендуем прочитать:
- Docker для начинающих — технология контейнеров
- В чем разница между Docker и Kubernetes?
- Введение в Docker Hub и все, что вы должны знать о нем
- Как установить Docker на Ubuntu, Windows, Debian и CentOS?
- Kubernetes — Введение для начинающих
- Docker посмотреть запущенные контейнеры, запустить или остановить контейнеры
Время на прочтение
4 мин
Количество просмотров 12K
Хотелось бы поделиться «граблями», на которые успел наступить при работе с docker, интересными фишками и вообще рассказать про эту замечательную технологию.
Что за зверь такой?
Думаю, сегодня уже все слышали про docker, но все же:
Docker — контейнеризатор приложений. =) (более развернутое пояснение на вики)
А тут я собрал основные свойства технологии:
Система контейнеров
Возможность добавлять в контейнер сам проект , среду окружения , сервер и все остальное
Запуск на любой машине без установки среды
Запуск с помощью одной команды
Безопасность
Возможность тестирования новых технологий без ее установки
Установка
Установка вполне дефолтная, но все же уделю этому немного внимания
Первое, что необходимо сделать — перейти на официальный сайт (удивительно, правда?!)
далее, как показано на скриншоте выше, вбираем вашу систему, и дожидаемся загрузки.
Стандартная установка и все, поздравляю, Вы установили себе Docker Desktop.
На ОС Windows может появиться ошибка, связанная с Hyper-V (система аппаратной визуализации)
Решение:
Переходим в папку с Docker -> открыть файл start.sh ->открываем в любом текстовом редакторе -> найти следующую строку:
«${DOCKER_MACHINE}» create -d virtualbox $PROXY_ENV «${VM}»
->заменить на :
«${DOCKER_MACHINE}» create -d virtualbox —virtualbox-no-vtx-check $PROXY_ENV «${VM}«
->снова запустить процесс установки (готово)
Работа с Docker
Есть несколько способов работы с Docker :
-
Работать в Docker Desktop (как устанавливать смотреть выше!)
-
При помощи cmd
-
Через IDE
Первый запуск
Запускаем наш Docker Desktop и открываем командную строку. После запуска приложения, у Вас должна отображаться следующая иконка (в скрытых значках):
в командной сроке пишем следующую команду:
docker
и если все верно сделано, то у Вас отобразиться список всех доступных команд и их описание:
Проверьте переменные зависимости. В переменной Patch мог не прописаться путь до docker.exe. Найдите путь до docker.exe (обычно в папке bin) и добавьте путь в переменную Patch
Надеюсь у Вас все хорошо, и команда docker заработала и описание команд появилось и погода хорошая. Теперь то можно и скопировать команду из Docker Desktop
и выполнить ее в командной строке. По идее должно получиться следующее:
И что же мы сделали? Создали и запустили контейнер docker/getting-started на порту 80.
Вернемся в наш Docker Desktop и видим следующее:
Поздравляю — мы запустили контейнер.
Перейдем во вкладку Images и увидим следующее:
Видим образ, на основе которого создался наш контейнер. (это все мы сделали командой выше)
Посмотреть информацию можно вернувшись в командную строку и прописав команду:
docker info
тогда увидим следующее
Видим всю информацию про все контейнеры и образы.
Давайте-то уже посмотрим, что у нас получилось. Переходим в Docker Desktop во вкладку Containers/Apps и нажимаем следующее:
Hello world! по docker-ски
Можем насладиться проделанной работой)
Контейнеры и образы
Контейнеры, образы — чтооооо?!
Давайте теперь немного теории(совсем чуть-чуть)
Образ – готовое решение , содержащее некий функционал(нельзя изменять), на его основе можем создать свой контейнер
Контейнер – это собранный проект , состоящий из образов: упакованное (контейнеризированное) приложение на основе образов
Посмотрим на картинку ниже:
Тут наглядно показан принцип работы технологии docker, но все же, уточним моменты:
-
Docker deamon – промежуточный api для нахождение и скачивания нужного image
-
Docker hub — место сбора различных образов
-
Images –образы
-
Containers- контейнеры
Установка образа
Давайте попробуем развернуть какой-нибудь контейнер (что-то повеселее стартовой страницы).
-
Заходим на сайт docker
-
Переходим во вкладку: Explore
-
В поиске вводим название нужного образа (я буду скачивать образ java- вы можете выбрать любой другой)
находим следующее
нажимаем, видим сразу готовенькую команду:
Копируем и вставляем в командную строку –> тем самым устанавливаем себе образ java:
Запуск образа
Давайте теперь создадим и запустим контейнер на основе только что скачанного образа.
docker run имя_образа
«Стоп» — скажите Вы . А откуда взять имя образа? А вот от куда:
docker images
На вас вывалится список образов, находим там нужный и вставляем в команду выше:
Что получили
Запустить образ без контейнера невозможно – противоречит принципу docker, следовательно у нас создался контейнер на основе нашего образа, который мы пытались запустить
Давайте запустим наш контейнер в интерактивном режиме и убедимся, что мы все сделали верно. Вводим команду для запуска (даем свое имя- тут я обозвал его как JavaContainer):
docker run -it --name JavaContainer openjdk
Получаем запушенный контейнер:
Видим — запустили контейнер с java (об этом нам говорит надпись jshell- java оболочка). Ну хорошо, поигрались с java, а как вернуться обратно, команды docker то уже не работают. И что делать ?
Спокойствие, только спокойствие. Нажимаем магическую комбинацию Ctrl + D:
и о чудо, можно выдохнуть)
А что еще можно запустить?
Давайте , на последок, посмотрим еще возможности docker и запустим Ubuntu.
Схема запуска не сложнее, чем мы занимались выше, все действия аналогичные:
-
Аналогично шагам выше , зайдем на сайт и найдем Ubuntu, после воспользуемся командой в описании на сайте
-
Далее запустим в интерактивном режиме:
docker run –it –name имя_контейнера имя_образа
как-то так )
Итоги
Тут я собрал некоторые полезные команды docker и их описание на русском. Может кому пригодится).
Это был краткий обзор на технологию Docker, разумеется он не претендует на полноценный гайд: не было рассказано про Dockerfile или Docker compose или про запуск контейнеров в IDE, про создание собственных образов; НО цель данной статьи — помочь ознакомиться с базой а не рассказать про все и вся). В будущем поговорим про незатронутые тут моменты в Docker. Надеюсь моя статья была для Вас полезной!
If you’re new to containers and Docker and work primarily on Windows, you’re in for a treat. In this article, you’re going to learn how to set up Docker on Windows 10 using Docker Desktop for Windows or simply referred to as Docker Desktop in this article.
Not a reader? Watch this related video tutorial!
Not seeing the video? Make sure your ad blocker is disabled.
Docker Desktop is the Docker Engine and a management client packaged together for easy use in Windows 10. In this article, you will install Docker Desktop, deploy your first container, and share data between your host and your containers.
Prerequisites for Docker on Windows
This is a walkthrough article demonstrating various steps in Docker Desktop for Docker on Windows. To follow along, be sure you have a few specific requirements in place first.
- An Internet connection to download 800MB+ of data
- Windows 10 64-bit running Pro, Enterprise, or Education edition with release 1703 or newer. This is necessary to run Hyper-V on Windows 10.
- A CPU with SLAT (nested paging) compatibility. All AMD/Intel processors since approximately 2008 are SLAT compatible
- At least 4GB of RAM
- BIOS hardware virtualization sometimes labeled as Virtualization Technology or VTx. This must be enabled and show as Enabled in the performance tab of Task Manager as shown below.
Downloading and Installing Docker Desktop
Up first, you need to download and install Docker Desktop to get Docker on Windows going. Docker Desktop comes available in two releases; a stable release and a testing release.
The stable release is released quarterly and ensures a fully-tested application. In this article, you will be using the stable release.
Warning: Upon installation, Docker Desktop will prompt you to install the Hyper-V hypervisor if not already installed. By doing so, the Hyper-V hypervisor prevents any user-mode hypervisors such as VirtualBox, VMWare, etc. from running guest VMs. Hyper-V support for VirtualBox and VMWare is limited but coming.
You also have the option of a download source through manually downloading Docker Desktop directly from Docker.com or via the Windows package manager, Chocolatey. Let’s briefly cover each method.
From Docker.com
To download Docker Desktop directly from docker.com, you can go to the product page, register for an account and download it from there. This is preferred if you intend to use Docker in production by registering an account.
However, if you’re just testing Docker out for the first time, you can also download it directly which is much easier.
Once the EXE is downloaded, run the executable and click through the prompts accepting all of the defaults.
When asked whether you plan to Use Windows containers instead of Linux containers, as shown below, do not enable the checkbox. You will be using Linux containers in this article.
Once installation is complete, reboot your computer.
Selecting the option to use Windows containers or Linux containers tells Docker to attach images to a Windows kernel or Linux kernel. You can change this setting at any time after installation by right-clicking the Docker icon in the System Tray and selecting Switch to Windows containers as shown below.
Using Chocolatey
The other option to get Docker Desktop downloaded and installed is with Chocolatey. Chocolatey automates many of the download/install tasks for you. To do so, open up a command-line console (either cmd or PowerShell) as an administrator to download and install the program in one shot by running the command below.
choco install docker-desktop
Once complete, reboot Windows 10.
If you’d like to try out the testing release at some point, you can download and install this by running
choco install docker-desktop --pre
.
Validating the Docker Desktop Installation
Once installed, Docker Desktop automatically runs as a service providing Docker on Windows. It’s shown in the system tray when you log in to Windows after you reboot. But how do you actually know it’s working?
To validate Docker Desktop is working correctly, open a command-line console and run the docker
command. If the installation went well, you will see a Docker command reference.
Finally, have Docker download and run an example container image called hello-world by running the command docker run hello-world
. If all is well, you will see output like below.
Running Commands in Docker Containers
Docker Desktop is installed and you’ve verified all is well? Now what? To get started with Docker on Windows, one common task to perform in a Docker container is running commands. Through the docker run
command, you can send commands through the host (your Windows 10 PC) directly into a running container.
To run commands in a container with docker run
, you’ll first specify an image name followed by the command. To get started, tell Docker to run the command hostname
inside of a container called alpine as seen below.
> docker run alpine hostname
b74ff46601af
Since you don’t have the alpine Docker image on your computer now, Docker on Windows will download the tiny image from the Docker Hub, bring up a container from that image, and send the command directly into the container and shut it down all in one swoop.
If you’d like to keep the container running, you can also use the -it
parameter. This parameter tells Docker to keep the container in “interactive mode” leaving it running in the foreground after executing the command. You’ll see that you are then presented with a terminal prompt ready to go.
> docker run -it alpine sh
/ #
When you’re done in the terminal, type exit
to return to Windows 10.
Accessing Files from the Docker Host in Containers
Another common task is accessing host files from containers. To access host files in containers, Docker on Windows allows you to link a folder path from your desktop to share that folder to your container. This process is called binding.
To create a binding, make a folder on a local drive. For this example, I’ll use E:\ and call it input. It’ll then create a new text document named file.txt in the folder. Feel free to use whatever path and file you wish.
Once you have the folder you’d like to share between the host and container, Docker needs to mount the folder using the --mount
parameter. The --mount
parameter requires three arguments; a mount type, a source host directory path and a target directory path. The target path will be a symbolic link within the container.
Below you will see an example of mounting the entire E:\ within the Windows 10 host to show up as the /home/TEST directory inside of the Linux container.
> docker run --mount type=bind,source="E:/",target=/home/TEST -it alpine
When you attempt to mount a host folder, Docker Desktop will ask for your permission to share this drive with the Docker containers as seen below.
If you created the file.txt file in the Windows 10 folder as described earlier, run cat /home/TEST/input/file.txt
. You will see that contents are displayed.
Now, delete the input folder that you just created and run the cat ...
command again. Observe that the shell now reports that the file does not exist anymore.
Mapping Network Ports
Another important concept to know is how Docker on Windows handles networking. For a brief introduction, let’s see what it takes to access a web service running in a container from the local host.
First, spin up a demo image that will run an example webpage. Download and run the Docker image called dockersamples/static-site. You’ll use docker container run
to do so.
The following command does four actions at once:
- Downloads a Docker image from Docker Hub called static-site in the docker-samples “directory”
- Starts a container instance up from the static-site image
- Immediately detaches the container from the terminal foreground (
—detach
) - Makes the running container’s network ports accessible to the Windows 10 host (
—publish-all
)
docker container run --detach --publish-all dockersamples/static-site
## Alternate/shorthand syntax that does the same thing:
## docker container run -d -P dockersamples/static-site
## docker run -d -P dockersamples/static-site
Once run, Docker will return the container ID that was brought up as shown below.
Publishing Network Ports
Since using the --publish-all
parameter, local host ports are now mapped to the container’s network stack. You can use the docker ps
subcommand to list all running containers including what ports are assigned to all of the running containers. In the instance below, one container is running mapping host port 32777 to container port 80 and host port 32776 to container port 443.
Docker on Windows assigns containers random ports when using the --publish-all
parameter unless explicitly define them.
Now open up a web browser and navigate to http://localhost:32777 or the port that Docker assigned to map to port 80 as output by docker ps
. If all goes well, you should see the below webpage show up.
Changing the Published Ports
You now have a Docker container running in Docker on Windows serving up a simple web page. Congratulations! But now you need to specify a specific port binding not relying on the random port selection with --publish-all
. No problem. Use the -p
parameter.
First, stop the running container by specifying a unique string of it’s container ID. You can find this container ID by running docker ps
. Once you know the container ID, stop the container and start a new one while designating Docker to assign a specific port to publish.
The syntax for specifying a port is <external port>:<container port>
. For each port that you want to publish, use the --publish
or -p
switch with the external and container port numbers as shown below.
> docker stop f766
> docker run --detach -p 1337:80 dockersamples/static-site
When you are specifying a container ID, you only have to type enough of the ID to be unique. If you are only running a single container and its ID is
f766f4ac8d66bf7
, you can identify the container using any number of characters including justf
. The requirement is that whatever you type allows it to uniquely identify a single container.
Now go to your web browser and navigate to localhost:1337
. Remember, you are not changing the image and it always listens on port 80; you are changing the port translation rule in the Docker configuration that lets you connect to the container.
Stopping all Containers
Using docker stop
, you can stop a container but how do you stop multiple containers at once? One way to do so is by providing multiple, space-delimited container IDs. You can see below an example of how to stop three containers with IDs of fd50b0a446e7
, 36ee57c3b7da
, and 7c45664906ff.
> docker stop fd50 36ee 7c45
If you’re managing Docker containers in PowerShell, you can also use a shortcut to stop all containers. Feed a list of container IDs via
docker ps -q
to the stop parameter through PowerShell’s command expansiondocker stop (docker ps -q)
.
Confirm all containers are stopped by seeing no containers listed when you type docker ps
.
Cleaning Up
You’ve downloaded a few container images and run some containers that are now stopped. Even though they’re stopped, their allocated storage isn’t gone off of the local host disk. You must delete the containers free up that space and avoid cluttering up your workspace.
To delete a single container, use the container remove rm
parameter like below.
> docker container rm <container ID>
Or, to delete all stopped containers, use the prune
parameter as below.
Last updated on 2023-10-03 |
Edit this page
This episode is meant to be demonstrative, that is, you do
not need to follow along.
Questions
- What is Docker Desktop?
- What can it be used for?
- Why can’t it replace the cli?
Objectives
- Show Docker Desktop and its components.
- Understand what images and containers are.
- Visualize the process of image aquisition, container execution and
where it ends. - Understand the ephimeral nature of containers.
- Have a glimpse at containers that allow interaction.
- Understand the importance of cleaning up in docker.
- Understand the limitations of Docker Desktop.
We will present the Docker Desktop dashboard, as it will be useful to
understand key concepts of docker, such as images and containers.
However, it is important to note that while it is mostly is free, some
features are offered at a premium. Also, it is not fully functional on
all operating systems; it can produce conflicts with the docker engine
on Linux, for example.
Getting images
Setting up docker in Windows or Mac will have installed Docker
Desktop by default. If you open the application you will likely see
something like this:
You’ll notice that the panel on the left has a tab for ‘Images’ and
another for ‘Containers’. These will be the focus for the episode, and
we will ignore most other features.
On the top you’ll also find a search icon, which links to Docker Hub,
and allows us to search for the images we saw in the previous episode
directly from here.
*Note that there are two tabs, one for containers and one for images.
Make sure that you select the right tab when you search!
In Docker Desktop you can either search by name only,
or include the owner. You can then select the tag from the dropdown
menu.
Once you find the image you were looking for, you can either download
it (pull), or directly run it.
We’ll start by downloading the latest versions of
hello-world
, docker/getting-started
and
alpine
.
Inspecting images
The ‘Images’ tab on the left panel will show all the images in your
system, so you will be able to see them here.
From this tab we can see some information about the images on disk,
and run them, but we can also inspect the images. Clicking on the image
will open a window with information on how the image is built, and
examine its packages and vulnerabilities.
The hello-world
image does not seem too interesting from
here. If you go to DockerHub you’ll find links to the Github site, where
you’ll see that the image is not as simple as it looks. Nevertheless,
this is a very nice and quick way to explore an image.
If we now inspect the docker/getting-started
image, for
example, we can see that it detects some vulnerabilities:
You can even further inspect the vulnerable layers by looking at the
command
This all looks rather scary, and it is important that we are careful
with the images that we download. It is therefore quite useful to be
able to analize them like this. This image, in particular, is from a
verified publisher (Docker Inc. no less!), and has been downloaded over
10M times, so the container is likely not maliicous.
Running containers
The images that we just downloaded are immutable files, they are
snapshots of an environment, distributed to be used as
templates to create ‘containers’. The containers are,
essentially, images being run. They are executions of the
image, and because they are running, they are no longer ‘static’.
Let’s run the hello-world
image by either clicking the
‘Run’ button in the ‘Actions’ column, from the Images tab.
A prompt will ask you to confirm ‘Run’ or modify some optional
settings.
The optional settings allow you to modify the container’s name, so
that you can easily identify it afterwards. Lets add an appropriate name
and confirm with the ‘Run’ button.
You will likely be taken to a ‘Logs’ tab inside the container that
you just ran. The logs show the output of this particular image, ‘Hello
from Docker!’ among other things.
If you look carefully, the ‘Containers’ tab on the left is
highlighted. We are looking at a container now, not an image, and so we
were re-located.
Exploring the ‘Inspect’ tab will show us some information, but for
now we are more interested in what the ‘Terminal’ and ‘Stats’ tabs have
to say. They both seem to indicate that we need to run or
start the container.
Indeed, if we look carefully, we will find an ‘Exited (0)’ status
under the container name, and a ‘Start’ button near the top-right
corner. However, if we click on that button we will see the output
duplicated in the logs, and the ‘Exited (0)’ status again.
If we go back to the images tab and run the image again (let’s not
bother giving it a name this time), we’ll see that the same thing
hapens. We get the ‘Hello from Docker!’, and the container exits.
The nature of most containers is ephimeral. They are meant
to execute a process, and when the process is completed, they exit. We
can confirm this by clicking on the ‘Containers’ tab on the left. This
will exit the container inspection and show us all the containers. Both
containers in the list have a status ‘Exited’.
You may be wondering why if we have only run the
hello-world
image, you can see there are two containers.
One of the containers we named, and the other has some gibberish as a
name (Docker generated this randomly). As mentioned before, the
image is used as a template, and as many containers as
we want can be created from it. If we go back to the ‘Images’ tab and
run hello world
again, we’ll see a new container
appear.
Interacting with containers
Not all containers are as short lived as the one we’ve been using. If
we run the docker/getting-started
image that we had pulled
earlier, we will see something different happen. You can immediately
notice the status under the container name is ‘RUNNING’ now. nal
inside the container.
The ‘Logs’ tab is not too informative, but the ‘Inspect’ tab already
shows more information. A process called ‘nginx’ is running. The
‘Terminal’ and ‘Stats’ tabs changed the most. Since the container is
still running, the stats get shown, and we are able to launch a
termi
Before trying to do anything in the terminal, let’s look at the
container list by clicking on the ‘Containers’ tab on the left. You’ll
see the green icon of the container indicating that it is still live,
and indication of how long it’s been running for.
Clicking on the container name again will take us back to the ‘Logs’
tab in the container. Lets try and interact with the terminal inside the
container. If you print the working directory with pwd
you’ll get the base directory: /
. You can also list the
contents with ls
, and the docker-entrypoint
files are a dead giveaway that we are inside the container. At this
point this container is very much like a VM. We can modify things, like
for example making a directory with mkdir
, and see it has
been created with ls
again.
But we can do more than that, we can install things. For example,
you’ll notice that htop
is not installed. Since the
getting-started
image is based on Alpine, we can install it
using apk add htop
, and we can now use it.
The container does not need to stay alive forever, and you can see
that there is a ‘stop’ icon on the top right. If we stop the container,
we get a familiar empty tab in ‘Terminal’ and ‘Stats’. The ‘Containers’
tab on the left will also show the container status as ‘Exited’
Now lets say I want to run the getting-started
image
again. So I go to the ‘Images’ tab, and click run. Now lets go to the
‘Terminal’ tab, and try and find our directory with ls
. The
directory is not there. We’d also installed htop
. so lets
have a go at running it. Not there either.
When we re-ran the image, we created a new
container. The new container is created from the template saved
in the image, and so ‘our’ changes have banished. This becomes very
clear when we go back to the ‘Containers’ tab on the left. We can see
that the first container we created from the
getting-started
image is there, next to the new container
(which is still running, by the way).
Reviving containers
We can get the old container running again, although this is
rarely something we’d want to do. In Docker Desktop, all we
need to do is click on the ‘Start’ button from the ‘Containers’ list.
The terminal will appear empty, because it is a new session, but you
will even be able to ‘recall’ commands.
Cleaning up
The hello-world
image was nice and useful to test docker
was working, but it is now rather useless. If I want to delete it, the
‘Images’ tab on the left has a convenient bin icon to do so. Clicking on
it will prompt you for confirmation, but it will fail.
You’ll probably notice that the status of the image is ‘In use’. That
seems strange though, given that all the containers from that image
excited immediately.
Lets have a look at the ‘Containers’ tab. It shows a list of 5
containers now. Three of them came from the hello-world
image, and are stopped. Two of them came from the
getting-started
image, and are running.
We’ve only been using Docker for 15 minutes though! You may see how
this can become a problem… Particularly so because we were a bit sloppy
and did not name the containers. Let’s try and get rid of the containers
then. We can conveniently select them all with the tickbox at the top,
and an option to ‘Delete’ shows up. Clicking on it will prompt for
confirmation, and we can go ahead and accept.
All our containers are now gone. Forever.
Warning: You have to be careful here, this
action deleted even the containers that were running. You can filter the
containers before you select them “all”.
On the up-side, the ‘Images’ tab shows both the
hello-world
and the getting-started
images as
‘Unused’ now. For docker, an image is ‘In use’ as long as at least one
container has been created from it. We have just deleted all the
containers created from either of these images. This tells Docker that
they are no longer being used, and can therefore be safely deleted.
Limitations — Why not Docker Desktop?
We have seen many of the neat and functional bits of Docker Desktop,
and it can be mighty appealing, particularly if you lean towards the use
of graphical interfaces. However, we’ve not touched on its weaknesses.
We’ll just need to point at one to feel the need to throw everything
overboard.
Let’s go ahead and run the only image we have already pulled,
alpine
.
That was fast, and uneventful. Not even a single output to the
‘Logs’. No way to open a terminal inside Alpine.
Just to be clear though, this Docker image does contain the whole
Alpine OS. In Docker Desktop, however, there is no way to interact with
it.
Let’s try something different. There’s a program called
cowsay
that lets you print messages as if a cow was saying
them. Searching for that image shows that there is one by
beatrixxx32
with a reasonable number of downloads.
So lets pull that image and run it.
We do get a cow this time, but it is not saying anything. But it does
not know what to say. Going back to the cowsay image search,
you may notice that in ‘Usage’ the command line asks for “your message”.
We are not using a command though, we just clicked run. Maybe
we missed something in the optional settings!
No, it does not seem like it. No matter what we do, we cannot make
the cow say anything from here.
Are the alpine and cowsay images useless? No, definitely not.
However, they are expecting some sort of input or command, which we
cannot provide from Docker Desktop.
This is the case for most images, and so Docker Desktop (as it is
now) cannot really be used for much more than as a nice dashboard.
In the next episode, we will use docker from the command line, and
all of the advantages it brings will become aparent.
Keypoints
- Docker Desktop is a great dashboard that allows us to understand and
visualize the lifecycle of images and containers. - Images are snapshots of an environment, easily distributable and
ready to be used as templates for containers. - Containers are executions of the images, often with configuration
added on top, and usually meant for single use. - Running a container usually implies creating a new copy, so it is
important to clean up regularly. - Docker Desktop could potentially be all you need to use if you only
consume images out of the box. - However, it is very limited in most cases (even for
consumers), and rarely allows the user to configure and
interact with the containers adequately.