Docker для windows server 2012

My environment: Windows Server 2012 R2. Slightly different steps may be required with other
versions of Windows.

Pretty straightforward, the only tricky parts here are about Hyper-V and finding out the IP
address of the VM.

With regards to the latter there is a lot of misleading information on the web.

1. Make sure Hyper-V is not running.

If it does, it will prevernt the VirtualBox VM to start and you will get mysterious errors.
Same goes if you use VMWare or any other hypervisor other than VirtualBox.

If you do need to have both Hyper-V and VirtualBox, Scott Hanselman wrote about some voodoo magic
you can do to easily switch between the two. I haven’t tried it.

2. Download and install Docker for Windows.

  • Download and install Boot2Docker from here: https://github.com/boot2docker/windows-installer/releases/latest

  • Install everthing

  • Tick “yes I trust that thing” when asked to install network driver. It’s required by VirtualBox.

  • You should have two icons added to the desktop:

    • Boot2Docker Start
    • Oracle VM VirtualBox

3. Run Boot2Docker

If everything goes well, you should see:

  • bash command window should open
  • after a bit, it should have ouput similar to the one shown below
  • take note of the line which says DOCKER-HOST, it should have the IP address of the docker VM.
  • if you open Virtual Box, you should see boot2docker-vm running there.

    Bash window

    Running docker vm

4. Post Install

A couple of useful things to know:

  • You can run as many instances of Boot2Docker as you want. It’s just a command prompt.

  • Finding out the IP address of the docker VM (and things which run within it). Several options:

    • from Boot2Docker command prompt run boot2docker.exe ip. This will show the IP address:

        $ boot2docker.exe ip
        192.168.59.103
      

    • Look for DOCKER-HOST string when you start Boot2Docker:

        ...
        starting...
        Waiting for VM and Docker daemon to start...
        .o
        Started.
        ...
      		
        To connect the Docker client to the Docker daemon, please set:
            export DOCKER_HOST=tcp://192.168.59.103:2376
      

  • Security and the images. One thing worth remembering is that when you say something like
    docker run some-image by default it will try and some-image from external repository.
    Which repository it is, and who built that image with what is a good question. So probably a
    good idea to install only “trusted” images.

Здравствуйте, уважаемые читатели хабра. Сегодня мы поговорим о Windocks–продукте компании с одноименным названием, позиционирующем себя как первый движок докер для Windows. Пока клиенты майкрософт ожидают новую версию Windows Server, а именно Windows Server 2016 (на момент написания статьи доступна версия Technical Preview 5) с нативной поддержкой докер-контейнеров, создатели windocks попытались предоставить докер-контейнеры для текущего поколения серверных систем windows.

Итак, что же такое Windocks? Если коротко — это смесь портированной версии существующего демона докер и open source container project от Uhuru Software. Об особенностях Windocks и вызовах, которые стояли перед разработчиками, можно почитать тут.

В рамках данного материала мы попробуем разобраться, чем работа с windocks принципиально отличается от работы с оригинальным демоном для linux, какие у текущей версии windocks ограничения и стоит ли внедрять инструмент в свои процессы разработки и тестирования.

Что доступно сейчас

На момент написания статьи windocks поддерживает следующие ОС:

  • Windows 8/8.1
  • Windows 10
  • Windows Server 2012 / Windows Server 2012 R2
  • Windows Server 2016

В этих ОС можно создавать контейнеры из образов:

  • SQL Server 2016/2014/2012/2008 R2/2008
  • Net 4.5/3.5/2.0
  • Jenkins (агенты, демо по запросу)
  • Office conversion (для конвертации презентаций powerpoint в видео, демо по запросу)
  • Microsoft Dynamics (линейка ERP и CRM решений, демо по запросу)

Развертываем windocks на VPS с Windows Server 2012

Совсем недавно Windocks объявили о релизе community edition, для того чтобы можно было бесплатно ознакомиться с возможностями продукта. Эту версию мы и будем разворачивать. Отправляем запрос через форму на сайте. Ответ приходит мгновенно, и через минуту ссылка уже у нас.

В качестве окружения для развертывания windocks будем использовать VPS с конфигурацией 2×2.6ГГц, 2Гб RAM, 20Гб HDD / Windows Server 2012 R2. Для того, чтобы использовать SQL Server контейнеры на VPS необходимо установить SQL Server. Устанавливаем, а затем ставим и сам windocks. Никаких дополнительных настроек в процессе установки не требуется.

Сгенерируем сертификаты и ключи для хоста и для клиента, чтобы настроить двустороннюю аутентификацию и предоставим их windocks:

server-key.pem -> C:\Users\Administrator\.docker\key.pem
server-cert.pem -> C:\Users\Administrator\.docker\cert.pem
ca.pem -> C:\Users\Administrator\.docker\ca.pem

Теперь запустим windocks (команда запуска выглядит немного иначе, чем для демона докер на линукс):

docker -H tcp://WINDOCKS_IP:2376 -dD --tlsverify=true

В логах запуска видим:

time="2016-06-30T14:32:06.901345300+03:00" level=info msg="Daemon has completed initialization"

Не забываем разрешить входящие подключения на tcp порт 2376 в файрволе для нужных ip-адресов.

Подключаемся с помощью стандартного клиента докер

Как вы наверное догадались по заголовку, Windocks поддерживает docker RESTful api. Это означает, что для работы с ним можно использовать стандартного консольного клиента докер. Однако, windocks на данный момент поддерживает не все команды, а только их часть. В DockerFile также поддерживается ограниченный набор комманд (FROM, ADD, COPY, ADDDB, MOUNTDB). Полный список комманд для сравнения вы можете найти тут.

Подключаемся к windocks абсолютно также, как и к обычному докер хосту (для работы с клиентом рекомендуем создать алиасы команд, в windows это можно сделать, например, с помощью DOSKEY):

docker.exe --tlsverify --tlscacert=ca.pem --tlscert=cert.pem --tlskey=key.pem -H=WINDOCKS_IP:2376 version

В результате получаем что-то вроде:


Client version: 1.7.0
Client API version: 1.19
Go version (client): go1.4.2
Git commit (client): 0baf609
OS/Arch (client): windows/amd64
Server version: $VERSION
Server API version: 1.19
Go version (server): go1.5.1
Git commit (server): $GITCOMMIT
OS/Arch (server): windows/amd64

Запускаем .NET приложение в windocks

У windocks свой локальный реестр образов, который в community addition по умолчанию содержит 2 образа: dotnet и mssql. Его содержимое можно получить, выполнив (считаем, что мы уже сделали алиас с параметрами для аутентификации с помощью сертификатов):

docker images

Результат:

Итак, нам доступны 2 базовых образа: dotnet-4.5 и mssql-2014. Вместе с Windocks идёт набор сэмплов, демонстрирующих его возможности.

В рамках статьи мы рассмотрим сэмплы testMountDb и testDotnet. Первый монтирует в контейнер, созданный на основе образа mssql-2014, базу для тестового приложения. Второй — использует эту базу в работе в другом контейнере. Скопируем их на клиентскую ОС, чтобы осуществлять работу непосредственно с помощью стандартного клиента.

Соберем контейнер из сэмпла testMountDb и запустим его.

docker build testMountDb

Получаем следующее:


Sending build context to Docker daemon 2.048 kB
	Sending build context to Docker daemon
	Step 0 : FROM mssql-2014
	Step 1 : MOUNTDB customers C:\dcr\mountDbExample\customerdata.mdf
	ContainerId = c4d6e4f7bdc9cfc4c8b62b09572b255f43b56716d862b28e291e7af86e08bc3f & ContainerPort = 10001 & ContainerUserName = prison_oo_aqRdapH & ContainerPassword = Pr!5n5A39SvNRo & MSSQLPort = 10001 & MSSQLServerUserName = sa & MSSQLServer
	SaPassword = Pr!54q0flmqoM1 & DockerFile output:  & Line 2- Mounted DB: customers, C:\ dcr \mountDbExample\customerdata.mdf

Отсюда нам понадобятся MSSQLServerUserName и SaPassword, которые мы будем использовать в web.cfg в строке подключения.
Запустим созданный контейнер:

docker start c4d

Теперь соберем контейнер из сэмпла testDotnet и запустим (всё аналогично):

docker build testDotnet

Результат:


SECURITY WARNING: You are building a Docker image from Windows against a Linux Docker host. All files and directories added to build context will have '-rwxr-xr-x' permissions. It is recommended to double check and reset permissions for sensitive files and directories.
	Sending build context to Docker daemon 20.99 kB
	Sending build context to Docker daemon
	Step 0 : FROM dotnet-4.5
	Step 1 : COPY web.config app-root\\runtime\\repo
	Step 2 : COPY default.aspx app-root\\runtime\\repo
	Step 3 : COPY default.aspx.cs app-root\\runtime\\repo
	Step 4 : COPY main.css app-root\\runtime\\repo
	Step 5 : COPY windockslogo.png app-root\\runtime\\repo
	Step 6 : COPY testrun.bat .
	Step 7 : RUN cmd.exe /C .\testrun.bat
	ContainerId = 3b8cefeef04d3ac5010fa8e37b04ce42aa207359e4848581222d521839ea7a04 & ContainerPort = 10003 & ContainerUserName = prison_oo_P4yo5gA & ContainerPassword = Pr!5c6g8mVfQq7 & DOTNETPort = 10003 & DockerFile output: PS

	docker start 3b8

Открываем в браузере

http://WINDOCKS_IP:10003 

и, если все сделано правильно, видим следующее:

Теперь сохраним образ приложения в реестре windocks, выполнив следующее:

docker commit a29 windocks_dotnet_demo_v1

И выведем обновлённый список образов:

docker images

Теперь образ windocks_dotnet_demo_v1 могут использовать и другие пользователи

Выводы

На наш взгляд, несмотря на то, что windocks достаточно ограниченный (в чем его ограничения мы указали в самом начале статьи) инструмент в сравнении с демоном докер для линукс, он неплохо справляется со своими стандартными задачами по предоставлению SQL Server и .NET контейнеров. Также его можно вполне комфортно использовать для разработки и тестирования приложений на ASP.NET 4.5 / MSSQL в небольших командах, однако для использования в продакшене инструмент ещё слишком молод и ещё может стать неактуальным после релиза Windows Server 2016. А вы как считаете, уважаемые читатели?

Table of contents

        • 0. Environmental preparation
        • 1. Download the docker_toolbox tool
        • 1. 2 Install docker_toolbox
        • 1. 3 Use virtual machines
        • 1, 4 port mapping
        • 1. Directory mounting:

Drama diagram:
Latterdocker_toolboxTools are actually similar to VMware of Windows,docker_toolboxA Linux system is provided, which can be used in the DOCKER (using docker in the Linux environment in peace)

0. Environmental preparation

Docker needs your CPU to support virtualization on Window. Open the task manager, select performance to view:

1. Download the docker_toolbox tool

Note:(Windows Server 2012 version requires the tool support to run docker)

Attach an installation package: extraction code: VMXV[Click me to download]You can also download it by yourself.

1. 2 Install docker_toolbox

Double -click to run the downloaded docker_toolbox program for installation;
Select the installation path by yourself;
In the following interface, it is recommended to check, and the rest of the default will be the next step.

1. 3 Use virtual machines

Double -click the virtual machine management tool installed below, and after entering the default, there is a name calleddefaultVirtual machine, right -click to run;

The default information of the virtual machine is generally:
host:192.168.99.100
user:docker
password:tcuser

(1) You can use your own terminal window for operation (not supporting Chinese display, not recommended);
(2) You can also use your own XSHELL tools to connect (recommend

1, 4 port mapping

E.g:
If you need to map the port 8001 of the internal service of the Docker container, you need to set it in the Docker_toolbox tool to access it at your Windows Server Solit Owner Browser:

1. Directory mounting:

If you need to map the internal directory of Docker to the local area of ​​Windows Server. need:
1. First map the local directory of Windows to the Linux virtual machine

Log in to the virtual machine Linux, execute the following command to mount

# Switching root
sudo -i

#
sudo mount -t vboxsf d/dian_lian/program/logs /mnt/docker/logs

2. Then map the Docker’s internal directory to the directory of the virtual machine Linux.

# Put the mirror into a container (map the container directory to the virtual machine directory)
docker run --name=u8 --privileged=true -p 8001:8001 -v /mnt/docker/logs:/web/u8_data/logs -itd u8 /usr/sbin/init

This is a technical blog that covers some of the challenges we faced in porting the docker engine to Windows Server 2012.

After a year of heads -down development to port Docker’s open source project from Linux to Windows Server 2012, I finally have some time to describe some of the technical challenges we faced. But first, a quick introduction to containers.

Containers are described as the natural replacement for virtual machines, since they are smaller in footprint and faster than virtual machines. Technically, you can think of them as multiple copies of the same libraries (DLLs on Windows) running on the core operating system. Each container provides an isolated system to a user to run their services.

For us, the challenge was that the Windows Server 2012 kernel does not support the constructs needed for containers. Our product, Windocks, uses Windows Job objects as the basis for a container, so there are plenty of limitations. Our goal for WinDocks is to support the development and use of trusted software by an organization, on a dedicated VM or bare metal host. This goal appears to be shared by Microsoft and AWS, both who deliver container services with VMs for assured security.

Now to the challenges in porting the docker engine….

Docker is written in Go and the building of the docker engine requires docker itself ! Programmers will appreciate the infinite recursion irony here since on Windows, we had no Docker binaries to begin with! So, we did things the hard way using Go and C++ compilers on Windows.

The code that creates the containers (Job Objects and more) is in C# and our second challenge was the communication between the Go docker engine and the container code in C#. Luckily, this proved easy by using an intermediate layer written in C++. As you can see, our use of programming languages seemed to grow by the day. First, Golang, then C#, then C++!

Another challenge we faced was that the docker engine creates goroutines (threads) for each request. Our design had to be conservative enough to prevent thread related bugs but at the same time had to be aggressive enough to speed execution of parallel docker commands from multiple users. While it was tempting to put global locks on each docker command, we resisted the temptation! We have a locking design which uses container ids, the nature of the docker command and more to decide on the granularity of the lock. We tested our locking by slamming the Windocks server on a 4 core machine with 10+ docker requests simultaneously and found no issues (I hate to say no bugs — call me pessimistic!)

Perhaps our hardest challenges were around SQL Server where we implemented the ability to add database copies into the container or mount remote databases (with or without cloning). While, SQL Server was never really designed for mdf / ndf file manipulation, we have managed to make the adding of database files or mounting of remote database files work reliably in Windocks. We were able to create a SQL Server container with a clone of a 750 GB database in 45 seconds, see this video.

If our SQL Server challenges were hard, I think the value of this is paramount to Windocks, Microsoft and the devops community. I have a strong bias towards SQL Server and consider it one of the finest database servers around, particularly for its ability to do high performance bulk inserts and updates. With Windocks, Microsoft can open its doors to a much higher volume of SQL Server usage because of the ease of getting it started for multiple developers and testers.

It has been a fascinating technology challenge for us to port the docker engine to Windows Server and we are quite excited to be the first ones to market with a commercially available solution on Windows that supports many of the docker commands.

Running Docker locally on a Windows machine is generally not an issue; unless you’ve committed to using Hyper-V. Since the Docker install for Windows relies on Sun’s Oracle’s Virtual Box, you can’t have both running (Hyper-V and Virtual Box).

There are ways to disable Hyper-V for a boot session (via bcdedit for example – here). However, I’d just like to run in Hyper-V.

Thankfully, Chris Swan has a nice post on getting started, using the Boot2Docker ISO, and setting up the data disk (via a differencing disks) so you can just re-use this config in future Docker instances. You can also see some of the details on the boot2docker requirements for naming of the data disk, username and password for SSH, etc. here:

  • https://github.com/boot2docker/boot2docker
  • http://docs.docker.com/installation/windows/

Basic Steps

Download ISO – from github https://github.com/steeve/boot2docker/releases

Create the VM and just use the ISO for bootup – we’ll add the disk in a moment

We’ll create the VM as a Generation 1 – we need the legacy adapters etc. as the version of CoreOS used won’t recognize the other adapter types.

Simple Settings:

Memory Size: 1,204 MB

Network Connection: Choose an interface that has Internet access and DHCP assignable addresses for ease:

Next, postpone the setup of the Hard Disk as we’re going to setup a differencing disk and we’d like some control over the IDE adapter / Port to use.

Once you’re done with the ‘New Virtual Machine’ Wizard, hop into settings for the VM

Modify the DVD settings to point to the ISO image that you downloaded above:

Boot the VM for the First Time

All goes right, you should see in the VM console the ‘bootdocker’ loader information, and eventually the linux prompt

Start a SSH session with your VM (if desired)

To get the IP address of the VM, run ifconfig eth0 to see the default adapter. You should get an address that is hopefully on the Network interface/LAN that you chose. This has to be accessible from your host OS if you want to use SSH – in fact, it also needs access to the internet in order to get to the Docker HUB for downloading images.

I use «github» Windows tools (which in turn sets up the ‘poshgit’ tools, etc.) so I can just run a SSH session from PowerShell. https://windows.github.com/

Initiate the connection normally with SSH

ssh docker@<IP.address>

Note that the default username / password is : docker / tcuser — see the section on SSH at https://github.com/boot2docker/boot2docker for more information.

Setup the Virtual Disk

Shutdown the VM.

The next step is following what Chris Swan did in his post – which is to setup the VHD – run through the initialization, then make a differencing disk based off of that VHD, then swap out the configuration settings on the VM to use the Differencing disk instead of the base.

Boot the VM again

Once it’s started, choose SSH or the console to perform the disk preparation

Partition the drive

The steps below are slightly different than Chris’ post – but are:

  1. Dump out the partition table just to be sure

    1. cat /proc/partions (if you chose IDE 0 / PORT 0 then it should be /dev/sda)
  2. run fdisk

    1. sudo fdisk /dev/sda
  3. Choose ‘extended’
  4. Select partition ‘1’
  5. Choose the defaults for the first and last cylinder
  6. Once that is done, commit with the ‘w’ command

Setup the file system

The naming convention of the disk is also specified on the boot2docker github page – but it has to be ‘boot2docker-data’

Next, format the drive with:

sudo mkfs.ext4 -L boot2docker-data /dev/sda

Note that you will be warned about formatting the entire device, and not a partition. For now, I just went with the above.

Create the Differencing Disk

Shut down the VM again

Go back into the Virtual Machine Wizard. Select the settings for the VM, then go to the Disk settings and create a «New Virtual Disk».

Make sure when prompted, you choose the «base» image you created before, but when you’re done, your «Differencing» disk should be what’s listed in the Hard Disk path for the Controller/Location as below.

Boot the VM – 3rd time

I think it’s the 3rd time – don’t remember at this point…

Now we’re ready to «run» something. We’ll use the same image that Chris posted about, just because it’s a cool tool (Node-RED — http://nodered.org/)

Access the image either through the console or via SSH

Do a ‘docker run’ specifying to download the image if needed (-d) as it’s won’t be in the image local library.

docker run –d –p 1880:1880 cpswan/node-red

If all is working, then you should see the image and all it’s dependencies downloading – with the container – and at the end, docker launches the process.

Checkout if the Differencing disk is working

The «before» size

The «after» size – note the increase of the Differencing disl.

Launch the Application

Note that the port mapping is using the same port 1880 (Nat’d).

You should get the ‘Node-Red’ home page, which is the designer surface.

I quickly imported a simple «hello world» from the flows http://flows.nodered.org/flow/8069baf59dcb258bb2bd

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Artcam windows 7 32 bit
  • Нет виртуального порта usb для принтера windows 10
  • Звук стал очень тихим на компьютере что делать windows 10
  • Как посмотреть uuid windows
  • Rsat windows 10 что это