How to Access Docker container from another container by name

Task:

Create custom network with default bridge driver named as my-custom-net.
Create two container named as web1 and test1 with custom network i.e my-custom-net.
Access the container web1 from test1 using the curl command. 

1. Create a custom network with the default driver.

#docker network create --driver bridge my-custom-net                                       

2. Create Nginx Container with a custom network.

#docker container run -itd --name web1 --network my-custom-net nginx             

3. Create another container with to test Nginx container

 #docker container run -itd --name test1 --network my-custom-net                      pranavdhopey/goinit_hub:curl                                                                           

Note: pranavdhopey/goinit_hub:curl is my own image with a curl package installed on alpine base image.

4. Now check whether we are able to access the web page from other container.

#docker container exec test1 curl web1:80                                                        


By above screenshot, we can see that we are able to access web1 from test1 container using name. 













Shell VS Python Examples


1. Use for loops to display the natural numbers from 1 to 50.
## Shell Script ##
for i in {1..50}
do 
   echo $i
done
--------------------------------------
for ((i=1; i<=50; i++))
do 
   echo $i
done

## Python Script ##
for i in range(1,51):
    print(i)

2. Read the input from user and print.
## Shell Script ##
read –p “Enter Your Name : ” name
echo “${name}”

## Python Script ##
name = input(“Enter Your Name : ”)
print(name)

3. Find the largest of three number.
## Shell Script ##
read -p "Enter Num1 : " num1
read -p "Enter Num2 : " num2
read -p "Enter Num3 : " num3

if [ $num1 -gt $num2 ] && [ $num1 -gt $num3 ]
then
    echo "Largest number is ${num1} "
elif [ $num2 -gt $num1 ] && [ $num2 -gt $num3 ]
then
    echo "Largest number is ${num2} "
else
    echo "Largest number is ${num3} "
fi

## Python Script ##
num1 = int(input("Enter Num1 :))
num2 = int(input("Enter Num2 :))
num3 = int(input("Enter Num3 :))

if num1 > num2 and num1 > num3:
        largest = num1
elif num2 > num1 and num2 > num3:
        largest = num2
else:
        largest = num3
print("Largest number is : ", largest)

4. Find the given number is prime or not.
 ## Shell Script ##
read -p "Enter a number: " num
if [ $num -gt 1 ]
then
   for i in `seq 2 $(($num-1))`
   do
      if (($num % $i == 0 ))
      then
        echo "$num is not a prime number"
        exit
      fi
   done
     echo "$num is a prime number"
else
   echo "$num is a not prime number"
fi

## Python Script ##
num = int(input("Any number number : "))
if num > 1:
    for i in range(2,num):
        if (num%2)==0:
          print(num,"is not a prime number")
          break
    else:
       print(num,"is a prime number")
else:
    print(num,"is not a prime number")

5. Find the length of string and specific words from the given string.
## Shell Script ##
str="Hello World, This is Testing!"
length=${#str}
echo "Length of str is $length"
 
echo "Printing the 11 characters starting from 6th position"
echo ${str:6:11}
echo "Printing the 7 characters starting from 21st position"
echo ${str:21:7}
echo "Printing entire string"
echo ${str:0}

## Python Script ##
str = "Hello World, This is Testing!"
print("Lenght of str is ", len(str))
 
print("Printing charachetrs from 6th to 10th position ", str[6:11])
print("Printing charachetrs from 21st to 27th position ", str[21:27])
print("Printing entire string ", str[0:])

6. Use for loops to display the numbers from 0 to 50 incremented by 2.
## Shell Script ##
for i in {0..50..2}
do
   echo $i
done
--------------------------------------
for i in $(seq 0 2 50)
do
   echo $i
done
 
## Python Script ##
for i in range(0,51,2):
    print(i)



Docker Interview Questions: Part 1

Q) What is Docker?
Docker is a containerization platform which packages your application and all its dependencies together in the form of containers so as to ensure that your application works seamlessly in any environment, be it development, test, or production.

Q) What is Docker Container?
Docker containers include the application and all of its dependencies. It shares the kernel with other containers, running as isolated processes in user space on the host operating system. Docker containers are not tied to any specific infrastructure: they run on any computer, on any infrastructure, and in any cloud. Docker containers are basically runtime instances of Docker images.

Q) What is Docker Image?
Docker image is an executable package that includes everything needed to run an application – the code, a runtime, libraries, environment variables and configuration files.  
Docker image is the source of the Docker container. In other words, Docker images are used to create containers. When a user runs a Docker image, an instance of a container is created. These docker images can be deployed to any Docker environment.

Q) What is Docker architecture?
Docker uses a client-server architecture. The Docker client talks to the Docker daemon, which does the heavy lifting of building, running, and distributing your Docker containers. The Docker client and daemon can run on the same system, or you can connect a Docker client to a remote Docker daemon. The Docker client and daemon communicate using a REST API, over UNIX sockets or a network interface.

There are three components in the Docker Engine.
The Docker daemon:
The Docker daemon (dockerd) listens for Docker API requests and manages Docker objects such as images, containers, networks, and volumes. A daemon can also communicate with other daemons to manage Docker services.

The Docker client:
The Docker client (docker) is the primary way that many Docker users interact with Docker. When you use commands such as docker run, the client sends these commands to dockerd, which carries them out. The docker command uses the Docker API. The Docker client can communicate with more than one daemon.

Docker registries:
A Docker registry stores Docker images. Docker Hub is a public registry that anyone can use and Docker is configured to look for images on Docker Hub by default.

Q) What is Docker Hub?
Docker Hub is cloud based registry service that stores container images. It allows us to pull and push docker images to and from Docker Hub. It stores both types of repositories, i.e., pubic repository as well as the private repository.
Docker Hub is central repository for container image discovery, distribution, change management, workflow automation and team collaboration.

Q) What is Docker Compose?
Compose is a tool for defining and running multi-container Docker applications. 
Docker Compose is a YAML file that contains details about the services, networks, and volumes for setting up the Docker application. So, you can use Docker Compose to create separate containers, host them, and get them to communicate with each other. Each container will expose a port for communicating with other containers.

Q) What is Docker Stack?
docker stack is a command that's embedded into the Docker CLI. It lets you manage a cluster of Docker containers through Docker Swarm.

Q) What is Docker Swarm?
Docker Swarm is native clustering for Docker. It turns a pool of Docker hosts into a single, virtual Docker host.

Q) What are the components of Docker Swarm?
1. Services: Service defines a task that needs to be executed on the manager or worker node.
2. Tasks: Tasks are the Docker container that executes the commands you define in service.
3. Manager Node: The manager node has a few responsibilities like accepting commands to create service objects, allocating the IP addresses to the various tasks, and assigning the tasks to the nodes.
4. Worker Node:  It is responsible for checking the tasks assigned and also executing the containers. 

Ref Link: https://intellipaat.com/community/41375/what-are-the-components-of-docker-swarm

Q) The correct order of service creation process in swarm mode? 
Manager Node:
Ø  Docker API: Accepts command from the client and creates service object.
Ø  Orchestrator: Reconciliation loop for service objects and creates tasks.
Ø  Allocator:  Allocates IP address to tasks.
Ø  Scheduler: Assigns nodes to tasks.
Ø  Dispatcher: Checks in on workers.
Worker Node:
Ø  Worker: Connects to the dispatcher to check on assigned tasks.
Ø  Executor: Executes the tasks assigned to the worker node.

Q) What is Dockerfile?
Docker images are built from Dockerfile. A Dockerfile defines all the steps required to create a docker image with your application configured and ready to be run as a container. A Dockerfile is executed by the docker build command.
Docker image itself contains everything from the operating system to dependencies and configuration required to run your application.

Q) Docker restart policies?
i) no: This is the default restart policy.
ii) always: Always restart the container if it stops. If it is manually stopped, it is restarted only when the Docker daemon restarts or the container itself is manually restarted.
iii) on-failure: Restart the container if it exits due to an error(non-zero exit code)
iv) unless-stopped: Similar to always, except that when the container is stopped (manually or otherwise), it is not restarted even after Docker daemon restarts. 


Q) Docker container lifecycle?
1. Create the container.
2. Run the container.
3. Pause the container.
4. Un-Pause the container.
5. Start the container.
6. Stop the container.
7. Restart the Container.
8. Kill the container.
9. Destroy the container.

Q) What are the various states that a Docker container can be in at any given point in time? 
There are six states that a Docker container can be in, at any given point in time. Those states are as given as follows:
Ø  Created
Ø  Restarting
Ø  Running
Ø  Paused
Ø  Exited
Ø  Dead

Ref Link: https://roytuts.com/what-are-the-possible-states-of-docker-container/

Q) What is Containerization?
In the software development process, code deployed on one machine might not work perfectly fine on any other machine because of dependencies. This problem was solved by the containerization concept.
Basically, an application that is being developed and deployed is bundled and wrapped together with all its configuration files and dependencies. This bundle is called a container. Containerization is the process of packaging application code with its required libraries, frameworks, and configuration files so that it can be run efficiently and seamlessly in any environment.  
The containerization environments are Docker and Kubernetes. 

Q) Difference between COPY and ADD command.
COPY command copies files/directories from the host machine to the container’s file system.
ADD command also copies files/directories from the host machine to the container’s file system, other than this it also copies files from URL to destination directory under the container file system. ADD command also copies tar file to destination directory by automatically extracting the content.

Q) Available Docker Network Drivers?
Docker comes with a built-in network drivers are known as Native Network Driver and those are:

1. Bridge
2. Host
3. Macvlan
4. Null
5. Overlay

Q) Difference between CMD and ENTRYPOINT instruction?
CMD instruction allows you to set a default command and default parameters which will be executed when docker is run.
ENTRYPOINT instruction should be used when you need your container to be run as an executable.

Q) Difference between ENV and ARG?
ENV is for future running containers. ARG for building your Docker image.
ENV is mainly meant to provide default values for your future environment variables. Running dockerized applications can access environment variables. It’s a great way to pass configuration values to your project.
ARG values are not available after the image is built. A running container won’t have access to an ARG variable value.

Q) What are the most common instructions in Dockerfile?
Some of the common instructions in Dockerfile are as follows:   
ØFROM: We use FROM to set the base image for subsequent instructions. In every valid Dockerfile, FROM is the first instruction.
ØLABEL: We use LABEL to organize our images as per project, module, licensing etc. We can also use LABEL to help in automation. In LABEL we specify a key-value pair that can be later used for programmatically handling the Dockerfile
ØRUN: We use RUN command to execute any instructions in a new layer on top of the current image. With each RUN command we add something on top of the image and use it in subsequent steps in Dockerfile.
ØCMD: We use CMD command to provide default values of an executing container. In a Dockerfile, if we include multiple CMD commands, then only the last instruction is used.

Q) Container Network Model (CNM).
Docker uses an architecture called Container Network Model (CNM) to manage networking for Docker containers.
1. Sandbox
2. Endpoint
3. Network
4. Driver
5. NetworkController 

Q) Docker Universal Control Plane.

Docker Universal Control Plane (UCP) is the enterprise-grade cluster management solution from Docker which helps you manage your Docker cluster and applications through a single interface.
Universal Control Plane include centralized policy management for all of your container, centralized role-based access control, user management, application cluster management, and the ability to organize your container as a service or stack.
It also includes secure image scanning, continuous monitoring of your image in the registry.

Q) What is Docker Trusted Registry(DTR)?
Docker Trusted Registry is an on-site, on-premise registry for centralized storage for all your container images. DTR is an enterprise-grade image storage solution from Docker. DTR is installed on-prem or in your own public cloud infrastructure. It works with Universal Control Plane. It allows you to securely store your Docker images so that you can easily track and manage your applications. Like UCP it's an easy-to-use web-based application. It has role-based access controls, so it supports multiple users and it allows your company to easily store all of your images on-premises in your own registry.

Q) What are the Control groups?
Docker Engine on Linux also relies on a technology called control groups (cgroups). A cgroup limits an application to a specific set of resources. Control groups allow Docker Engine to share available hardware resources to containers and optionally enforce limits and constraints. For example, you can limit the memory available to a specific container.
what a cgroup does is it provides resource accounting and limiting and it ensures that no containers exhaust the host's resources.

Q) Difference between replicated and global deployment?
For a replicated service, you specify the number of identical tasks you want to run. For example, you decide to deploy a Redis service with five replicas, each serving the same content. A global service is a service that runs one task on every node. There is no pre-specified number of tasks.

Q) Mount options available in docker?
1. Volume mount: it is managed by docker and is stored in a part of the host filesystem (stored at /var/lib/docker/volumes/ in Linux).
2. Bind mount: it may be stored anywhere on the host system.
3. tmpfs: Stored only in a host’s system memory in Linux.

Q) Difference between docker stop and docker kill?
#docker stop <container-id>: will send SIGTERM (terminate) signal and then SIGKILL signal after a grace period of 10 secs to the process running inside the container leading to a gracefull stop. 
#docker kill <container-id>: will send SIGKILL signal to the process running inside the container causing abruptly stop the container.

VPC Creation Using VPC Wizard Scenario 2

Scenario 2: VPC with the Public and Private Subnet

In this scenario, we are going to create VPC with single public subnet using VPC Wizard.

1. Go to VPC Dashboard on AWS Web Console and click on Start VPC Wizard.


2. Choose VPC with public and private subnet and then choose select.



3. Provide the details for creating VPC as follows.

IPv4 CIDR block: 10.0.0.0/16 (Default AWS provide CIDR block as 10.0.0.0/16).

IPv6 CIDR block: No (Default it is selected as NO).

VPC name: Pranav-VPC2 (Provide VPC Name as you like).

Public subnet's IPv4 CIDR: 10.0.1.0/24 (This will provide the public CIDR block range).

Availability Zone: us-east-1a (Select the availability zone as you like or let AWS will decide).

Public subnet name: Public-1a (Provide subnet name).

Private subnet's IPv4 CIDR: 10.0.2.0/24 (This will provide the public CIDR block range).

Availability Zone: us-east-1b (Select the availability zone as you like or let AWS will decide).

Subnet name: Public-1b (Provide subnet name).

Specify the allocation ID for an Elastic IP address in your account, for NAT gateway.

Enable DNS hostnames: Yes (Default it is selected as yes so that instances can be accessed using DNS hostname).

Hardware tenancy: Default 

After providing all the details click on Create VPC. Within few seconds you have VPC created as per your requirement.


4. Enable Auto assign Public IP for public subnet.

By default the subnet which is created will have “Auto assign public IP” attribute set to No, This is because the subnet is non default subnet created using VPC Wizard.



In order to access the instances launched into the Public Subnet must have public IP assigned to it. To enable “Auto assign public IP” attribute we need to modify the auto-assign IP settings.

Under VPC dashboard, in navigation pane choose Subnets.

Select your subnet and choose Subnet Actions, Modify auto-assign IP settings.
Click on check box to select and then press save.




Important Points:
1. In this scenario, after creating VPC using VPC wizard, AWS will create two subnets, public and private, Internet Gateway (IGW) that allows instances in public subnet to communicate with the internet and other AWS services and NAT Gateway with its own Elastic IP address allows the instances in private subnet to connect to the internet.
2. It creates two route tables:
  One is the Main Route table associated with private subnet which has local route that allows the instances to communicate within VPC and second route allows instances in private subnet to connect to the internet through NAT Gateway.
  Second is Custom (No Main) associated with public subnet which have two routes added to it. One which allows instances to communicate within VPC and other one has route that allows instances to communicate with internet through internet gateway (IGW).
3. Public subnet created using VPC wizard is the non-default subnet, having “Auto-assign Public IP” and “Auto-assign IPv6 address” attributes set to NO (false).

VPC Creation Using VPC Wizard Scenario 1

VPC with a Single Public Subnet

Under VPC Wizard we have 4 options available to us and those are:
1. VPC with a Single Public Subnet
2. VPC with Public and Private Subnets
3. VPC with Public and Private Subnets and Hardware VPN Access
4. VPC with a Private Subnet Only and Hardware VPN Access

In this scenario, we are going to create VPC with single public subnet using VPC Wizard.

1. Go to VPC Dashboard on AWS Web Console and click on Start VPC Wizard.


2. Choose VPC with a single public subnet and then choose select.



3. Provide the details for creating VPC as follows

IPv4 CIDR block: 192.168.0.0/16 (Default AWS provide CIDR block as 10.0.0.0/16).

IPv6 CIDR block: No (Default it is selected as NO).


VPC name: Pranav-VPC1 (Provide VPC Name as you like).

Public subnet's IPv4 CIDR: 192.168.1.0/24 (This will provide the public CIDR block range).

Availability Zone: us-east-1a (Select the availability zone as you like or let AWS will decide).

Subnet name: Pranav-VPC1-Public Sub (Provide subnet name).

Enable DNS hostnames: Yes (Default it is selected as yes so that instances can be accessed using DNS hostname).

Hardware tenancy: Default


After providing all the details click on Create VPC. Within few seconds you have VPC created as per your requirement.




4. Enable Auto assign Public IP.
By default the subnet which is created will have “Auto assign public IP” attribute set to NO, This is because the subnet is non-default subnet created using VPC Wizard.



In order to access the instances launched into the Public Subnet must have public IP assigned to it. To enable “Auto assign public IP” attribute we need to modify the auto-assign IP settings.
Under VPC dashboard, in navigation pane choose Subnets.
Select your subnet and choose Subnet Actions, Modify auto-assign IP settings.
Click on the check box to select and then press save.




Important Points:
1. In this scenario, after creating VPC using VPC wizard, AWS will create Internet Gateway (IGW) that allows instances in public subnet to communicate with the internet and other AWS services.
2. It creates two route tables:
  One is the Main Route table which has a local route that allows the instances to communicate within VPC and it has no subnet associated with it.
  Second is Custom (No Main) which have two routes added to it. One which allows instances to communicate within VPC and other one has a route that allows instances to communicate with internet through internet gateway (IGW).
 Custom (No Main) route table has one subnet associated with it.
3. Subnet created using VPC wizard is the non-default subnet, having “Auto-assign Public IP” and “Auto-assign IPv6 address” attributes set to NO (false).

Gentoo Installation Step by Step

1. Boot the system with Gentoo-minimal ISO CD.

Download Gentoo ISO (Minimal) from https://www.gentoo.org/downloads/ site.

Burn the CD and boot the system.

2. Determine interface name using ifconfig command.

In my case, it is “eno16777728”. Configure the network interface. IP will change according to your network.

# ifconfig eth0 192.168.1.109 broadcast 192.168.1.255 netmask 255.255.255.0 up
# route add default gw 192.168.1.1

Add the following entry in resolve.conf file.

# nano /etc/resolv.conf
nameserver 192.168.1.1
nameserver 8.8.8.8


3. Start sshd service.

To do the installation over ssh, start the sshd service and provide the root password.

#/etc/init.d/sshd start
# passwd


4. Create partitions as per the requirement.
In my case, I am going to create following partitions as on my virtual machine I am having only 20 GB of /dev/sda disk size.
Partitions and its size will vary depending on your system.

1. /boot -- 500M
2. /          -- 18G
3. swap   --  1024M


5. Formatting partitions.

Now Format created partitions with the supported filesystem(here formatted with ext4 filesystem).

#mkfs.ext4 /dev/sda1


#mkfs.ext4 /dev/sda2


Activate the swap partition.

#mkswap /dev/sda3
#swapon /dev/sda3


6. Setting date.

Check date and time of the system. In case of time desynchronization use following command to set time.

#date MMDDhhmmYYYY

7. Mounting root partition.

Mount the root and boot partition under /mnt/gentoo.

#mount /dev/sda2 /mnt/gentoo
#mkdir /mnt/gentoo/boot
#mount /dev/sda1 /mnt/gentoo/boot




8. Downloading stage3 tarball.

Download stage3 tar from https://www.gentoo.org/downloads/
Once downloaded dump it into /mnt/gentoo. 


Now unpack the tar ball under /mnt/gentoo directory.

#tar xvjpf stage3-*.tar.bz2 --xattrs --numeric-owner
After extracting stage3 tar ball it will look like in below image.



9. Copy dns info.

Before entering the new environment copy the DNS information in /etc/resolv.conf.

#cp -L /etc/resolv.conf /mnt/gentoo/etc/

10. Mounting the necessary filesystems.

Mount the /proc, /sys and /dev directories to /mnt/gentoo installation system path, as this contains all the important hardware information of your system gathered by the kernel when the live CD is booted.

#mount -t proc /proc /mnt/gentoo/proc
#mount --rbind /sys /mnt/gentoo/sys

#mount --rbind /dev /mnt/gentoo/dev



11. Entering the new environment

Now go to the chroot environment, load previous system settings provided by /etc/profile file and change $PS1 Command Prompt.

#chroot /mnt/gentoo /bin/bash
#source /etc/profile
#export PS1="(chroot) $PS1"



12. Install ebuild repository snapshot from the web.

#emerge-webrsync


13. Choosing the right profile.

After Portage finishes synchronization select a profile for your future system destination.

#eselect profile list

I am going to select default profile i.e. 1

#eselect profile set 1

14. Setting time zone.
Next, configure your system Time Zone.

# ls /usr/share/zoneinfo
# cp /usr/share/zoneinfo/Asia/Kolkata /etc/localtime
# echo " Asia/Kolkata " > /etc/timezone


15. Configuring locales.

Configure Locales by uncommenting your preferred language from /etc/locale.gen file using the following series of commands.

#nano  /etc/locale.gen

Uncomment your system locale, I have uncommented below one.

en_US.UTF-8 UTF-8

run locale-gen command to generate all the locale specified in /etc/locale.gen

#locale-gen


Now reload the environment.

#env-update && source /etc/profile


16. Installing the sources.

#emerge --ask sys-kernel/gentoo-sources

17. Installing pciutils.
#emerge --ask sys-apps/pciutils


18. Configuring Linux kernel.

Go to the kernel source directory and execute make menuconfig.

#cd /usr/src/linux
#make menuconfig


Now configuration screen will appear on the terminal. The Linux kernel configuration has many, many sections. Select/Verify appropriate modules has been selected or not. Select if not and finally save the configuration.


Exit the configuration and start the compilation process

#make && make modules_install
#make install



Copy the kernel image file to the boot directory.

#cp arch/x86_64/boot/bzImage /boot/kernel-4.12.5-gentoo


19. Open /etc/fstab file and add the following content.

Next step is to configure fstab file to automatically mount system partitions during the boot process.


20. Installing system bootloader.

To make Gentoo start after reboot install GRUB Boot Loader on your first hard disk and generate its configuration file by running the following commands.

#emerge sys-boot/grub


#grub-install /dev/sda
#grub-mkconfig -o /boot/grub/grub.cfg


21. Set the hostname.


Set a hostname for your system by editing /etc/conf.d/hostname file.  



22. Install DHCP client.

Configure your network settings with DHCP install dhcpcd Client.
rc-update will add it in system startup process.

#emerge net-misc/dhcpcd

#rc-update add dhcpcd default


23. Install other important packages.

#emerge virtual/ssh
#emerge syslog-ng
#emerge cronie
#emerge mlocate
#rc-update add sshd default
#rc-update add syslog-ng default
#rc-update add cronie default
#emerge sudo
#emerge net-misc/netkit-telnetd
#emerge tcpdump

24. Provide root password in chroot environment.

#passwd


25. Rebooting the system

Exit the chrooted environment and unmount all mounted partitions.

#exit
#cd
#umount -l /mnt/gentoo/dev{/shm,/pts,}
#umount -R /mnt/gentoo
#reboot




Reference Link: https://wiki.gentoo.org/ and https://www.tecmint.com/