Archive for November, 2016

Create empty file called template.json and paste the following code:

{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"adminUsername": {
"type": "string",
"metadata": {
"description": "Username for the Virtual Machine."
}
},
"adminPassword": {
"type": "securestring",
"metadata": {
"description": "Password for the Virtual Machine."
}
},
"dnsLabelPrefix": {
"type": "string",
"metadata": {
"description": "Unique DNS Name for the Public IP used to access the Virtual Machine."
}
},
"windowsOSVersion": {
"type": "string",
"defaultValue": "2016-Datacenter",
"allowedValues": [
"2008-R2-SP1",
"2012-Datacenter",
"2012-R2-Datacenter",
"2016-Nano-Server",
"2016-Datacenter-with-Containers",
"2016-Datacenter"
],
"metadata": {
"description": "The Windows version for the VM. This will pick a fully patched image of this given Windows version."
}
}
},
"variables": {
"storageAccountName": "mystorageaccount112016",
"nicName": "myVMNic",
"addressPrefix": "10.0.0.0/16",
"subnetName": "Subnet",
"subnetPrefix": "10.0.0.0/24",
"publicIPAddressName": "myPublicIP",
"vmName": "MyAzureVM",
"virtualNetworkName": "MyVNET",
"subnetRef": "[resourceId('Microsoft.Network/virtualNetworks/subnets', variables('virtualNetworkName'), variables('subnetName'))]"
},
"resources": [
{
"type": "Microsoft.Storage/storageAccounts",
"name": "[variables('storageAccountName')]",
"apiVersion": "2016-01-01",
"location": "[resourceGroup().location]",
"sku": {
"name": "Standard_LRS"
},
"kind": "Storage",
"properties": {}
},
{
"apiVersion": "2016-03-30",
"type": "Microsoft.Network/publicIPAddresses",
"name": "[variables('publicIPAddressName')]",
"location": "[resourceGroup().location]",
"properties": {
"publicIPAllocationMethod": "Dynamic",
"dnsSettings": {
"domainNameLabel": "[parameters('dnsLabelPrefix')]"
}
}
},
{
"apiVersion": "2016-03-30",
"type": "Microsoft.Network/virtualNetworks",
"name": "[variables('virtualNetworkName')]",
"location": "[resourceGroup().location]",
"properties": {
"addressSpace": {
"addressPrefixes": [
"[variables('addressPrefix')]"
]
},
"subnets": [
{
"name": "[variables('subnetName')]",
"properties": {
"addressPrefix": "[variables('subnetPrefix')]"
}
}
]
}
},
{
"apiVersion": "2016-03-30",
"type": "Microsoft.Network/networkInterfaces",
"name": "[variables('nicName')]",
"location": "[resourceGroup().location]",
"dependsOn": [
"[resourceId('Microsoft.Network/publicIPAddresses/', variables('publicIPAddressName'))]",
"[resourceId('Microsoft.Network/virtualNetworks/', variables('virtualNetworkName'))]"
],
"properties": {
"ipConfigurations": [
{
"name": "ipconfig1",
"properties": {
"privateIPAllocationMethod": "Static",
"privateIPAddress": "10.0.0.5",
"publicIPAddress": {
"id": "[resourceId('Microsoft.Network/publicIPAddresses',variables('publicIPAddressName'))]"
},
"subnet": {
"id": "[variables('subnetRef')]"
}
}
}
]
}
},
{
"apiVersion": "2015-06-15",
"type": "Microsoft.Compute/virtualMachines",
"name": "[variables('vmName')]",
"location": "[resourceGroup().location]",
"dependsOn": [
"[resourceId('Microsoft.Storage/storageAccounts/', variables('storageAccountName'))]",
"[resourceId('Microsoft.Network/networkInterfaces/', variables('nicName'))]"
],
"properties": {
"hardwareProfile": {
"vmSize": "Standard_D1"
},
"osProfile": {
"computerName": "[variables('vmName')]",
"adminUsername": "[parameters('adminUsername')]",
"adminPassword": "[parameters('adminPassword')]"
},
"storageProfile": {
"imageReference": {
"publisher": "MicrosoftWindowsServer",
"offer": "WindowsServer",
"sku": "[parameters('windowsOSVersion')]",
"version": "latest"
},
"osDisk": {
"name": "osdisk",
"vhd": {
"uri": "[concat(reference(resourceId('Microsoft.Storage/storageAccounts/', variables('storageAccountName'))).primaryEndpoints.blob, 'vhds/osdisk.vhd')]"
},
"caching": "ReadWrite",
"createOption": "FromImage"
},
"dataDisks": [
{
"name": "datadisk1",
"diskSizeGB": "100",
"lun": 0,
"vhd": {
"uri": "[concat(reference(resourceId('Microsoft.Storage/storageAccounts/', variables('storageAccountName'))).primaryEndpoints.blob, 'vhds/datadisk1.vhd')]"
},
"createOption": "Empty"
}
]
},
"networkProfile": {
"networkInterfaces": [
{
"id": "[resourceId('Microsoft.Network/networkInterfaces',variables('nicName'))]"
}
]
},
"diagnosticsProfile": {
"bootDiagnostics": {
"enabled": "true",
"storageUri": "[reference(resourceId('Microsoft.Storage/storageAccounts/', variables('storageAccountName'))).primaryEndpoints.blob]"
}
}
}
}
],
}

After declaring schema,In Parameters section we define parameters:username/password,public DNS name

"parameters": {
"adminUsername": {
"type": "string",
"metadata": {
"description": "Username for the Virtual Machine."
}
},
"adminPassword": {
"type": "securestring",
"metadata": {
"description": "Password for the Virtual Machine."
}
},
"dnsLabelPrefix": {
"type": "string",
"metadata": {
"description": "Unique DNS Name for the Public IP used to access the Virtual Machine."
}

Then we specified OS version:

"windowsOSVersion": {
"type": "string",
"defaultValue": "2016-Datacenter",
"allowedValues": [
"2008-R2-SP1",
"2012-Datacenter",
"2012-R2-Datacenter",
"2016-Nano-Server",
"2016-Datacenter-with-Containers",
"2016-Datacenter"
],
"metadata": {
"description": "The Windows version for the VM. This will pick a fully patched image of this given Windows version."
}
}

In next section we specify StorageAccountName,VM NIC,subnet,public IP,VM name and Virtual Network name

"variables": {
"storageAccountName": "mystorageaccount112016",
"nicName": "myVMNic",
"addressPrefix": "10.0.0.0/16",
"subnetName": "Subnet",
"subnetPrefix": "10.0.0.0/24",
"publicIPAddressName": "myPublicIP",
"vmName": "MyAzureVM",
"virtualNetworkName": "MyVNET",
"subnetRef": "[resourceId('Microsoft.Network/virtualNetworks/subnets', variables('virtualNetworkName'), variables('subnetName'))]"
},

Then Storage Account Type:

"sku": {
"name": "Standard_LRS"
},

Optionally,we can set internal IP:

"properties": {
"ipConfigurations": [
{
"name": "ipconfig1",
"properties": {
"privateIPAllocationMethod": "Static",
"privateIPAddress": "10.0.0.5",
"publicIPAddress": {
"id": "[resourceId('Microsoft.Network/publicIPAddresses',variables('publicIPAddressName'))]"
},
"subnet": {
"id": "[variables('subnetRef')]"
}
}
}
]
}

VM disk configuration:

"dataDisks": [
{
"name": "datadisk1",
"diskSizeGB": "100",
"lun": 0,
"vhd": {
"uri": "[concat(reference(resourceId('Microsoft.Storage/storageAccounts/', variables('storageAccountName'))).primaryEndpoints.blob, 'vhds/datadisk1.vhd')]"
},
"createOption": "Empty"
}
]

Now create second empty file,param.json and paste code below:

{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json",
"contentVersion": "1.0.0.0",
"parameters": {
"adminUserName": { "value": "batman" },
"adminPassword": { "value": "Password1234" },
"dnsLabelPrefix": { "value": "server-201601"}
}
}

Here we specified admin username/password and public DNS name

Create Resource Group where new VM will be stored:

New-AzureRmResourceGroup -Name rg -Location 'west europe'

Deploy VM:

New-AzureRmResourceGroupDeployment -ResourceGroupName 'rg' -TemplateFile 'c:\template.json' -TemplateParameterFile 'c:\param.json'

 

1

 

capture

 

Advertisements

I wanted to install Windows Server 2016,but in that case,VM has no Public IP and NIC is not associated to any security group (Connect option grayed out),but all works as expected with Windows Server 2012 R2 !!???,is it bug or something else,i don’t know

For creating VM we need Azure Power Shell (see this blog for reference).First step is to create Resource Group.Resource Group can be seen as container for storing Azure resources (Virtual machines,Networks,Subnets,Storage accounts..).

This is resource group content i created in one of my previous posts

Untitled.png

New-AzureRmResourceGroup -Name "My_Resource_Group" -Location "West Europe"

We also need Azure Storage Account.With this account we have access to Azure Storage services such as Tables, Queues, Files, Blobs and Azure virtual machine disks

Binary Large Object (BLOB) collection of bytes that can be used
to store anything (up to 200 TB)

Tables are used to store large amounts of data for massive scale where some basic structure is required, but relationships between data don’t need to be maintained.

Queues provide reliable and persistent messaging between applications
within Azure

Files  provide an easy method to share storage within an Azure region

When creating a storage account, we can select one of the following replication options:

Locally redundant storage (LRS) replicates your data three times within a storage scale unit which is hosted in a datacenter in the region in which you created your storage account. A write request returns successfully only once it has been written to all three replicas. These three replicas each reside in separate fault domains and upgrade domains within one storage scale unit.

Zone-redundant storage (ZRS) replicates your data asynchronously across datacenters within one or two regions in addition to storing three replicas similar to LRS, thus providing higher durability than LRS. Data stored in ZRS is durable even if the primary datacenter is unavailable or unrecoverable

Geo-redundant storage (GRS) replicates your data to a secondary region that is hundreds of miles away from the primary region. If your storage account has GRS enabled, then your data is durable even in the case of a complete regional outage or a disaster in which the primary region is not recoverable.

Read-access geo-redundant storage (RA-GRS) maximizes availability for your storage account, by providing read-only access to the data in the secondary location, in addition to the replication across two regions provided by GRS.

New-AzureRmStorageAccount -ResourceGroupName My_Resource_Group -Name myresourceaccount11201 -SkuName "Standard_LRS" -Kind "Storage" -Location 'west europe'

Creating Virtual Network:

Create subnet first:

$mySubnet = New-AzureRmVirtualNetworkSubnetConfig -Name "mySubnet" -AddressPrefix 192.168.2.0/24

Create Virtual Network and add subnet to it:

$myVnet = New-AzureRmVirtualNetwork -Name "myVnet" -ResourceGroupName My_Resource_Group -Location 'west europe' -AddressPrefix 192.168.2.0/24 -Subnet $mySubnet

We can also specify custom DNS server adding -DNSServer ‘ip address’ switch

Check IP Address Availability

We can check if address we want to assign to VM is in use:

Get-AzureRmVirtualNetwork -Name myvnet -ResourceGroupName My_Resource_Group | Test-AzureRmPrivateIPAddressAvailability -IPAddress "192.168.2.1"

1

Creating NIC and assigning IP address:

$myNIC = New-AzureRmNetworkInterface -Name "dc-01" -ResourceGroupName My_Resource_Group -Location 'west europe' -SubnetId $myVnet.Subnets[0].Id -PublicIpAddressId $myPublicIp.Id -PrivateIpAddress 192.168.2.4

Creating Public IP

In order for VM to comunicate with virtual network we need public IP (AllocationMethod can be static and dynamic)

$myPublicIp = New-AzureRmPublicIpAddress -Name "myPublicIp" -ResourceGroupName 'My_Resource_Group' -Location 'west europe' -AllocationMethod Dynamic

Creating local admin credentials:

We’ll store credentials in variable

$username = 'daredevil'
$password = 'Password1234!'
$passwordsec = convertto-securestring $password -asplaintext -force
$creds = New-Object System.Management.Automation.PSCredential($username, $passwordsec)

Configuring VM-Set Size

 $myVm = New-AzureRmVMConfig -VMName "dc-01" -VMSize "Standard_D2"

For all available VM sizes check out this link

Configuring VM-Set the computer name, operating system type, and  credentials

$myVM = Set-AzureRmVMOperatingSystem -VM $myVM -Windows -ComputerName "dc-01" -Credential $creds -ProvisionVMAgent -EnableAutoUpdate

Configuring VM-Set the OS image:

$myVM = Set-AzureRmVMSourceImage -VM $myVM -PublisherName "MicrosoftWindowsServer" -Offer "WindowsServer" -Skus "2012-R2-Datacenter" -Version "latest"

Configuring VM-Add network interface:

$myVM = Add-AzureRmVMNetworkInterface -VM $myvm -Id $mynic.Id

Configuring VM-Define the name and location of the VM hard disk:

$storacct = Get-AzureRmStorageAccount -ResourceGroupName 'my_resource_group' –StorageAccountName 'myresourceaccount11201'
$blobPath = "vhds/myOsDisk1.vhd"
$osDiskUri = $storacct.PrimaryEndpoints.Blob.ToString() + $blobPath

With above commands,VM disk is created in storage account myresourceaccount11201

Configuring VM-Add hard disk to VM:

$vm = Set-AzureRmVMOSDisk -VM $myVM -Name "myOsDisk1" -VhdUri $osDiskUri -CreateOption fromImage

Create VM:

New-AzureRmVM -ResourceGroupName 'my_resource_group' -Location 'west europe' -VM $myVM

 

To find out Domain name,on (new) Azure web portal click Azure Active Directory

1

And Domain Names

2.PNG

This domain name we’ll use during user creation

Creating New User

Click again Azure Active Directory-Users and Groups-Add a User:

3.png

Give user name and Job title and click OK:

4.PNG

On Directory role choose role

User:can access assigned resources but cannot manage most directory resources.

Global Administrator:Full admin rights

Limited Administrator:has the one of following roles:

Helpdesk administrator: Resets passwords, manages service requests, and monitorsservice health

Billing administrator: Makes purchases, manages subscriptions, manages support tickets, and monitors service health.

Service support administrator: Manages service requests and monitors service health.

Exchange service administrator: Users with this role have global permissions within Microsoft Exchange Online, when the service is present

Lync (Skype for Business) service administrator: Users with this role have global permissions within Microsoft Skype for Business, when the service is present.

User account administrator: Resets passwords, monitors service health, and manages user accounts, user groups, and service requests

SharePoint service administrator: Users with this role have global permissions within Microsoft SharePoint Online, when the service is present.

Security reader: Read-only access to a number of security features of Identity Protection Center, Privileged Identity Management, Monitor Office 365 Service Health, and Office 365 Security & Compliance Center.

Security administrator: All of the read-only permissions of the Security reader role, plus a number of additional administrative permissions for the same services: Identity Protection Center, Privileged Identity Management, Monitor Office 365 Service Health, and Office 365 Security & Compliance Center.

Privileged Role Administrator:perform common role management related tasks

Guest inviter:invite guest users

1.PNG

 

6.PNG

Copy password to clipboard and click create

Adding Windows 10 to Azure AD

On windows 10,click settings-System

1.PNG

About-Connect to work or school

 

1.PNG

Connect

1.PNG

Join this device to Azure Active Directory

1.PNG

Enter username/password (copied to clipboard)

10

Need to set a new password:

 

11

Click Join

 

12

 

13

When log in to Windows 10 we are asked to set PIN (You can skip next 4 pictures if don’t want to set up a PIN)

14

 

15

Provide cell phone number,you’ll get verification code

 

16.PNG

Set desired PIN

 

17

 

18

Next time You log on,You’ll have two options to log in (Password and PIN)

18-1a.PNG

When logged in,click change account settings:

18a.png

Manage my account:

 

18b

Azure portal web page opens:

 

19

 

 

 

Installing Active Directory on Azure VM

Posted: November 18, 2016 in Azure

In one of previous posts i installed VM with Windows Server 2016.It currently have dynamic IP address,so we need to set a static one.

Installing Azure PowerShell

Azure PowerShell is a set of modules that provide cmdlets to manage Azure with Windows PowerShell. You can use the cmdlets to create, test, deploy, and manage solutions and services delivered through the Azure platform.I used Web Platform Installer.It’s tool that allows you to download and install web and cloud tools.

capture

Capture.PNG

Capture.PNG

Now start powershell as Administrator

Add-AzureRMAccount

You’ll be prompted for Azure credentials

capture

capture

Now,when we are logged in to Azure,we can finally set VM’s IP and DNS address

$RGname = 'test_network_resource_group' #VM and NIC RG
$VNetRG = 'test_network_resource_group' #Virt Net RG
$VMName = 'server-2016' #VM Name
$NICName = 'server-2016784' #NIC Name
$VNetName = 'test_network' #Virt Net name
$TarSubnetName = 'default' #Target subnet name
$VM = Get-AzureRmVM -Name $VMName -ResourceGroupName $RGname
$VNET = Get-AzureRmVirtualNetwork -Name $VNetName -ResourceGroupName $VNetRG
$TarSubnet = Get-AzureRmVirtualNetworkSubnetConfig -VirtualNetwork $VNET -Name $TarSubnetName
$NIC = Get-AzureRmNetworkInterface -Name $NICName -ResourceGroupName $RGname
$NIC.IpConfigurations[0].Subnet.Id = $TarSubnet.Id
Set-AzureRmNetworkInterface -NetworkInterface $NIC

#Once the subnet has been set and that applied can apply the static IP address
$NIC = Get-AzureRmNetworkInterface -Name $NICName -ResourceGroupName $RGname
$NIC.IpConfigurations[0].PrivateIpAddress = ‘10.1.1.5' #set IP address
$NIC.IpConfigurations[0].PrivateIPAllocationMethod = 'Static'
$NIC.DnsSettings.DnsServers = '10.1.1.5' #Set preferred DNS server 
Set-AzureRmNetworkInterface -NetworkInterface $NIC

Installing AD on Azure VM

I logged on to VM and set Primary DNS suffix

netdom computername server-2016 /add:server-2016.test.com
netdom computername server-2016 /makeprimary:server-2016.test.com

After reboot,i installed AD service:

Install-windowsfeature ad-domain-services -IncludeManagementTools
Import-Module ADDSDeployment
Install-ADDSForest `
-CreateDnsDelegation:$false `
-DatabasePath "C:\Windows\NTDS" `
-DomainMode "Win2012R2" `
-DomainName "test.com" `
-DomainNetbiosName "TEST" `
-ForestMode "Win2012R2" `
-InstallDns:$true `
-LogPath "C:\Windows\NTDS" `
-NoRebootOnCompletion:$false `
-SysvolPath "C:\Windows\SYSVOL" `
-Force:$true

Setting public DNS name of Azure VM

After Azure VM is installed public DNS name is empty by default.

On Azure dashboard click on Virtual Machine and then click on selected area (picture below)

1-1.PNG

Set desired name:

1-2

Enable WinRM 

We need to modify Network Security Group (NSG)

Click All Resources

1-1

Select NSG

1-1

Click On Inbound security rules

1-1.PNG

Click Add

1-1

Enter Rulename,from service drop-down choose WinRm,click Allow and OK

1-1

1-1

Now enable port 5986 on Azure VM (Run Powershell As admin):

New-NetFirewallRule -Displayname "Allow PS Remoting" -direction inbound -LocalPort 5986 -Protocol tcp -Action allow

Create self-signed certificate (Run Powershell As admin):

New-SelfSignedCertificate -DnsName server-2016.westeurope.cloudapp.azure.com -CertStoreLocation Cert:\LocalMachine\My

Copy Thumbprint to clipoard

1-3

Configure WinRM to listen on port 5986 (run CMD as admin),we can’t run this command from Powershell (Error: Invalid use of command line. Type “winrm -?” for help.)

winrm create winrm/config/Listener?Address=*+Transport=HTTPS @{Hostname="server-2016.westeurope.cloudapp.azure.com";CertificateThumbprint="4C73BF0432E120DDDEABE4B9D19AA0B9C280A18B"}

Export Self-signed certificate from Azure VM

Start-run-mmc Add/Remove SnapIn

1-5a.png

Click Certificate

1-5b.png

Computer Account

1-5c

Local Computer

1-5d

Click Personal-Certificates-Self-signed certificate-Right click-All-Tasks-Export

1-5e

Don’t export Private Key

1-5f

Click Next

1-5g

Export certificate to file

1-5h
Importing certificate on client machine
After copying certificate to client machine,on the client,right click on certificate-Install Certificate

1-6.png

Current User

1-7

Place all certificates in the following store

1-8

Trusted Root Certification Authorities

1-9

 

 

1-5

 

 

Connect to Azure VM:

Enter-PSSession -ComputerName server-2016.westeurope.cloudapp.azure.com -Credential spiderman -UseSSL

1-10

Installing Microsoft Azure Virtual Machine

Posted: November 12, 2016 in Azure

We need Microsoft account first,and register it at https://azure.microsoft.com/en-us/free/?b=16.45 ,for verificaton purpose,we need to provide Credit Card and cell phone number.We have 30 days trial period and 200 USD,as soon as we reached 200 USD limit,account will be suspended.Once registered,and logged in,we can create our virtual network

1-1.PNG

Click add:

1-2

Specify name,subnet,sunet mask,choose whether to create new or create existing Resource group.Resource groups provide a way to monitor, control access, provision and manage billing for collections of assets that are required to run an application, or used by a client or company department

1-3

Now we can create VM:

Click Virtual machine

1-4

Click add

1-5

I installed server 2016 so typed Server 2016 in search field

1-6.png

1-7

For difference between Classic and Resource Manager deployement method see this link

Set Username and password (Username Administrator is not allowed),password must be minimum 12 characters long

1-8

Choose VM size

1-9

1-12.png

After deploying,when clicking again on Virtual machines,we can see our VM (it’s automatically started,port 3389 is opened)

1-15.PNG

1-13

Right click VM and choose connect,RDP file will be downloaded

1-14.png

1-15.PNG

Double clicking on rdp file we’ll be asked for credentials:

1-15.PNG

1-16.png

Packaging software in docker images

Posted: November 3, 2016 in Linux

By default,when we create docker,it comes without any software installed.
Wouldn’t be nice if we can create predefined docker images (remember,dockers are derived from images),with predefined software.

Let’s start with “empty” docker:

docker run --name web --hostname web -it ubuntu bash

Update docker container and install some software:

root@web:/# apt-get update && apt-get install nano -y && apt-get install -y  net-tools

Now we need to create image from a modified container.It’s not a bad idea to use -a switch that “signs” an image with author string and -m which set a commit message

root@ubuntu:~# docker commit -a "created by me :)" -m "with net-tools" web ubuntu_modified
sha256:0575f08e5562a1793357f630109366f97146bba9ff9a97898c7f0640305000ca
root@ubuntu:~#  docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
ubuntu_modified     latest              0575f08e5562        4 minutes ago       167.6 MB
registry            2                   c9bd19d022f6        2 weeks ago         33.3 MB
ubuntu              latest              f753707788c5        2 weeks ago         127.2 MB
hello-world         latest              c54a2cc56cbb        4 months ago        1.848 kB
nginx               1.9                 c8c29d842c09        5 months ago        182.8 MB

Now we need to test it:
We’ll remove web container (with net-tools installed)

docker rm -v web

Create new container from modified image:

docker run --name web1 --hostname web1 -it ubuntu_modified bash
root@web1:/# ifconfig
eth0      Link encap:Ethernet  HWaddr 02:42:ac:11:00:04
          inet addr:172.17.0.4  Bcast:0.0.0.0  Mask:255.255.0.0
          inet6 addr: fe80::42:acff:fe11:4/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:8 errors:0 dropped:0 overruns:0 frame:0
          TX packets:8 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:648 (648.0 B)  TX bytes:648 (648.0 B)

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

As we can see,ifconfig is available “out of the box”

Exporting and imorting containers

docker export --output web1_export.tar.gz web1

Docker container is exported to tar file

Copying container to another system (with docker installed):

root@ubuntu:~# scp web1_export.tar.gz ja@192.168.0.50:/tmp

Importing and running it in new system

docker import web1 web1_export.tar.gz
docker run -it web1 /bin/bash

 

Automating docker deployement

First,create a docker file

FROM ubuntu:latest
MAINTAINER dragan979@yahoo.com
RUN apt-get update && apt-get install -y apache2 && apt-get install -y nano && apt-get install net-tools
RUN adduser --disabled-password --gecos '' example
RUN usermod -G $(groups example| sed -e 's/.*: *//' -e 's/ */,/g'),example example
VOLUME /myvolume
COPY apache.sh /usr/local/
COPY test /myvolume/test
RUN mkdir /in_docker
RUN chown example:example /in_docker
EXPOSE 80
CMD bash -C '/usr/local/apache.sh';'bash'

FROM:Tells the docker wich image to use

MAINTAINER:who created the image

RUN:commands to execute

VOLUME:create volume in docker container

COPY:copy files/folders from host to docker container

EXPOSE:open port on docker container

CMD:run script on startup on docker container

To summarize:

New docker container will be created,container will be updated,apache,nano and net-tools will be installed,new user and group (example) will be created and user will be added to group.Volume /myvolume will be created,script to start apache service will be copied from host to docker container,and folder test will be also copied to docker container,also /in_docker folder will be created in docker container.

Compose container:

docker build --tag ubuntu-apache .

New image,ubuntu-apache will be created based on docker file in current folder .

Step 1 : FROM ubuntu:latest
latest: Pulling from library/ubuntu
Digest: sha256:2d44ae143feeb36f4c898d32ed2ab2dffeb3a573d2d8928646dfc9cb7deb1315
Status: Downloaded newer image for ubuntu:latest
—> f753707788c5
Step 2 : MAINTAINER dragan979@yahoo.com
—> Running in c6a72a1259f8
—> dc08f9805cf6
Removing intermediate container c6a72a1259f8
Step 3 : RUN apt-get update && apt-get install -y apache2 && apt-get install -y nano && apt-get install net-tools
Step 4 : RUN adduser –disabled-password –gecos ” example
—> Running in ec1a36f56ae7
Adding user `example’ …
Adding new group `example’ (1000) …
Adding new user `example’ (1000) with group `example’ …
Creating home directory `/home/example’ …
Copying files from `/etc/skel’ …
—> 1f987549253e
Removing intermediate container ec1a36f56ae7
Step 5 : RUN usermod -G $(groups example| sed -e ‘s/.*: *//’ -e ‘s/ */,/g’),example example
—> Running in 70a33b1a09ff
—> f0875f632bad
Removing intermediate container 70a33b1a09ff
Step 6 : VOLUME /myvolume
—> Running in f794f854779e
—> 9412bd436bb6
Removing intermediate container f794f854779e
Step 7 : COPY apache.sh /usr/local/
—> ae1b7dccece3
Removing intermediate container 65e578b6a262
Step 8 : COPY test /myvolume/test
—> 15172e733a3b
Removing intermediate container b525ad49fb94
Step 9 : RUN mkdir /in_docker
—> Running in 30954343fbe7
—> 5f6b51d7d249
Removing intermediate container 30954343fbe7
Step 10 : RUN chown example:example /in_docker
—> Running in 3da2b61afe17
—> ec1d1ebdc353
Removing intermediate container 3da2b61afe17
Step 11 : EXPOSE 80
—> Running in 7684950ddb84
—> dd10f2b22e64
Removing intermediate container 7684950ddb84
Step 12 : CMD bash -C ‘/usr/local/apache.sh’;’bash’
—> Running in 373d8c0e3d2a
—> 056203232f3a
Removing intermediate container 373d8c0e3d2a
Successfully built 056203232f3a

All steps defined in docker file are executed

Now run container based on new image:

docker run --name web -it ubuntu-apache
root@ubuntu:~# docker run --name web -it ubuntu-apache
 * Starting Apache httpd web server apache2                                                                    AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 172.17.0.4. Set the 'ServerName' directive globally to suppress this message

Container is created and script copied from host (apache.sh) is started (service apache2 start).Also folder copied from host (test) is shown,as well as created folder (in_docker)

root@97b57ef34be9:/# ls
bin   dev  home       lib    media  myvolume  proc  run   srv  tmp  var
boot  etc  in_docker  lib64  mnt    opt       root  sbin  sys  usr