Jul 17, 2018

Introduction to docker

Docker is a way to simplify the process of building applications, shipping them, and then running them in different environments.

Image

Image is a file that's essentially a snapshot of a container. Images are created with the build command. 

docker build -t rraj/nodeexpress .

The above command will create a image using Dockerfile and tag that image as rraj/nodeexpress. When you build a new image, Docker does this for each instruction (RUN, COPY etc.) in your Dockerfile:
  • create a intermediate (temporary) container from the previous image layer (or the base FROM image for the first command.
  • run the Dockerfile instruction in the temporary "intermediate" container;
  • save the temporary container as a new image layer.
  • remove intermediate container
The final image layer is tagged with whatever you name the image. Once the image is built, you can view all the layers that make up the image with the docker history command.

docker history rraj/nodeexpress

The intermediate image will not show when you run docker images, but these are cached, so if you build it again it will use cache until it find new instruction after which it will create intermediate contain and follow the same step for subsequent instruction. Try this by changing one of the instruction.


Pull
Because image can become quite large, images are designed to be composed of layers of other images, allowing a minimal amount of data to be sent when transferring images over the network. Layers can be reused by images. Run docker pull node:6.14.3 and then run docker pull node:8.11.3, you will notice that some of the layer already exist and it will not pull them and it will show them as Already exists.  

Container

Image is like a blue print which isn't very useful of it own, so you use them to create running instance of container. Container are actually where the live application run. So image is a read only template with layering, for example you will have a layer specific to your linux (or windows) OS and then you will have layer for your application framework like asp.net core or nodejs and so on. Once you have an image you can build an isolated container. Image and file system they have is read only and can be shared across multiple containers, whereas container has thin read/write layer



Benefits of Using Docker

Build it once and run it anywhere

You develop an application using programming run-time (like nodejs, .net) on you dev box and then you add some dependencies to it like angularjs, newtonsoft, entityframework etc. The instruction on how to do this will differ depending on what OS you are using MacOS, Linux or Windows or may be even between different version of same OS. This raises a big complexity in developing application and sharing and deploying it to different environments. With docker you create a docker file which you  can think of it as a recipe for how to set up your application. You only need to define this file once and then build it. Once that Docker image is built, all you have to do is move it to another machine and run it.

Resource efficiency and density

Since docker does not require guest OS as compared to VM, you can run many more containers than VMs on a single server.

Effective isolation and resource sharing

By default, a container is relatively well isolated from other containers and its host machine. You can control how isolated a container’s network, storage, or other underlying subsystems are from other containers or from the host machine. Docker uses a technology called namespaces to provide the isolated workspace called the container. When you run a container, Docker creates a set of namespaces for that container. These namespaces provide a layer of isolation. Each aspect of a container runs in a separate namespace and its access is limited to that namespace.

Speed

Starting, creating, replicating or destroying containers is very fast. Run following command and you will have sql server instance. Also if you have image already on your m/c running a container will be in seconds
docker run -e 'ACCEPT_EULA=Y' -e 'SA_PASSWORD=mysecurepwd' -p 1433:1433 -d microsoft/mssql-server-linux

Handy Command

List Images
docker images

Remove Image
docker rmi <few character of images id>

Launch docker container
docker run <image name>
Options
 -d  - detached mode 
 -name - name container
 --rm - automatically clean up container and remove file system when container exists
 -it  - For interactive processes like a shell (docker run -it ubuntu /bin/bash)
 -p hostport:containerport  - Expose container port to host post
 -e  - To set environment variable refer this for automatically set environment variable in Linux
 --memory=27m Max amount of memory a container can use
 --cpus=".1"  Specify how much of the available CPU resources a container can use.

Other container command
docker ps -a
docker ps -as #with container size
docker stop <container>
docker rm <container>
docker inspect <container>
docker container logs -f  <container> # follow documentation for more options
docker stats <container name>

Start a shell in a container
docker exec -it <containername> /bin/bash

Remove unused data
docker system prune -a

Common Collection Methods in Javascript and C#

Transform each element of collection into a new form and return new array 
javascript  
[1, 2, 3].map(x => x * 2);
c#
(new int[] {1, 2, 3}).Select(x => x * 2)

var students1 = new[] {
 new { Id = 1, FirstName = "John", LastName = "Singh", Addresss=new []{ new {City = "Boston" }, new { City = "Quincy" } } } ,
 new { Id = 2, FirstName = "Json", LastName = "Jha", Addresss=new []{ new {City = "Cambridge" } } }
 };
foreach ( var item in students1.SelectMany(y=>y.Addresss,(a,b)=> new { a, b} ) ) {
 Console.WriteLine($"{item.a.FirstName}-{item.b.City}");
}
Filters collection 
javascript
[1, 2, 3].filter(x => x > 2)
c#  
(new int[] {1, 2, 3}).Where(x=>x>1)
Accumulator function over a collection 
javascript  
[1, 2, 3].reduce((accumulate, currentValue, index) => accumulate + currentValue, 10)
c#
(new int[] {1, 2, 3}).Aggregate(10, (accumulate, currentValue) => accumulate + currentValue)
Determines whether a collection contains any elements which pass the test 
javascript
[1, 2, 3].some(x=>x>2) //true
[1, 2, 3].some(x=>x>3) //false 
c#
(new int[] {1, 2, 3}).Any(x=>x>2) 
Determines whether all elements of collection pass the test 
javascript
[1, 2, 3].every(x=>x>0) //true
[1, 2, 3].some(x=>x>1) //false 
c#   

(new int[] {1, 2, 3}).Any(x=>x>2) 
(new int[] {1, 2, 3}).All(x=>x>2)
Find first element of collection that pass the test 
javascript  
[1, 2, 3].find(x=>x>1) //2
[1, 2, 3].find(x=>x>7) //undefined
[1, 2, 3].findIndex(x=>x>0) //0
[1, 2, 3].findIndex(x=>x>7) //-1
c#  
(new int[] {1, 2, 3}).First(x=>x>1) //2
(new int[] {1, 2, 3}).First(x=>x > 7) //InvalidOperationException 
(new int[] {1, 2, 3}).FirstOrDefault(x=>x3) //0

(new int[] { 1, 2, 3 }).ToList().Find( x => x > 0 ) //0
(new int[] { 1, 2, 3 }).ToList().Find( x => x > 7 ) //0
(new int[] { 1, 2, 3 }).ToList().FindIndex( x => x > 7 ) // -1
Concatenates two Collections 
javascript
[1, 2, 3].concat([4, 5, 6])
[...[1, 2, 3],...[4, 5, 6]]
c#
(new int[] {1, 2, 3}).Concat(new int[] {4, 5, 6})
GroupBy 
javascript
[{name:'John', city:'Quincy'},{name:'Sam', city:'Boston'} ,{name:'Json', city:'Boston'}]
  .reduce((a,c,i)=>{
    let element = a.find(x=>x.key === c.city);
    element ? element.item.push({name:c.name}): a.push({key:c.city, item:[{name:c.name}]});
    return a;
  }, [])  
c#
var students = new[] { new { Id=1, FirstName = "John", LastName = "Singh" }, new { Id = 2, FirstName = "Json", LastName="Jha"} };
var address = new[] { new {StudentID =1, City = "Boston" }, new { StudentID = 1, City = "Quincy" }, new { StudentID = 2, City = "Quincy" } };
var query1 = students.
 Join( address, s => new { s.Id }, a => new { Id = a.StudentID }, ( s, a ) => { return new { Name = s.LastName + "," + s.FirstName, a.City }; } ).
 GroupBy( x => x.Name );
foreach ( var item in query1 ) {
 Console.WriteLine($"{item.Key}-{item.Count()}");
}
Sorting 
javascript  
console.log([{name:'John', age:42},{name:'Sam', age:25}].sort((x,y)=>x.age-y.age))
c#  
var a = new int[] { 1, 2, 3, 5 };
a.OrderBy(x=>x) //here x should implement ICampare
Slicing 
javascript
var number = [ 1, 2, 3];  
console.log(number.slice(0,2,))//1,2 (will not include end index), number object is not modified
console.log(number.splice(1,2,4)) //[2,3] starting from index 1 take out two and add 4 at the end  
console.log(number) //1,4

number = [ 1, 2, 3];  
console.log(number.shift());//1
console.log(number) //2,3
number = [ 1, 2, 3];  
console.log(number.pop());//3
console.log(number) //1,2

c#
var a = new int[] { 1, 2, 3, 5 };
a.Skip( 1 ).Take(2); //[2,3]
a.Take(1).Concat(a.Skip(3)) //[1,5]
a.Take(1).Concat(new int[]{4}).Concat(a.Skip(3)) //[1,4,5]
var b = new List<int>(){ 1, 2, 3, 5 };
b.RemoveAt(2);//remove 2nd item
b.Remove(5);//remove item with value as 5

Add New Item
javascript
[1,2,3].push(4)// add 2 to end
[1,2,3].upshift(0)//add 0 to starting

c#
stIndex(x=>x=
(new List<int>(){1,2,3,2,5}).Add(6) (new List<int>(){1,2,3,2,5}).Insert(0,0)
Index Of Item 
javascript
[1,2,3,1].indexOf(1,2)///eturn 3
c#
Array.IndexOf( [1,2,3,1], 1, 2 ) //return 3
(new List<int>(){1,2,3,2,5}).FindIndex(x=>x==2);
(new List<int>(){1,2,3,2,5}).FindLastIndex(x=>x==2);


String to Character Array 
javascript  
'this is string'.split('');
'this is string'.split('').join('');
c# 
"this is string".ToCharArray();
new String("this is string".ToCharArray());
String Split 
javascript  
'this is string'.split('is');
c# 
"this is string".Split(new char[]{'i', 't'}, StringSplitOptions.RemoveEmptyEntries);
"this is string".Split(new string[]{is, str},StringSplitOptions.RemoveEmptyEntries );
Substring 
javascript  
'abcdef'.substring('0,3');//abc start index and end index not include end index
c#
"abcd".Substring(1,2);bd//start index and length

Join Collection of String
javascript  
'this is string'.split(' ').join(',');
c# 
string.Join(",","this is string".Split(" "))
https://javascript.info/string