Docker create windows image

Adam the Automator

How To Create A Docker Windows Image Using Docker Build

Kevin Sapp

Read more posts by this author.

Are you new to Docker Windows Images? Are you currently working in a Windows shop and curious to learn about Docker builds for container images? You have come to the right place. The best way to learn about new something is by doing.

In this article, you are going to learn how to create your first Windows Docker image from a Dockerfile using the docker build command.

Let’s get started!

Table of Contents

Understanding Docker Container Images

For years, the only way to test or perform development on multiple operating systems (OS) was to have several dedicated physical or virtual machines imaged with the OS version of your choice. This methodology required more hardware and overhead to provision new machines for each software and OS specification.

However, these days the usage of Docker container images has grown partly due to the popularity of micro-service architecture. In response to the rise in Docker’s popularity, Microsoft has started to publicly support Docker images for several flagship products on their Docker Hub page. They have even added native support for images for Windows as a product feature in the Windows 10 and Windows Server 2016!

A Docker image is run on a container by using the Docker Engine. Docker images have many benefits such as portability (applicable to multiple environments and platforms), customizable, and highly scalable. As you can see below, unlike traditional virtual machines, the Docker engine runs on a layer between the host OS kernel and the isolated application services that are being containerized.

Understanding Docker Build and Images

The docker build **command can be leveraged to automate container image creation, adopt a container-as-code DevOps practice, and integrate containerization into the development cycle of your projects. Dockerfiles are simply text files that contain build instructions used by Docker to create a new container image that is based on an existing image.

The user can specify the base image and list of commands to be run when a container image is deployed or startup for the first time. In this article, you will learn how to create a Windows-based docker image from Dockerfile using a Windows container.

This process has several benefits over using a pre-built container image:

  1. You are able to rebuild a container image for several versions of Windows – which is great for testing code changes on several platforms.
  2. You will have more control over what is installed in the container. This will allow you to keep your container size to a minimum.
  3. For security reasons, you might want to check the container for vulnerabilities and apply security hardening to the base image

Prerequisites/Requirements

This article is a walkthrough on learning about learning how to build a Docker image using a Dockerfile. If you’d like to follow along, ensure that you have the following prerequisites in place.

  • Docker for Windows installed. I’ll be using the Docker Community Edition (CE) version 2.1.0.4 in my environment.
  • Internet access is needed for downloading the Docker images
  • Windows 10+ Operating System (version 1709 is being used for this tutorial)
  • Nested virtualization enabled
  • 5 GB of free diskspace on your local machine
  • PowerShell 5.0+
  • This tutorial uses the Visual Studio Code IDE. However feel free to use what ever IDE you’d prefer.

Note: Be sure to enable Windows Containers Configuration when installing Docker.

Getting Prepared

You’ll first need a folder to store all of the Docker images and containers you’ll be building from those images. To do so, open a Powershell or cmd terminal (you’ll be using PowerShell throughout this article) and create a new directory called C:\Containers.

Once the folder is created, change to that directory. This puts the console’s current working directory to C:\Containers to default all downloads to this directory.

Читайте также:  Как завершить работу ноутбука с windows 10

In this article, you’ll get a headstart. Most of the files to work through this project are already available. Once the folder is created, perform a Git pull to copy over the files needed for this article from the TechSnips Github repository to the C:\Containers folder. Once complete, check to make sure that the C:\Containers folder looks like below.

Downloading the IIS Windows Docker Image

The first task to perform is to download a “template” or base image. You’ll be building your own Docker image later but first, you need an image to get started with. You’ll be downloading the latest IIS and Windows Server Core Images that are required for this tutorial. The updated list of images can be found on the official Microsoft Docker hub image page.

Reviewing the Current Docker Base Images

Before downloading the image from the image repository, let’s first review the current Docker base images that you currently have on your local system. To do so, run a PowerShell console as Administrator and then type docker images . This command returns all images on your local system.

As you can see below, the images available are initially empty.

Downloading the Base Image

Now it’s time to download the base IIS image from Docker Hub. To do so, run docker pull as shown below. This process can take some time to complete depending on your internet speeds.

Now run docker images and you should have the latest Microsoft Windows Core IIS image available for this tutorial.

Inspecting the Dockerfile

In an earlier step, you had downloaded an existing Dockerfile for this tutorial. Let’s now take a look at exactly what that entails.

Open the C:\Containers\Container1\Dockerfile file in your favorite editor. The contents of this Dockerfile are used to define how the container image will be configured at build time.

You can see an explanation of what each piece of this file does in the in-line comments.

Building a New Docker Image

You’ve got the Dockerfile ready to go and a base IIS image downloaded. Now it’s time to build your new Docker image using the Dockerfile.

To build a new image, use the docker build command. This command creates the image. For this article, you can see below you’re also using the -t **option. This option allows you to give your new image a friendly tag name and also reference the Dockerfile by specifying the folder path where it resides.

Below you can see an example of ensuring the console is in the C:\Containers directory and then building a new image from the Dockerfile in the C:\Containers\Container1 directory.

Once started, you can see the progress of the command as it traverses each instruction in the docker file line by line:

Once done, you should now have a new Docker image!

Now run the docker images command to view the images that are available. You can see below an example of the container1 image created.

Note: The docker build —help command is a useful parameter to display detailed information on the docker command being run.

Running the Docker Container

At this point, you should have a new image created. It’s time to spin up a container using that image. To bring up a new container, use the docker run command.

The docker run command will bring up a new Docker container based on the container1 image that you created earlier. You can see an example of this below.

Notice that the -d parameter is used. This tells the docker runtime to start the image in the detached mode and then exit when the root process used to run the container exits.

When docker run completes, it returns the ID of the container created. The example below is capturing this ID into a $containerID variable so we can easily reference it later.

Once the container is brought up, now run the docker ps command. This command allows you to see which containers are currently running using each image. Notice below that the running image is automatically generated a nickname (busy_habit in this case). This nickname is sometimes used instead of the container ID to manage the container.

Running Code Inside a Docker Container

A new container is built from a new image you just created. Let’s now start actually using that container to run code. Running code inside of a Docker container is done using the docker exec command.

Читайте также:  Linux and touch command

In this example, run docker exec to view PowerShell output for the Get-ChildItem command in the container using the command syntax below. This will ensure the instructions in the Dockerfile to remove the default IIS files succeeded.

You can see below that the only file that exists is index.html which means the default files were removed.

Now run the ipconfig command in the container to get the local IP address of the container image so that you can try to connect to the IIS website.

You can see below that ipconfig was run in the container just as if running on your local computer and has return all of the IP information.

Inspecting the IIS Website

Now it’s time to reveal the fruits of your labor! It’s time to see if the IIS server running in the Docker container is properly serving up the index.html page.

Open a browser and paste the IP4 Address found via ipconfig into the address bar. If all is well, you should see a Hello World!! message like below.

Reviewing Docker History

One useful command to use when working with Docker containers i the docker history command. Although not necessarily related to creating an image or container itself, the docker history command is a useful command that allows you to review changes made to the container image.

You can see below, that docker history returns all of the Dockerfile and PowerShell activity performed on the container1 container you’ve been working with.

Cleaning up the Running Docker Images

The steps below are used to cleanup all stopped containers running on your machine. This will free up diskspace and system resources.

Run the docker ps command to view a list of the containers running on your system:

Now stop the running containers using the docker stop command:

Finally you can permanently remove the stopped containers using the docker system prune command.

Создание собственного образа Docker

Docker позволяет не только загружать и использовать готовые контейнеры, но создавать свои. В данной инструкции мы пошагово разберем установку Docker на Linux, создание собственного образа и загрузку его на Docker Hub.

Установка Docker

Рассмотрим примеры установки на базе операционных систем Red Hat/CentOS и Debian/Ubuntu.

Red Hat/CentOS

Устанавливаем репозиторий — для этого загружаем файл с настройками репозитория:

* если система вернет ошибку, устанавливаем wget командой yum install wget.

. и переносим его в каталог yum.repos.d:

mv docker-ce.repo /etc/yum.repos.d/

yum install docker-ce docker-ce-cli containerd.io

Если система вернет ошибку Необходимо: container-selinux >= . , переходим на страницу пакетов CentOS, находим нужную версию container-selinux и копируем на него ссылку:

. с помощью данной ссылки выполняем установку:

yum install http://mirror.centos.org/centos/7/extras/x86_64/Packages/container-selinux-2.99-1.el7_6.noarch.rpm

После повторяем команду на установку докера:

yum install docker-ce docker-ce-cli containerd.io

Debian/Ubuntu

В deb-системе ставится командой:

apt-get install docker docker.io

После установки

Разрешаем запуск сервиса docker:

systemctl enable docker

. и запускаем его:

systemctl start docker

docker run hello-world

. мы должны увидеть:

.
Hello from Docker!
This message shows that your installation appears to be working correctly.
.

Сборка нового образа

Сборка начинается с создания файла Dockerfile — он содержит инструкции того, что должно быть в контейнере. В качестве примера, соберем свой веб-сервер nginx.

И так, чтобы создать свой образ с нуля, создаем каталог для размещения Dockerfile:

mkdir -p /opt/docker/mynginx

* где /opt/docker/mynginx — полный путь до каталога, где будем создавать образ.

. переходим в данный каталог:

. и создаем Dockerfile:

FROM centos:7
MAINTAINER Dmitriy Mosk
RUN yum install -y epel-release && yum install -y nginx
RUN yum clean all
RUN echo «daemon off;» >> /etc/nginx/nginx.conf
RUN sed -i «0,/nginx/s/nginx/docker-nginx/i» /usr/share/nginx/html/index.html
CMD [ «nginx» ]

* в данном файле мы:

  1. используем базовый образ centos 7;
  2. в качестве автора образа указываем Dmitriy Mosk;
  3. устанавливаем epel-release и nginx;
  4. чистим систему от метаданных и кэша пакетов после установки;
  5. указываем nginx запускаться на переднем плане (daemon off);
  6. в индексном файле меняем первое вхождение nginx на docker-nginx;
  7. запускаем nginx.

* подробное описание инструкций Dockerfile смотрите ниже.

docker build -t dmosk/nginx:v1 .

* где dmosk — имя автора; nginx — название для сборки; v1 — тег с указанием версии. Точка на конце указывает, что поиск Dockerfile выполняем в текущей директории.

. начнется процесс сборки образа — после его завершения мы должны увидеть что-то на подобие:

Читайте также:  Создание дистрибутива автоматической установки windows 10

Successfully built eae801eaeff2
Successfully tagged dmosk/nginx:v1

Посмотреть список образов можно командой:

Создаем и запускаем контейнер из образа:

docker run -d -p 8080:80 dmosk/nginx:v1

* в данном примере мы запустим контейнер из образа dmosk/nginx:v1 и укажем, что необходимо опубликовать внешний порт 8080, который будет перенаправлять трафик на порт 80 внутри контейнера.

Открываем браузер и переходим по адресу http:// :8080 — мы должны увидеть страницу приветствия с нашим docker-nginx:

Посмотреть созданные контейнеры можно командой:

Запустить или остановить контейнеры можно командами:

docker stop 5fe78aca2e1d

docker start 5fe78aca2e1d

* где 5fe78aca2e1d — идентификатор контейнера.

Редактирование образа

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

Скачаем образ операционной системы CentOS:

docker pull centos:latest

Войдем в скачанный образ для его изменения:

docker run -t -i centos:latest /bin/bash

Внесем небольшие изменения, например, создадим учетную запись:

[root@8f07ef93918f /]# useradd dmosk -G wheel -m

[root@8f07ef93918f /]# passwd dmosk

* в данном примере мы создали пользователя dmosk и задали ему пароль.

docker commit -m «Add user dmosk» -a «Dmitry Mosk» 8f07ef93918f centos:my

* где -m — параметр для указания комментария; -a — указывает автора; 8f07ef93918f — идентификатор контейнера, который был нами изменен (его можно было увидеть в приглашении командной строки); centos:my — название нашего нового образа.

Новый образ создан.

Загрузка образа на Docker Hub

Заходим на Docker Hub страницу регистрации. Создаем пользователя:

На следующей странице также заполняем данные профиля. После переходим в почтовый ящик, который был указан при регистрации и переходим по ссылке Confirm Your Email With Docker для подтверждения регистрации. Регистрация закончена.

Переходим на страницу Repositories и создаем свой репозиторий, например, dmosk. Теперь можно загрузить наши образы в репозиторий.

Сначала авторизуемся в Linux под нашим зарегистрированным пользователем:

docker login —username dmosk

Задаем тег для одного из образов и загружаем его в репозиторий:

docker tag centos:my dmosk/dmosk:centos

docker push dmosk/dmosk:centos

Загрузим второй образ:

docker tag dmosk/nginx:v1 dmosk/dmosk:nginx

docker push dmosk/dmosk:nginx

В Docker Hub должны появиться наш образы:

Чтобы воспользоваться образом на другом компьютере, также авторизуемся под зарегистрированным пользователем docker:

docker login —username dmosk

docker pull dmosk/dmosk:nginx

docker run -d -p 8080:80 dmosk/dmosk:nginx

Описание инструкций Dockerfile

Инструкция Описание Пример
FROM Указывает, какой базовый образ нужно использовать. Обязательная инструкция для Dockerfile FROM ubuntu:16.04
MAINTAINER Автор образа. MAINTAINER DMosk
RUN Выполняет команду в новом слое при построении образа. RUN apt-get install python
CMD Запускает команду каждый раз при запуске контейнера. Может быть вызвана только один раз. Если в Dockerfile указать несколько таких инструкций, то выполнена будет последняя. CMD [«openvpn»]
LABEL Добавляет метаданные. LABEL version=»2″
EXPOSE Указывает, какой порт должно использовать приложение внутри контейнера. EXPOSE 8080
ENV Задает переменные окружения в образе. ENV PGPASSWORD pass
ADD Добавляет файлы/папки из текущего окружения в образ. Если в качестве копируемого файла указать архив, то он будет добавлен в образ в распакованном виде. Также в качестве источника принимает URL. ADD /root/.ssh/ /root/.ssh/
COPY Также как и ADD добавляет файлы в образ, но обладает меньшими функциями — не принимает URL и не распаковывает архивы. Рекомендован для использования в случаях, где не требуются возможности ADD или когда нужно перенести архив, как архив. COPY ./mypasswd /root/
ENTRYPOINT Указывает команду, которой будет передаваться параметр при запуске контейнера. ENTRYPOINT [«/sbin/apache2»]
VOLUME Добавляет том в контейнер. VOLUME [«/opt/myapp»]
USER Задает пользователя, от которого будет запущен образ. USER user:group
WORKDIR Можно задать каталог, откуда будут запускаться команды ENTRYPOINT и CMD. WORKDIR /opt/apps
ARG Создает переменную, которую может использовать сборщик. ARG folder=/opt/apps
WORKDIR $folder
ONBUILD Действия, которые выполняются, если наш образ используется как базовый для другой сборки. ONBUILD ADD . /app/src
STOPSIGNAL Переопределяет сигнал SIGTERM для завершения контейнера. STOPSIGNAL SIGINT
HEALTHCHECK Команда, которая будет проверять работоспособность контейнера. HEALTHCHECK —interval=5m —timeout=3s CMD curl -f http://localhost/ || exit 1
SHELL Позволяет заменить стандартную оболочку для выполнения команд на пользовательскую. SHELL [«/bin/sh», «-c»]

Резервное копирование и восстановление контейнера

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

Создание резерва

И так, для создания резервной копии контейнера, смотрим их список:

. и для нужного выполняем команду:

docker save -o /backup/docker/container.tar

* в данном примере мы создаем архив контейнера в файл /backup/docker/container.tar.

Чтобы уменьшить размер, занимаемый созданным файлом, раархивиркем его командой:

* в итоге, мы получим файл container.tar.gz.

Восстановление

Сначала распаковываем архив:

После восстанавливаем контейнер:

docker load -i container.tar

Смотрим, что нужный нам контейнер появился:

Оцените статью