Introduction to C# delegate and multicast delegate

What is a C# delegate?

The C# delegate is a reference data type that defines the method and their signature. The delegate stores the address of one or more methods. When a delegate for a method assigned, it behaves exactly like the method. It can be invoked like any other method with parameters and return value.
A delegate simply stores the reference of the methods with the same signatures such as return type and parameter list. A delegate can be invoked as like a class by creating an object for the delegate. The delegate object allows running the methods at run time without invoking it directly.

Usage of delegate:

When an event needs to be used then delegates can be used. Multicast delegates can be used for invoking many events at a time. When a class need to have more than one implementation of the method and to encapsulate a static method.

Refer for when to use delegates and interfaces -> https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/ms173173(v=vs.100)

The Ultimate Managed Hosting Platform

Declaring a delegate:

The System.Delegate class is the base class for the delegate declaration. The delegate keyword is used to declare a delegate. The return type and parameters should same as the methods.

Eg:

public delegate int CalDelegate(int num1,int num2);

Instantiation and invoking delegates:

To instantiate a delegate, an instance is created similar to how a class instance is created. When a delegate is instantiated, the address of the method is stored in the instance.


Eg:
Calculator cal=new Calculator();
CalDelegate sumDel=new CalDelegate(cal.sum);
CalDelegate mulDel=new CalDelegate(cal.multiply);


CalDelegate is the delegate created and the sumDel is the delegate instance instantiated to CalDelegate with the reference to the sum() method in cal instance and mulDel is for reference of multiply() method.


To invoke the delegate, calling the delegate instance with the parameter list referenced by the delegate with the same data type.


Eg:
sumDel(10, 12);

mulDel(10,12);

using System;

public delegate int CalDelegate(int num1,int num2);
public class Calculator
{
	public int sum(int num1,int num2)
	{
		return num1+num2;
	}
	public int multiply(int num1,int num2)
	{
		return num1*num2;
	}
}
public class Program
{
	public static void Main()
	{
		Calculator cal=new Calculator();
		CalDelegate sumDel=new CalDelegate(cal.sum); // sumDel for sum() reference
		CalDelegate mulDel=new CalDelegate(cal.multiply); //mulDel for multiply() reference
		Console.WriteLine(sumDel(10,12));
		Console.WriteLine(mulDel(10,12));
	}
}

Output:

22

120

Multicast delegates:

To have a reference of more than one method in delegate multicast delegates is used. This mainly used in the multi-event invocation. The += operator is used to add the methods referred to delegate and -= operator is used to remove the methods. The methods are called in First-In-First-Out(FIFO) order.

Remember when using multicast delegates use void as return types because the use of multiple methods will clash in return type. So void is safe to avoid runtime exception.

Eg:

CalDelegate simpleDel=new CalDelegate(cal.sum);

simpleDel += new CalDelegate(cal.multiply);

simpleDel -= new CalDelegate(cal.sum);

using System;

public delegate void CalDelegate(int num1,int num2);
public class Calculator
{
	public void sum(int num1,int num2)
	{
		Console.WriteLine(num1+num2);
	}
	public void multiply(int num1,int num2)
	{
		Console.WriteLine(num1*num2);
	}
}
public class Program
{
	public static void Main()
	{
		Calculator cal=new Calculator();
		CalDelegate simpleDel=new CalDelegate(cal.sum);
		simpleDel+=new CalDelegate(cal.multiply); //multicasting using += operator
		simpleDel(10,12);
	}
}

Output:

22

120

The above delegate example is used with multicast delegates in which the firstsum()method is referenced to thesimpleDeldelegate. Thenmultiply()method is added to multicast using += operator. To remove the methods from delegate simply use -= operator. As said multicast delegate run in FIFO, firstsum()delegate reference is run and thenmultiply()with output 22 and 120 respectively.

For documentation of delegates refer -> https://docs.microsoft.com/en-in/dotnet/api/system.delegate?view=netcore-3.1

In next post, I will explain synchronous delegate, asynchronous delegate and covariance and contravariance delegates.

For my other C# archives -> Go.

If you enjoy my post please share it and if any suggestion please comment on it.

 1,568 total views,  1 views today

How to create C# List generics

C# List<T> generics

  • C# List<T> is a strongly typed collection for creating a list of objects of type <T>. 
  • It is similar to ArrayList, we can add, remove, search, sort, manipulate list-objects.
  • In C#, ArrayList is a non-generic collection whereas List<T> is a generic collection.
  • List<T> has high performance than ArrayList and type-safe. 
  • List<T> has similar methods and properties as the ArrayList.

Creating a C# List<T>

  • List<T> is created by using a new operator either it can be empty capacity or specify the size.

Syntax:

List<T> <list_name> = new List<T>(<capacity>);

  • <T> is the type of object to be created like int, float, double etc.
  • <list_name> name of the list.
  • <capacity> is the size of the list which is optional.

Eg:

List<string> List1 = new List<string>();

Adding object to List<T>

  • Add(T obj) method will add the element type <T> in the list on by one.

Eg:

List1.Add(“Element1”);

  • Insert(int index, T obj) method will add the element at the specified index.

Eg:

List1.Insert(1,”Element1”);

Removing object to List<T>

  • Remove(T obj) method will remove the element in the list.

Eg:

List1.Remove(“Element1”);

  • RemoveAt(int index) Removes the element at the specified index.

Eg:

List1.RemoveAt(1);

Get the size of List<T>:

  • Count property is used to get the size of the list.

Eg:

List1.Count();

To sort the List<T>:

  • Use the Sort() method to sort the array in ascending order.

Eg:

List1.Sort();

Accessing the elements in the List<T>

  • The index number can be used to access the elements like an array.

Eg:

List1[0] // accessing element at index 0;

  • To iterate over the List<T>, use foreach function.

Eg:

foreach(string str in List1)

{

Console.WriteLine(str);

}

Example:

using System;
using System.Collections.Generic;
					
public class Program
{
	public static void Main()
	{
		//create new List<T> of string type using new operator.
		List<string> list1=new List<string>();
		
		//Adding elements using Add(T) method.
		list1.Add("Element1");
		list1.Add("Element2");
		list1.Add("Element3");
		list1.Add("Element4");
		list1.Add("Element5");
		
		
		Console.WriteLine("Printing elements in list1");
		Console.WriteLine("Size of list1: "+list1.Count);//prinitng size of list1 using count
			
		//printing list1 elements using foreach
		foreach(string str in list1)
		{
			Console.WriteLine(str);
		}
		
		//removing 'Element1' 'Element2' using Remove(T) method.
		list1.Remove("Element1");
		list1.Remove("Element2");
		
		Console.WriteLine();
		
		Console.WriteLine("Printing elements in list1 after removing Element1, Element2");
		Console.WriteLine("Size of list1: "+list1.Count);//prinitng size of list1 using count
		
		//printing list1 elements using foreach
		foreach(string str in list1)
		{
			Console.WriteLine(str);
		}
		
		list1.Insert(2,"Element1");//inserting 'Element1' in index 2
		list1.Insert(4,"Element2");//inserting 'Element2' in index 4
		
		Console.WriteLine();
		
		Console.WriteLine("Printing elements in list1 after inserting Element1, Element2");
		Console.WriteLine("Size of list1: "+list1.Count);//prinitng size of list1 using count
		//printing list1 elements using foreach
		foreach(string str in list1)
		{
			Console.WriteLine(str);
		}
		
		list1.Sort();//sorting list1
		
		Console.WriteLine();
		
		Console.WriteLine("Printing elements in list1 after sorting");
		//printing list1 elements using foreach
		foreach(string str in list1)
		{
			Console.WriteLine(str);
		}
		
	}
}

Output:

Printing elements in list1
Size of list1: 5
Element1
Element2
Element3
Element4
Element5

Printing elements in list1 after removing Element1, Element2
Size of list1: 3
Element3
Element4
Element5

Printing elements in list1 after inserting Element1, Element2
Size of list1: 5
Element3
Element4
Element1
Element5
Element2

Printing elements in list1 after sorting
Element1
Element2
Element3
Element4
Element5

It is recommended to use List<T> generic over ArrayList since it is type-safe, high performance. 

To more refer:https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=net-5.0#remarks


For my other programming archives -> Go.

If any suggestions please comment about it.

 785 total views,  1 views today

Learn how to create C# ArrayList

ArrayList in C#

ArrayList is a type of non-generic collection framework available in the .Net framework for creating an array of objects list using C# language. The non-generic refers to that we don’t need to mention the data type of the array list. This array list can be dynamically defined of what size wanted. Unlike array initialization, we don’t need to specify the size of the list. It dynamically allocates size as we add or remove an element in the array list. Since it is a non-generic collection, the elements added to the array are stored as an object.

The basic operation we do in ArrayList add, remove, count, sort list. We can also do many operations such as reverse the ArrayList, get the index value of elements etc.

To view full properties and methods please refer: https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist?view=netcore-3.1

Create ArrayList

We can create an ArrayList using the ArrayList class and new operator.

using System;
using System.Collections;
					
public class Program
{
	public static void Main()
	{
		//array1 array list is created using new operator.
		ArrayList array1=new ArrayList();
		
	}
}

Add() method

Add(Object value) method will add the element to the ArrayList one after another.

using System;
using System.Collections;
					
public class Program
{
	public static void Main()
	{
		
		ArrayList array1=new ArrayList();
		//adding 5 elements to array1 using ADD() method.
		array1.Add("Element1");
		array1.Add("Element2");
		array1.Add("Element3");
		array1.Add("Element4");
	}
}

Remove()

Remove(Object value) method will remove the element mentioned.

using System;
using System.Collections;
					
public class Program
{
	public static void Main()
	{
		
		ArrayList array1=new ArrayList();
		//adding 5 elements to array1 using Add() method.
		array1.Add("Element1");
		array1.Add("Element2");
		array1.Add("Element3");
		array1.Add("Element4");
		
		Console.WriteLine("Before removing");
		//output of array1 before remove
		foreach(string str in array1)
		{
			Console.WriteLine(str);
		}
		
		//removing Element4 and Element3 from array1 arraylist using Remove().
		array1.Remove("Element3");
		array1.Remove("Element4");
		
		Console.WriteLine("After removing");
		//output of array2 after remove
		foreach(string str in array1)
		{
			Console.WriteLine(str);
		}
		
	}
}

Output:

Before removing
Element1
Element2
Element3
Element4
After removing
Element1
Element2

In the above program, foreach used to iterate through array1 ArrayList to display the elements.

Using indexers [<index_number>] we can access the elements in the array list.

The output shows the elements in array1 before and after remove() method is used.

  • To get the no of elements in the ArrayList use Count property.
  • To sort the ArrayList use Sort() method.
  • To check an element is contained in the ArrayList use Contains() method.
		//get the count of elements in array1
		Console.WriteLine(array1.Count);
		//to sort the array1
		array1.Sort();
		//check element contains in an array and return true if it contains the element else return false
		Console.WriteLine(array1.Contains("Element1"));

Some other methods are

Insert(int index,object value)

  • Use to insert the element at the given index.

RemoveAt(int index)

  • Removes the element at the given index.

BinarSearch(object value)

  • Search for an object using binary search.

Clear()

  • Clear all the elements in ArrayList.

IndexOf(object value)

  • Gets the index of the particular object.

For other operations refer .NET docs.


For other C# archives -> Go.

For my other programming archive -> Go.

 1,488 total views

C# interface and multiple interfaces tutorial

What is interface?

The definitions for a group of related functionalities that a non-abstract class or struct can declare is called an interface. The interface is another way of abstraction in C#. The interface is like the abstract class but it only contains the methods definitions, whereas the abstract class contains all methods, fields, constants definitions. Unlike the abstract class, the interface cannot have a constructor. The interface methods should be abstract and public. The interface only provides the definition for the methods. In C# multiple inheritances cannot be done in class but by means of the interface.

The interface in C#:

  • Members in the interface should be abstract and public only no other access specifier used.
  • By interface, we can’t able to create an object like an abstract class.
  • Interface only define the methods, the class needed to override and implement those methods.
  • The interface doesn’t contain a constructor.
  • The interface contains methods and properties but not fields.

Implementation of C# interface:

The interface keyword used to implement the interface. We can also implement multiple interfaces for a single class in C#. It’s suggested to use I before every interface name to identify it has the interface. To use an interface in a class we use (:) to access the interface. For example, demo as interface name then use IDemo.

Syntax:

interface <interface_name>
{
    method definition;
}
class <class_name>:<interface_name>
{
interface_method declaration;
}

Example:

using System;
	
interface IDemo1
{
	void simpleInterface();
}

public class Demo:IDemo1{
	public void simpleInterface(){
		Console.WriteLine("Implementation of Idemo1 interface");
	}
}
public class Program
{
	public static void Main()
	{
		Demo d=new Demo();
		d.simpleInterface();
		Console.ReadLine();
	}
}

Here I implement an interface called IDemo1. Then I use the IDemo1 interface in Demo class using the operator (:). Then I implement the interface method simpleInterface by declaring an output statement which displays Implementation IDemo1 interface.

Multiple interfaces:

To use multiple interfaces, simply use a comma between the interfaces name in class. The above program can be implemented as multiple interfaces with another interface called Idemo2.

using System;
	
interface IDemo1
{
	void simpleInterface1();
}

interface IDemo2
{
	void simpleInterface2();
}
public class Demo:IDemo1,IDemo2{
	public void simpleInterface1(){
		Console.WriteLine("Implementation of Idemo1 interface");
	}
	
	public void simpleInterface2(){
		Console.WriteLine("Implementation of Idemo2 interface");
	}
}
public class Program
{
	public static void Main()
	{
		Demo d=new Demo();
		d.simpleInterface1();
		d.simpleInterface2();
		Console.ReadLine();
	}
}

From C# 8.0 onwards we can implement a default implementation for the interface methods itself. We can also use other access specifiers such as private, protected, internal, public, virtual, abstract, override, sealed, static, extern. We can also implement static methods in interfaces.

For reference https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/default-interface-methods#drawbacks

For my other programming post -> Go.

 721 total views,  1 views today

A simple jquery calculator application

I had created a simple jquery calculator using HTML, CSS and jquery only. Though it is simple, it will be helpful for beginners for web developing.

I use codepen.io platform to create this application. This platform is helpful to easily create small web apps, flutter apps, react apps.

HTML code

To display the output <input> element is used here. To display the input element without editing it we need to use a read-only attribute for the input element.

I simply use <table> element to create the buttons for the calculator. You can also use other options such as flexbox or grid. It’s up to your choice.

<div class="wrapper">
  <div class="display">
    <input type="text" value="0" readonly></input>
  </div>
  <div class="button">
    <table>
      <tr>
        <td><button id="num" onclick="insrt(1)">1</button></td>
        <td><button id="num" onclick="insrt(2)">2</button></td>
        <td><button id="num" onclick="insrt(3)">3</button></td>
        <td><button id="num" onclick="insrt('+')">+</button></td>
      </tr>
      <tr>
        <td><button id="num" onclick="insrt(4)">4</button></td>
        <td><button id="num" onclick="insrt(5)">5</button></td>
        <td><button id="num" onclick="insrt(6)">6</button></td>
        <td><button id="num" onclick="insrt('-')">-</button></td>
      </tr>
      <tr>
        <td><button id="num" onclick="insrt(7)">7</button></td>
        <td><button id="num" onclick="insrt(8)">8</button></td>
        <td><button id="num" onclick="insrt(9)">9</button></td>
        <td><button id="num" onclick="insrt('*')">x</button></td>
      </tr>
      <tr>
        <td><button id="exp" onclick="cl()">C</button></td>
        <td><button id="num" onclick="insrt(0)">0</button></td>
        <td><button id="exp" onclick="eql()">=</button></td>
        <td><button id="num" onclick="insrt('/')">/</button></td>
      </tr>
    </table>
  </div>
</div>

CSS

* {
  font-family: monospace;
  font-size: 20px;
}

.wrapper {
  margin: 0 auto;
  width: 500px;
  border: 1px solid grey;
  border-radius: 10px;
  background: #ddd;
}
.display {
  margin: 10px auto;
  width: 480px;
  height: 100px;
  border: 1px solid grey;
  border-radius: 10px;
  font-size:2rem;
  background: #dfd;
  color: grey;
}

.display input{
  display: block;
  margin:20px auto;
  height:60px;
  width:420px;
  font-size:1.5rem;
  border-style:none;
  border-radius:10px;
  overflow:hidden;
}

.button {
  width: 500px;
  height: 500px;
}

.button #exp{
  background-color:orange;
}
.button table {
  table-layout: fixed;
  width: 500px;
  height: 500px;
}

.button table tr td {
  padding: 10px;
}
.button table button {
  width: 100%;
  height: 100px;
  font-weight: bold;
  border-style: none;
  border-radius: 10px;
  background: grey;
  color: white;
}

.button table button:hover {
  background: white;
  border: 1px solid grey;
  color: grey;
}

Jquery

function insrt(num){
  if( $('.display input').val()==0)
   $('.display input').val('');
  $('.display input').val($('.display input').val()+num);
}
function eql(){
  $('.display input').val(eval($('.display input').val()));
}
function cl(){
  $('.display input').val(0);
}

insrt() function is used for inserting the numbers from 0-9 and +, - , x, /.

eq() function used for evaluating the expression in the input.

To evaluate the expression in input, eval() function used to evaluate the expression.

For reference of eval() refer https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval

cl() function used for clearing the input and display 0.

The below output is an embed of codepen. You can use this to test or run the application.

For my other programming archives -> Go.

If any queries please comment below.

 857 total views,  1 views today

What is hyperledger fabric blockchain?

 Hyperledger Fabric is an open-source enterprise-grade permissioned distributed ledger technology platform. Focus for use in enterprise contexts. It has key features than any other blockchain platforms. I will explain what is a blockchain and how it is useful. Then I explain about Hyperledger Fabric blockchain platform.

What is a blockchain?

Blockchain is an immutable chain of records called a ledger. A hash function associated with the ledger and stored in chronological order of execution. These records may be a transaction done between two nodes. Blockchain network is a distributed decentralized network, where each peer nodes have a copy of the ledger. Since blockchain is a decentralized network, there is no centralized host. the reliability achieved through consensus protocol. Each node needs to verify and validate the transaction in the network. This feature makes blockchain with high security.

This is how a blockchain works.

What is hyperleder fabric blochchain?-blockchain
Source: https://www.investopedia.com/terms/b/blockchain.asp

Each time a hash function for the block created and connected with the previous block. This forms a chain of cryptographic records. After each transaction, the nodes in each node in the network store the copy of that ledger. This makes blockchain a fault tolerance network.

For more reference https://www.investopedia.com/terms/b/blockchain.asp

Bitcoin by Satoshi Nakamoto is the first blockchain network used for cryptocurrency. Nowadays, blockchain technology has many uses cases like banking, hospitality, supply chain, government etc.

some of the interesting use cases are:

  1. Deutsche Bahn, the second-largest transport company in world and infrastructure management, digitizing the railway transport with blockchain for assets management, railway signalling infrastructure. To more read here.
  2. Walmart manages its food supply chain in an unpredicted way using hyperledger fabric blockchain network. To more read here.
  3. BurstIQ’s platform helps healthcare companies to safe and secure massive amounts of patient data. Its blockchain technology enables the safekeeping, sale, sharing or license of data while maintaining strict compliance with HIPAA rules.

There are many blockchain networks available. These can be divided into two categories.

  1. Public blockchain: Public blockchain is where any participants can be able to participate in the blockchain network and make a transaction between them. Bitcoin, Ethereum which are the most popular public blockchain network.
  2. Private blockchain: Private blockchain main focus is for B2B. A consortium of organizations or organizations under governance use this blockchain. Private blockchain archives high privacy and security. The most popular private blockchain is Hyperledger technologies such as fabric and sawtooth, Corda, Ripple, Ethereum.

What is hyperledger fabric blockchain?

As said Hyperledger Fabric is a distributed ledger platform. The main focus for enterprise private blockchain solution. It is an open-source project under Linux-foundation started by IBM. It is an active project in Hyperledger technologies. Currently, more than 30 companies contribute to Hyperledger fabric.

Hyperledger technologies have different frameworks and libraries like fabric, sawtooth, indy, besu. It also has tools for managing blockchain networks. For more details go to hyperledger.org

Why hyperledger fabric?

Hyperledger fabric focus in private permissioned blockchain. It has many key features than other blockchain platforms to standalone.

They key features are:

  • Modularity
  • Permissioned
  • Privacy and confidentiality
  • Performance and scalability
  • Smart contract in form of chaincode
  • Pluggable consensus

Modularity

Hyperledger Fabric has a modular architecture. The modularity of consensus protocol, cryptographic functions, ease of smart contract development, key management protocol and different algorithms.

To know how hyperledger works go to https://hyperledger-fabric.readthedocs.io/en/release-2.2/txflow.html

Permissioned

Hyperledger fabric is a private blockchain. The main key focus is on privacy and security. A blockchain platform for the enterprise can be fully deployed using this framework. This use different consensus protocol such as byzantine and crash fault tolerance protocols.

Additionally, in such a permissioned context, the risk of a participant intentionally introducing malicious code through a smart contract is diminished. First, the participants are known to one another and all actions, whether submitting application transactions, modifying the configuration of the network or deploying a smart contract recorded on the blockchain following an endorsement policy that was established for the network and relevant transaction type.

Privacy and confidentiality

Hyperledger Fabric, being a permissioned platform, enables confidentiality through its channel architecture and private data feature. In channels, participants on a Fabric network establish a sub-network where every member has visibility to a particular set of transactions. Thus, only those nodes that participate in a channel have access to the smart contract (chaincode) and data transacted, preserving the privacy and confidentiality of both. Private data allows collections between members on a channel, allowing much of the same protection as channels without the maintenance overhead of creating and maintaining a separate channel.

Performance and scalability

In performance and scalability, Hyperledger Fabric standalone from other blockchain platforms. Variables such as transaction size, block size, network size, as well as limits of the hardware, etc may affect the performance. The Hyperledger Fabric Performance and Scale working group currently working on a benchmarking framework called Hyperledger Caliper. The latest scaled Fabric to 20,000 transactions per second.

Fabric introduces a new architecture for transactions that we call execute-order-validate. It addresses the resiliency, flexibility, scalability, performance and confidentiality challenges faced by the order-execute model by separating the transaction flow into three steps:

  • execute a transaction and check its correctness, thereby endorsing it,
  • order transactions via a (pluggable) consensus protocol, and
  • validate transactions against an application-specific endorsement policy before committing them to the ledger

This design departs radically from the order-execute paradigm in that Fabric executes transactions before reaching a final agreement on their order.

We can deploy those blockchain network using docker container technology also. Thus scalability of the blockchain network is efficient than other platforms. Many cloud service providers such as AWS, Azure, IBM provide cloud blockchain solution. Where we can easily deploy the blockchain network and make ease of transaction in it.

Smart contract in form of chaincode

A smart contract, or what Fabric calls “chaincode”, functions as a trusted distributed application that gains its security/trust from the blockchain and the underlying consensus among the peers. It is the business logic of a blockchain application.
There are three key points that apply to smart contracts, especially when applied to a platform:

  • many smart contracts run concurrently in the network,
  • A smart contract can be dynamically deployed
  • Untrusted and potentially malicious code treated as well.

It is easy to write that chaincode in native languages such as NodeJS, JAVA, Go, Typescript. No need to have separate language for smart contract.

Pluggable consensus

A consensus algorithm is a procedure through which all the peers of the Blockchain network reach a common agreement about the present state of the distributed ledger. In this way, consensus algorithms achieve reliability in the Blockchain network and establish trust between unknown peers in a distributed computing environment. Essentially, the consensus protocol makes sure that every new block added to the Blockchain is the one and only version of the truth that agreed upon by all the nodes in the Blockchain.

Hyperledger fabric uses two types of the consensus protocol. one is Byzantine protocol and another one is crash fault tolerance. As of modular architecture, it uses them as for the problem in the blockchain network. Thus achieve more reliability to the blockchain network.

For complete features visit https://hyperledger-fabric.readthedocs.io/en/release-2.2/whatis.html

I learned about this technology for my college project. It is an awesome open source project. You can easily develop a smart contract with NodeJS. We can deploy the blockchain network using containers also. For more go to https://hyperledger-fabric.readthedocs.io.

I will be posting articles on hyperledger fabric administration and chaincode development. If you have any suggestion or corrections in this article please share in the comments.

For my other programming archives -> Go.

 7,622 total views,  3 views today

How to restart containers automatically in docker

If we are using docker containers for personal use we can restart it manually using docker restart. The docker restart command allows us to restart containers with some time limit. But, in production, it is difficult to restart by manual. To restart containers automatically, we can use restart policies for docker containers.

Restart policies for docker containers

Restart polies allows the container to restart automatically in required situations. The situations may be when a failure occurs, when daemon starts, when a container stopped.
The --restart flag is used with docker run command when starting a container. There are four restart policies available.

noDo not automatically restart containers anyway
alwaysAlways restart the container even though the container stopped manually. Until the daemon stops or the restart policy is changed, it will restart it in loop.
on-failureRestart the container if it exits due to an error, which manifests as a non-zero exit code. If any container is stopped due to any fault, it will automatically restart those containers with this policy.
unless-stoppedSimilar to always, except that when the container is stopped (manually or otherwise), it is not restarted even after Docker daemon restarts.

To run a container with restart policies, try with following code pattern

docker run --restart no hello-world

The above command run the hello-world image with restart policy set as no. It will not restart the containers automatically.

docker update --restart always hello-world

Here I use update command to update the restart policy of the hello-world container with always policy. This will restart the container always even though it is stopped manually or start when the daemon starts.

To view the events that occurs during restart we can use event command.

docker event

Open the docker event in one shell and run the container with always policy with another shell. The event shows the hello-world container will restart automatically every times it stopped. The image shows that every time the hello-world container stopped, it restart it.

docker restart containers(1)

We can also restart the containers using process managers such as upstart, systemd, supervisor. I will be posting an article on using process managers for docker in later.

For any reference to docker -> go.

For my other docker archives -> go.

If you like the article feel free to share.

 1,062 total views

What is docker networking and bridge networking?

In docker we can connect two or more containers or non-docker system using networking. Whether it is a windows or Linux containers, docker network helps to connect them in an easy way. This may helpful for beginners who interested in docker.

There are different network drivers available in docker networking

  • bridge:
    The default network driver if we don’t mention a network driver when running a container. It is created automatically when a container is created. It is best for standalone containers
  • host:
    If you use the host network mode for a container, that container’s network stack is not isolated from the Docker host, and the container does not get its own IP-address allocated.
    For instance, if you run a container which binds to port 80 and you use host networking, the container’s application is available on port 80 on the host’s IP address.
  • overlay:
    Overlay is mainly used when we want to connect multiple containers to create a swarm service to communicate between them.
  • macvlan:
    Macvlan networks allow you to assign a MAC address to a container, making it appear as a physical device on your network. The Docker daemon routes traffic to containers by their MAC addresses.
  • The other driver is called none, which is used when we use third party plugins from docker hub.

Bridge networking tutorial

This tutorial explain how a two standalone containers can be connected by bridge network. Here we create two alpine linux containers namely alpine1 and alphine2, then connect them using bridge.
We can view the network list using the command

docker network ls

You may see different network listed as bridge, host, none as following image. Any newly created network also listed here.
Docker_network_ls
Next create two alpine containers as alpine 1 and alpine 2 with following command

docker run -dit --name alpine1 alpine 
docker run -dit --name alpine2 alpine

The two container created as follows
container_create
Then inspect the bridge network to view details of the containers connected to it with the following command

docker network inspect bridge

This will display a JSON format of bridge network details. We could see that by default alpine1 and alpine2 has bridge networks with different IP address as 172.17.0.2/16 and 172.17.0.3/16 respectively .
network_inspect
Now connect to the alpine1 container using attach command

docker attach alpine1

Now attach to the container and ping a website say google.com -c 2 make 2 limit of ping.

Then try to ping the alpine2 container using the IP 172.17.0.3/16 and check they are connected. If it ping correctly then successfully two containers are connected using bridge.

ping -c 2 172.17.0.3/16

docker_networking_bridge
For other docker archive -> go.
For network reference of docker -> go.

 1,187 total views,  1 views today

The difference between ADD and COPY in dockerfile.

When I was seeing some examples for docker file image building, I came across two things of same functionalities. They are COPY and ADD instructions. This article gives the difference between ADD and COPY in dockerfile. Next it explains how similar they are, then the best practice for using the RUN instead of ADD instruction.

ADD instruction

ADD instruction is an older one, which job is to copy the file or directory from a source to destination.
The ADD instruction can also do operations such as extraction of compressed files or download from an URL path.
Here the source may be a local compressed tar file or the URL path.
If it is a tar file, it extracts the contents to the destination else if it is an URL, then it download the file and extract to the destination in a similar way.
If authentication needs for URL file we can use RUN with curl or wget to download the files.
Since, ADD degrades in performance of the docker containers, COPY is been introduced for simple job.
Syntax for ADD:

ADD <src> <dest>

A simple example to ADD used for local tar file called source.tar.xz to the destination folder /dest.

ADD sourcefile.tar.xz /dest

This syntax example gives how the URL path called https://example.com/source.tar.xz file is downloaded and copied to the /dest.

ADD https://example.com/source.tar.xz /dest

COPY instruction

COPY instruction copies the file or directory from a source path to the destination.
Its job is simple as it duplicates the source file or directory to the destination.
It doesn’t include the operation of extraction or downloading files as ADD instruction.
Syntax for COPY:

COPY <src> <dest>

An example to COPY a file called source.txt to the destination folder /dest.

COPY sourcefile.txt /dest

What to use either COPY or ADD?

In dockerfile we use COPY many time because it only copies the file from a source to destination.ADD used when there is a purpose such as local tar files or URL file source.
For best docker practice, we can use RUN instruction instead of creating an extra layer.
RUN instruction with curl or wget used to get the file direct into the destination.
The RUN instruction will execute any commands in a new layer on top of the current image and commit the results. The resulting committed image will be used for the next step in the Dockerfile.

ADD https://example.com/source.tar.xz /usr/src/things/
RUN tar -xJf /usr/src/things/source.tar.xz -C /usr/src/things

For instance take the above sentence, where a file called source.tar.gz is downloaded using ADD and extracted using tar with RUN instruction.
This makes two layers that worse the docker performance.
It simply done using RUN with curl tool as follows within a single layer.
If, there is direct copy operation needed than COPY instruction is recommended.
The below dockerfile only takes single layer of operation of file download using curl and then extraction of file using tar with RUN instruction.

RUN mkdir -p /usr/src/things \
    && curl -SL https://example.com/source.tar.xz \
    | tar -xJC /usr/src/things 

Reference to the Best docker practices -> go.
For my docker archives click here -> go.
If any queries please comment it.

 1,129 total views

Deploy a React application using docker containers

This article helps you to deploy a React application using docker containers. To know about docker and docker containers refer this article. This involves creating a react app using npx, then we use the docker file to deploy the docker containers using nginx images.

Create a React application

First, we need to create a React application. For this we can use npx create-react-app tool.

npx create-react-app react-docker-example
cd react-docker-example && npm install
npm start

Run the app in the localhost at http://localhost:3000/ or if any cloud such as AWS or Azure VMs with the 3000 port to check the app is running.

Create dockerfile

First, create a dockerfile in the React app folder with the following lines of dockerfile code.

# build stage
FROM node:lts-alpine as build-stage
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build     

# production stage
FROM nginx:stable-alpine as production-stage
COPY --from=build-stage /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
  • The FROM is the base image in which React app needed to run here. Here we use node:lts-alpine image to first build the artifacts for the React app, that it set as build-stage.
  • The WORKDIR is the dir where the app is build and run.
  • Then we copy package.json to the workdir /app.
  • Then run npm install to install dependencies and run npm run build to build the dependencies.
  • In production-stage we run the react application using nginx:stable-alpine image.
    For this we need to copy the files to nginx/html folder, then we expose the port 80.

Build the docker image

Next step is to build the docker image using the docker file using the following command

docker build -t dockertutorial/react-example .

The -t is used for tag command here we named as react-example and we need to mention the folder here . used for selecting all. It take some time to build it and shows following result.

Docker-react-app-build-img
React app image build

Run the container

The last step is to run the container. docker run command is used to run the container from the image we created as following

$docker run -d -it -p 80:80 --name reactapp dockertutorial/react-example:latest 
fd2285a0a2e37afc9d0317ce6c668d2c2bf23a71d75a9df8b8d7134c8d223573
  • -d runs the command in detached mode.
  • -p refers to port which expose container to local system, here it expose port 80 of container to port 80 of local machine.
  • -it runs in interactive mode with the tag name and --name refers to name of the container.
Docker-react-app-container-img
React app container run

Then go to http://localhost:80 or if you use cloud VM use the public IP address and select the port 80. It gives the following results

Docker-react-app-img
React app

This react application can also be run with multiple containers using docker compose. This will be our next article.

  • For my docker archive -> go.
  • My programming archives -> go.
  • Any docker reference -> go.

If any suggestion and queries please comment it, so I can improve my self.

 1,141 total views