Showing posts with label Docker. Show all posts
Showing posts with label Docker. Show all posts

Docker Interview Questions: Part 2

Q) How to keep the container alive, even when Docker Daemon is down?
By default, when the Docker daemon terminates, it shuts down running containers. You can configure the daemon so that containers remain running if the daemon becomes unavailable. This functionality is called live restore. The live restore option helps reduce container downtime due to daemon crashes, planned outages, or upgrades.
 
Add the configuration to the daemon configuration file. On Linux, this defaults to /etc/docker/daemon.json
{
  "live-restore": true
}
Ref Link: https://docs.docker.com/config/containers/live-restore/

Q) How to view the log for the last one hrs, logs for a particular date, tail the log of the container continuously?
To view log for last 1hr: # docker logs --since 1h <container-id>
To view log for particular date: #docker logs --until yyyy-mm-ddThh:mm:ss <container-id>         
To view log continuously:   #docker logs --follow <container-id>

Q) How to get the IP address and gateway details of the container?
#docker inspect --format '{{ .NetworkSettings.IPAddress }}' <container-id>
#docker inspect --format '{{ .NetworkSettings.Gateway }}' <container-id>
#docker inspect <container-id>|grep –wm1 "IPAddress"| cut -d '"' -f4
#docker inspect <container-id>|grep –wm1 "Gateway"| cut -d '"' -f4

Q) Explain the below command, their difference and purpose
#docker run -d --read-only -it --tmpfs /app/tmp voiptempdata

Above command will run container with read-only root file system and tmpfs mount on target directory “/app/tmp“. You can write to the directory as tmpfs creates file outside containers writeable layer. 
The --tmpfs flag does not allow you to specify any configurable options.
The --tmpfs flag cannot be used with swarm services. Its is for standalone
container. 

#docker run -d -it --name voiptempdata --mount type=tmpfs,destination=/app/tmp voipasterix

Above command will run container named “voiptempdata” with tmpfs mount on
target directory “/app/tmp“
The --mount flag allow you to specify any configurable options.It consists of
multiple key-value pairs, separated by commas.
The --mount flag is compatible with swarm services.

Ref Link: https://docs.docker.com/storage/tmpfs

Q) What is the use of tmpfs mount and where it resides? Is it possible to share them between containers?
When you don’t want to store the container’s data on the host machine and also don’t want to write data into the container's writable layer then you can use tmpfs mount option for the container.
This is useful to temporarily store sensitive files that you don’t want to persist in either the host or the container writable layer.
tmpfs mount is temporary and only persisted in the host memory. When the container stops, the tmpfs mount is removed, and files are written there won’t be persisted.
you can't share tmpfs mounts between containers.

Ref Link: http://docs.docker.oeynet.com/engine/admin/volumes/tmpfs/

Q) When to use Volume and When to use Bind Mounts?
Docker provides two options for the container to store their data on the host machine, so that data can be persisted even after the container stops and those are
Volume mounts and Bind mounts
Volumes are stored in a part of the host filesystem which is managed by Docker. The non-Docker process on Docker hosts can not modify this part of the filesystem.
Bind mounts may be stored anywhere on the host system. The non-Docker process on Docker host or docker container can modify them at any time.
The use of Volume and Bind mounts depends on your application requirements. If you want that everything should be managed by docker then use volume mount and if you want to use your own directory structure managed by you then use bind mount.
As the bind mount depends on the directory structure of the host machine, it has the potential of failure where as volume mount is managed by docker there is no chance of failure. 

Ref Link: http://docs.docker.oeynet.com/engine/admin/volumes/#choose-the-right-type-of-mount

Q) Explain the below commands and their purpose
#docker run -it –name voip1 -v voipdata:/datav voipserver

The above command will run a container with a volume that does not exist. In this case, a volume “voipdata” will be created and mounted on “/datav” inside container filesystem named “voip1”.

#docker run -it –name voip2 --volumes-from voip1 voipserver

The above command will run a container with a volume referenced from another container. In this case, a volume that is referenced from “voip1” will be mounted inside the container filesystem named “voip2”.

Ref Link: https://docs.docker.com/engine/reference/commandline/run/#mount-volumes-from-container---volumes-from

Q) How to run the containers only on manager node?
#docker service create --replicas=3 --constraint="node.role==manager" <image>

Q) Write a sample services section in Docker compose file for 3 replicas, worker node role and to restart on failure?
 
version: "3.8"
services:
  web:
    image: httpd:alpine
    ports:
      - 80:80
    deploy:
      placement:
        constraints:
          - "node.role==worker"
      mode: replicated
      replicas: 3
      restart_policy:
        condition: on-failure

Q) What are the types of logging driver available for docker? What is the default one and how to limit size of the log file?
There are different logging drivers available for docker, like none, local, json-file, syslog, journal etc. Below is the link for supported logging driver in docker.
supported-logging-drivers
 
The default logging driver of Docker for Linux distributions is “json-file”.

To limit size of log file set “max-size” value in “log-opts” configuration options in the daemon.json
 
{
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "10m"
      }
}

Q) What is difference between below commands?
CMD [“/appboot.sh”] à This form is know as exec form of CMD,in this the <command> is expressed as JSON array.
CMD /appboot.sh  à This form is know as shell form of CMD,in this the <command> will execute in “/bin/sh -c “
 
Ref Link: https://docs.docker.com/engine/reference/builder/#cmd

Docker Command Line / Docker Cheat Sheet

########## Docker ########## 

## To pull the image from registry

docker pull <registry>/<repository>:<tag>
docker pull docker.io/busybox:latest

## To list images on the host machine

docker image ls
docker images

## To run container in detached mode 

docker container run --detach --name <name-to-container> <container-name>
docker container run -d --name <name-to-container>  <container-name>

## To run container in interactive mode 

docker container run --tty --interactive --name <name-to-container> <container-name>
docker container run -it --name <name-to-container> <container-name>

## To execute comand on running container

docker container exec --tty --interactive  <name-to-container> <cmd-to-run>
docker container exec -it <name-to-container> <cmd-to-run>

## To inspect docker container

docker container inspect <container-name>

## To list running containers 

docker container ls

## To list all the containers including running, exited 

docker ps 
docker ps -a
docker container ls -a
docker container ls -all

## To list all the containers with exit statue 

docker ps -a --filter "status=exited"
docker container ls -a --filter "status=exited"

## To list all the containers with running status 

docker ps --filter status=running
docker container ls --filter status=running

## To list container id's 

docker container ls --all --quiet
docker container ls -a -q

## To check the stats  

docker container stats <container-id>

## To check the logs

docker container logs <container-id>

## To check process running inside container

docker container top <container-id>

## To check disk space that docker is using

docker system df

## To remove stopped containers, unused volumes, networks, and dangling images

docker system prune

## To remove dangling images

docker image prune

## To remove stopped containers

docker container prune

## To List all networks

docker network ls 

## To create network

docker network create <network-name>
docker network create -d <driver> <network-name>  
docker network create --driver <driver> <network-name> 

## To display detailed information of network

docker network inspect <network-name> 

## List port mappings for the container

docker container port <container-id>

## To Remove one or more networks

docker network rm <network-name>

## Create volume

docker volume create <vol-name>

## Bind Mount local directory to container 

docker container run --mount type=bind,source=<source-path>,target=<target-path> <image-name>
docker container run -v <source-path>:<target-path> <image-name>

## Mount local directory to container 

docker container run --mount type=volume,source=<vol-name>,target=<target-path> <image-name>
docker container run -v <vol-name>:<target-path> <image-name>

## To run container with restart policy

docker container run -d --restart always <image-name>
docker container run -d --restart on-failure <image-name>
docker container run -d --restart unless-stopped <image-name>

## To create docker secret

echo "<secret>" | docker secret create <my_secret> -
echo "pass123" | docker secret create db_pass -

## To create docker secret using file

docker secret create <my_secret> <file-name>
docker secret create db_pass pass-file.txt

## To list the secrets in docker

docker secret ls

## To inspect secret

docker secret inspect <my_secret>
docker secret inspect db_pass

## To removes a secret

docker secret rm <my_secret>
docker secret rm db_pass


########## DOCKER COMPOSE ##########

## To create and start the container 

docker-compose up

## To create and start the container in detached mode

docker-compose up --detach
docker-compose up -d

## To List all the containers

docker-compose ps

## To Display services

docker-compose ps --services

## To scale particular service in docker-compose

docker-compose up --detach --scale <service-name>=<count>

## Stops containers and removes containers, networks, volumes, and images created 

docker-compose down

## To Validate and view the Compose file

docker-compose config

##List images used by the created containers

docker-compose images

## To view logs output from services

docker-compose logs
docker-compose logs --tail=10

## To stop running containers without removing them

docker-compose stop

## To start running containers for service

docker-compose start

## Displays the running processes

docker-compose top


########## DOCKER SWARM ##########

## To initialize swarm mode 

docker swarm init --advertise-addr <IP-Address> 

## To create Token for Worker/Manager

docker swarm join-token worker
docker swarm join-token manager

## To list swarm nodes in the cluster

docker node ls

## To leave worker node from the swarm

docker swarm leave

## To remove worker node from the swarm

docker node rm <node-name>

## To promote node to worker

docker node promote <node-name>

## To demote node to worker

docker node demote <node-name>

## To update role of node 

docker node update --role <manager|worker> <node-name>

## To create service 3 replicas 

docker service create --name <service-name> --replicas <no-of-replicas> <image-name>
docker service create --name web-server --replicas 3 nginx:latest

## To adds a published service port to an existing service

docker service update --publish-add published=<hport>,target=<cport> <service-name>
docker service update --publish-add published=8080,target=80 web-server

## To update no. of replicas 

docker service update --replicas=<count> <service-name>
docker service update --replicas=3 web-server

## To check status of running service

docker service ps <service-name>
docker service ps web-service

## To check logs of service

docker service logs <service-name>
docker service logs web-server

## To scale replicas of service

docker service scale <service-name>=<no-of-replicas>
docker service scale web-server=6

## To run one task for the service on every available node in the cluster

docker service create --name <service-name> mode=global <image-name>
docker service create --name web-server mode=global busybox

## To update service to use new docker image

docker service update --image <new-image> <service-name>
docker service update --image nginx:alpine web-server

## To create service on Manager Node only

docker service create --constraint="node.role==manager" <image-name>

## To create service on Worker Node only

docker service create --constraint="node.role==worker" <image-name>


How to create custom network with specific subnet and IP range

Task:

Create a custom network with default bridge driver named as my-custom-net with subnet 10.100.0.0/16 gateway 10.100.0.1 and IP range 10.100.2.0/24.
Create a container named as net-test with custom network i.e my-custom-net.
Inspect the container net-test and check the IP address assigned to it.

1. Create a custom network with custom IP settings.

#docker network create --subnet 10.100.0.0/16 --gateway 10.100.0.1 --ip-range 10.100.2.0/24 --driver bridge --label host2net my-custom-net                             

2. Inspect the custom network.

#docker network inspect my-custom-net                                                           

Check the Subnet, Gateway, IP Range and Label assigned to the network.


3. Launch the container with the custom network.  

#docker run -itd --name test1 --net my-custom-net centos:centos7 bash             

4. check container IP with docker inspect command.

#docker container inspect test1| grep -w "IPAddress"                                         

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. 













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.