G4A99

    экструдер -- коренной житель планеты,
    имунный к инопланетной инвазии через заражение*
    и вынужденный теперь жить в окружении интрудеров.

    *) вирус (вакцина, зависит от точки зрения), 
       наподобие компьютерного, но передается от машины к человеку,
       заражая при этом мозг.

    пример дешевого синтетического плагиата,
    инспирированного картинкой "Доскер"-кораблика 
    в примере "docker run hello-world"

Начало работы с Docker для Windows
==================================

(на основе https://docs.docker.com)

Это начало работы для неопытных пользователей, которые заинтересованы в получении информации о Docker. Здесь вы изучите основные черты Docker, выполняя несколько простых задач. Вы узнаете, как:

  + установить программное обеспечение Docker с помощью Docker Toolbox
  + использовать Docker Engine для запуска образа программного обеспечения в контейнере
  + выбрать образ (browse for an image) на Docker Hub
  + создать свой собственный образ и запустить его в контейнере
  + создать учетную запись на Docker Hub и хранилище образов (image repository)
  + создать образ самостоятельно (create an image of your own)
  + добавить созданный вами образ в Docker Hub для использования другими

Установка Docker для Windows
============================

Используйте Docker Toolbox для установки программного обеспечения Docker. Docker Toolbox включает в себя следующие инструменты Docker:
  + CLI (command line interface) клиент Docker. Cлужит для запуска Docker Engine применяемого для создания изображений и контейнеров.
  + Docker машина -- чтобы можно было запускать команды Docker Engine из Windows терминала 
  + Docker Compose  для запуска команды docker-compose
  + Kitematic, Docker GUI
  + shell Docker QuickStart, предварительно настроенный для использования командной строки в среде Docker Oracle VM VirtualBox
  
Шаг 1. Убедитесь чтo 
  + установлена 64-битная OS Windows 7-10
      Control Panel -> System
      System Type: 64-bit Operating System, x64-based processor
      
  + включена аппаратная поддержка виртуализации
      Task Manager -> Performance
      Virtualization: Enabled

Шаг 2. Установить Docker Toolbox.

  + Скачать и установить Docker Toolbox (196MB, exe файл) на
      https://www.docker.com/toolbox
    (uncheck VirtualBox если он уже есть в системе, "takes some time" -- на 99% висит пару минут)
    В списке машин VirtualBox будет добавлена машина "default". У меня
      General
        Name: default
        Operating System: Linux 2.6/3.x/4.x (64-bit)
      System
        Base Memory: 1024 MB
      Storage:
        Sata Port 0: [Optical Drive] boot2docker.iso (32.00 MB)
        Sata Port 1: disk.vmdk (Normal, 19.53 GB)
      Network:
        Adapter 1: Intel PRO/1000 MT Desktop (NAT)
        Adapter 2: Intel PRO/1000 MT Desktop (Host-only Adapter)
      Shared folders:
        Machine Folders
          Name     Path      Automount  Access
          c/Users  c:\Users  Yes        Full
          
Если при установке возникли проблемы:

  + install VirtualBox with the NDIS5 driver (NDIS6 default).
  + идите на https://docs.docker.com/faqs/troubleshoot/.
    
Шаг 3. Проверка работоспособности

  + Запустите икону Docker QuickStart на Рабочем столе. У меня напечаталось:
  
    Creating CA: C:\Users\kiril\.docker\machine\certs\ca.pem
    Creating client certificate: 
      C:\Users\kiril\.docker\machine\certs\cert.pem
    Running pre-create checks...
    Creating machine...
    (default) Copying 
      C:\Users\kiril\.docker\machine\cache\boot2docker.iso to
      C:\Users\kiril\.docker\machine\machines\default\boot2docker.iso...
    (default) Creating VirtualBox VM...
    (default) Creating SSH key...
    (default) Starting the VM...
    (default) Check network to re-create if needed...
    (default) Windows might ask for the permission to create a network 
    adapter. Sometimes, such confirmation window is minimized in the 
    taskbar.
    (default) Creating a new host-only adapter produced an error: 
      C:\Program Files\Oracle\VirtualBox\VBoxManage.exe hostonlyif create failed:
    (default) 0%...
    (default) Progress state: E_INVALIDARG
    (default) VBoxManage.exe: error: Failed to create the host-only adapter
    (default) VBoxManage.exe: error: Assertion failed: [!aInterfaceName.isEmpty()] at
    'F:\tinderbox\win-5.0\src\VBox\Main\src-server\HostNetworkInterfaceImpl.cpp' (74) 
    in long __cdecl HostNetworkInterface::init(
        class com::Bstr,
        class com::Bstr,
        class com::Guid,
        enum __MIDL___MIDL_itf_VirtualBox_0000_0000_0036
    ).
    (default) VBoxManage.exe: error: Please contact the product vendor!
    (default) VBoxManage.exe: error: Details: 
      code E_FAIL (0x80004005), 
      component HostNetworkInterfaceWrap, 
      interface IHostNetworkInterface
    (default) VBoxManage.exe: error: Context: 
      "enum RTEXITCODE __cdecl handleCreate(struct HandlerArg *)" 
    at line 71 of file VBoxManageHostonly.cpp
    (default)
    (default) This is a known VirtualBox bug. Let's try to recover anyway...
    (default) Found a new host-only adapter: "VirtualBox Host-Only Ethernet Adapter"
    (default) Windows might ask for the permission to configure a network adapter. 
    Sometimes, such confirmation window is minimized in the taskbar.
    (default) Windows might ask for the permission to configure a dhcp server. 
    Sometimes, such confirmation window is minimized in the taskbar.
    (default) Waiting for an IP...
    Waiting for machine to be running, this may take a few minutes...
    Detecting operating system of created instance...
    Waiting for SSH to be available...
    Detecting the provisioner...
    Provisioning with boot2docker...
    Copying certs to the local machine directory...
    Copying certs to the remote machine...
    Setting Docker configuration on the remote daemon...
    Checking connection to Docker...
    Docker is up and running!
    To see how to connect your Docker Client to the Docker Engine running 
    on this virtual machine, run: 
      C:\Program Files\Docker Toolbox\docker-machine.exe env default

                            ##         .
                      ## ## ##        ==
                   ## ## ## ## ##    ===
               /"""""""""""""""""\___/ ===
          ~~~ {~~ ~~~~ ~~~ ~~~~ ~~~ ~ /  ===- ~~~
               \______ o           __/
                 \    \         __/
                  \____\_______/

    docker is configured to use the default machine with IP 192.168.99.100
    For help getting started, check out the docs at https://docs.docker.com

    kirill@DESKTOP-F3897JJ MINGW64 ~

  + выполните
  
      $ docker run hello-world
      
    у меня напечаталось:
    
    Unable to find image 'hello-world:latest' locally
    latest: Pulling from library/hello-world

    03f4658f8b78: Pull complete
    a3ed95caeb02: Pull complete
    Digest: sha256:8be990ef2aeb16dbcb9271ddfe2610fa6658d13f6dfb8bc72074cc1ca36966a7
    Status: Downloaded newer image for hello-world:latest

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

    To generate this message, Docker took the following steps:
     1. The Docker client contacted the Docker daemon.
     2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
     3. The Docker daemon created a new container from that image which runs the
        executable that produces the output you are currently reading.
     4. The Docker daemon streamed that output to the Docker client, which sent it
        to your terminal.

    To try something more ambitious, you can run an Ubuntu container with:

      $ docker run -it ubuntu bash

    Share images, automate workflows, and more with a free Docker Hub account:

      https://hub.docker.com

    For more examples and ideas, visit:

      https://docs.docker.com/userguide/

  + попробуйте предложенный амбициозный пример. у меня напечаталось:

    $ docker run -it ubuntu bash
    Unable to find image 'ubuntu:latest' locally
    latest: Pulling from library/ubuntu
    87192bdbe00f: Pull complete
    28e09fddaacb: Pull complete
    7e15ce58ccb2: Pull complete
    a3ed95caeb02: Pull complete
    Digest: sha256:f6e8757419147ba099af8cec4db365b3603472bd6182722b16fdae932c0bf3bf
    Status: Downloaded newer image for ubuntu:latest
    root@fca8d5cd8ae2:/# echo $SHELL
    /bin/bash
    root@fca8d5cd8ae2:/# uname -a
    Linux fca8d5cd8ae2 4.1.19-boot2docker #1 SMP Mon Mar 7 17:44:33 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux
    root@fca8d5cd8ae2:/# cat /etc/issue
    Ubuntu 14.04.4 LTS \n \l
    root@fca8d5cd8ae2:/# free
                 total     used      free   shared   buffers   cached
    Mem:       1019988   456800    563188   132616     12116   341676
    -/+ buffers/cache:   103008    916980
    Swap:      1202252        0   1202252
    root@fca8d5cd8ae2:/# df
    Filesystem     1K-blocks   Used Available Use% Mounted on
    none            19049892 259736  17799432   2% /
    tmpfs             509992      0    509992   0% /dev
    tmpfs             509992      0    509992   0% /sys/fs/cgroup
    /dev/sda1       19049892 259736  17799432   2% /etc/hosts
    shm                65536      0     65536   0% /dev/shm
    root@fca8d5cd8ae2:/# fdisk -l
    root@fca8d5cd8ae2:/# whoami
    root

Чтобы все выключить

  $ docker stop $(docker ps -a -q)
  $ docker-machine stop default
  
Иногда хочется уничтожить все контейнеры

  $ docker rm $(docker ps -a -q)
  
Изучаем образы и контейнеры Docker
==================================

Команда docker run hello-world имеет три составляющие

  + docker      -- Использовать Docker
  + run         -- Создать и выполнить контейнер Docker
  + hello-world -- Образ, который следует загрузить в Docker
  
Контейнер -- усеченная версия Linux (stripped-to-basics). 
Образ     -- программа, которая загружается в контейнер. 

При выполнении команды:

  + проверяется, существует ли локальная копия образа hello-world
  + осуществляется загрузка образа из Docker Hub (подробнее о Hub позже)
  + загрузка образа в контейнер и запуск контейнера.

В зависимости от того, как он был построен, образ может запустить простой, одну простую команду, а затем выйти. Это то, что сделано в hello-world.
С другой стороны образ может включать сложную СУБД c данными.

Docker Engine позволяет людям создавать и совместно использовать программное обеспечение через образы Docker'а.

Поиск и запуск whalesay образа
==============================

  + Откройте браузер и перейдите к Docker Hub.
      https://hub.docker.com/
  + Browse или Search: whalesay
  + Выбрать:           docker/whalesay
  + Запустить:         
    docker run docker/whalesay cowsay boo
    ..
    docker images
    $ docker images
    REPOSITORY       TAG     IMAGE ID      CREATED        SIZE
    ubuntu           latest  b549a9959a66  3 days ago     188 MB
    hello-world      latest  690ed74de00f  5 months ago   960 B
    docker/whalesay  latest  6b362a9f73eb  10 months ago  247 MB

Создание образа
===============

В командном окне Docker Quickstart:

  kirill@DESKTOP-F3897JJ MINGW64 ~
  $ mkdir mydockerbuild

  kirill@DESKTOP-F3897JJ MINGW64 ~
  $ cd mydockerbuild

  kirill@DESKTOP-F3897JJ MINGW64 ~/mydockerbuild
  $ touch Dockerfile

  kirill@DESKTOP-F3897JJ MINGW64 ~/mydockerbuild
  $ ls Dockerfile
  Dockerfile

  kirill@DESKTOP-F3897JJ MINGW64 ~/mydockerbuild
  $ vi Dockerfile

  kirill@DESKTOP-F3897JJ MINGW64 ~/mydockerbuild
  $ cat Dockerfile
  FROM docker/whalesay:latest
  RUN apt-get -y update && apt-get install -y fortunes
  CMD /usr/games/fortune -a | cowsay

  kirill@DESKTOP-F3897JJ MINGW64 ~/mydockerbuild
  $ docker build -t docker-whale .
  Sending build context to Docker daemon 2.048 kB
  Step 1 : FROM docker/whalesay:latest
   ---> 6b362a9f73eb
  Step 2 : RUN apt-get -y update && apt-get install -y fortunes
   ---> Running in 973ced6101fa
  Ign http://archive.ubuntu.com trusty InRelease
  Get:1 http://archive.ubuntu.com trusty-updates InRelease [65.9 kB]
  Get:2 http://archive.ubuntu.com trusty-security InRelease [65.9 kB]
  Hit http://archive.ubuntu.com trusty Release.gpg
  Hit http://archive.ubuntu.com trusty Release
  Get:3 http://archive.ubuntu.com trusty-updates/main Sources [340 kB]
  Get:4 http://archive.ubuntu.com trusty-updates/restricted Sources [5217 B]
  Get:5 http://archive.ubuntu.com trusty-updates/universe Sources [192 kB]
  Get:6 http://archive.ubuntu.com trusty-updates/main amd64 Packages [942 kB]
  Get:7 http://archive.ubuntu.com trusty-updates/restricted amd64 Packages [23.5 kB]
  Get:8 http://archive.ubuntu.com trusty-updates/universe amd64 Packages [462 kB]
  Get:9 http://archive.ubuntu.com trusty-security/main Sources [139 kB]
  Get:10 http://archive.ubuntu.com trusty-security/restricted Sources [3920 B]
  Get:11 http://archive.ubuntu.com trusty-security/universe Sources [40.5 kB]
  Get:12 http://archive.ubuntu.com trusty-security/main amd64 Packages [564 kB]
  Get:13 http://archive.ubuntu.com trusty-security/restricted amd64 Packages [20.2 kB]
  Get:14 http://archive.ubuntu.com trusty-security/universe amd64 Packages [164 kB]
  Hit http://archive.ubuntu.com trusty/main Sources
  Hit http://archive.ubuntu.com trusty/restricted Sources
  Hit http://archive.ubuntu.com trusty/universe Sources
  Hit http://archive.ubuntu.com trusty/main amd64 Packages
  Hit http://archive.ubuntu.com trusty/restricted amd64 Packages
  Hit http://archive.ubuntu.com trusty/universe amd64 Packages
  Fetched 3028 kB in 19s (156 kB/s)
  Reading package lists...
  Reading package lists...
  Building dependency tree...
  Reading state information...
  The following extra packages will be installed:
    fortune-mod fortunes-min librecode0
  Suggested packages:
    x11-utils bsdmainutils
  The following NEW packages will be installed:
    fortune-mod fortunes fortunes-min librecode0
  0 upgraded, 4 newly installed, 0 to remove and 80 not upgraded.
  Need to get 1961 kB of archives.
  After this operation, 4817 kB of additional disk space will be used.
  Get:1 http://archive.ubuntu.com/ubuntu/ trusty/main librecode0 amd64 3.6-21 [771 kB]
  Get:2 http://archive.ubuntu.com/ubuntu/ trusty/universe fortune-mod amd64 1:1.99.1-7 [39.5 kB]
  Get:3 http://archive.ubuntu.com/ubuntu/ trusty/universe fortunes-min all 1:1.99.1-7 [61.8 kB]
  Get:4 http://archive.ubuntu.com/ubuntu/ trusty/universe fortunes all 1:1.99.1-7 [1089 kB]
  debconf: unable to initialize frontend: Dialog
  debconf: (TERM is not set, so the dialog frontend is not usable.)
  debconf: falling back to frontend: Readline
  debconf: unable to initialize frontend: Readline
  debconf: (This frontend requires a controlling tty.)
  debconf: falling back to frontend: Teletype
  dpkg-preconfigure: unable to re-open stdin:
  Fetched 1961 kB in 4s (451 kB/s)
  Selecting previously unselected package librecode0:amd64.
  (Reading database ... 13116 files and directories currently installed.)
  Preparing to unpack .../librecode0_3.6-21_amd64.deb ...
  Unpacking librecode0:amd64 (3.6-21) ...
  Selecting previously unselected package fortune-mod.
  Preparing to unpack .../fortune-mod_1%3a1.99.1-7_amd64.deb ...
  Unpacking fortune-mod (1:1.99.1-7) ...
  Selecting previously unselected package fortunes-min.
  Preparing to unpack .../fortunes-min_1%3a1.99.1-7_all.deb ...
  Unpacking fortunes-min (1:1.99.1-7) ...
  Selecting previously unselected package fortunes.
  Preparing to unpack .../fortunes_1%3a1.99.1-7_all.deb ...
  Unpacking fortunes (1:1.99.1-7) ...
  Setting up librecode0:amd64 (3.6-21) ...
  Setting up fortune-mod (1:1.99.1-7) ...
  Setting up fortunes-min (1:1.99.1-7) ...
  Setting up fortunes (1:1.99.1-7) ...
  Processing triggers for libc-bin (2.19-0ubuntu6.6) ...
   ---> 1f07f64fe871
  Removing intermediate container 973ced6101fa
  Step 3 : CMD /usr/games/fortune -a | cowsay
   ---> Running in 7f7f5a43d1a5
   ---> 3f77d5faacfa
  Removing intermediate container 7f7f5a43d1a5
  Successfully built 3f77d5faacfa
  SECURITY WARNING: You are building a Docker image from Windows against a non-Windows 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.

  kirill@DESKTOP-F3897JJ MINGW64 ~/mydockerbuild
  $ docker images
  REPOSITORY       TAG      IMAGE ID       CREATED          SIZE
  docker-whale     latest   3f77d5faacfa   15 seconds ago   274.5 MB
  ubuntu           latest   b549a9959a66   3 days ago       188 MB
  hello-world      latest   690ed74de00f   5 months ago     960 B
  docker/whalesay  latest   6b362a9f73eb   10 months ago    247 MB

  kirill@DESKTOP-F3897JJ MINGW64 ~/mydockerbuild
  $ docker run docker-whale
   _________________________________________
  / Need                                    \
  |                                         |
  | Is the action of nature not unlike      |
  | drawing a bow? What is higher is pulled |
  | down, and what is lower is raised up;   |
  | What is taller is shortened, and what   |
  | is thinner is broadened; Nature's       |
  | motion decreases those who have more    |
  | than they need And increases those who  |
  | need more than they have. It is not so  |
  | with Man. Man decreases those who need  |
  | more than they have And increases those |
  | who have more than they need. To give   |
  | away what you do not need is to follow  |
  | the Way. So the sage gives without      |
  | expectation, Accomplishes without       |
  | claiming credit, And has no desire for  |
  | ostentation.                            |
  |                                         |
  \ -- Lao Tse, "Tao Te Ching"              /
   -----------------------------------------
      \
       \
        \
                      ##        .
                ## ## ##       ==
             ## ## ## ##      ===
         /""""""""""""""""___/ ===
    ~~~ {~~ ~~~~ ~~~ ~~~~ ~~ ~ /  ===- ~~~
         \______ o          __/
          \    \        __/
            \____\______/

  kirill@DESKTOP-F3897JJ MINGW64 ~/mydockerbuild
  $

Вопросы (so far)
----------------

1. Где все лежит?

  C:\Users\kiril\.docker\machine\machines\default\disk.vmdk
  
2. whalesay:
      https://hub.docker.com/r/docker/whalesay/
      почему он такой большой???
      потому что это чертов кит!
    Если серьезно, то
      https://www.reddit.com/r/docker/comments/3keefr/why_is_whalesay_so_big/
      
3. Try running the whalesay image again with a word or phrase. 
   Try a long or short phrase. Can you break the cow?
      docker run docker/whalesay cowsay boo-boo

Читать
======

1. https://www.ibm.com/developerworks/community/blogs/jfp/entry
         /Using_Docker_Machine_On_Windows?lang=en

2. https://serversforhackers.com/getting-started-with-docker

3. https://developer.codero.com/community
         /easily-stop-and-remove-multiple-docker-containers/