Showing posts with label Container. Show all posts
Showing posts with label Container. Show all posts

Shell Script to find Container IP


I developed a shell script to find container IP running on the host machine. This script takes an argument from a user which is "all" either "container name" and based on that it provides IP of containers

Find repo here (find_IP_Address.sh)

In this tutorial, I am gonna explain my script to understand how it works!
as I mentioned my Script name above, run the command below to get help to find out what would be given as an argument. 
find_IP_Address.sh --help--Parameters -> <Name of the container> or <All>--Sample -> sh find_IP_Address <Parameters>
It is not the case I want to explain. I want to Explain how it finds IP for the given argument.

Let's dig the code!

Below code print all containers name and its IP. let see how it is extracting those output.
elif [ "$1" = "All" ]
then
	for container in $(docker ps --format '{{.Names}}')
	do
		for ipadd in $(docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}} {{end}}' $container)
		do
		echo "IP address of $container container :  $ipadd"
		done
	done
we know docker ps command print running containers and --format pretty-prints container output using a Go template (print its value without header)

$ docker ps

CONTAINER ID        IMAGE                        COMMAND                CREATED              STATUS              PORTS               NAMES
4c01db0b339c        ubuntu:12.04                 bash                   17 seconds ago       Up 16 seconds       3300-3310/tcp       webapp
d7886598dbe2        crosbymichael/redis:latest   /redis-server --dir    33 minutes ago       Up 33 minutes       6379/tcp            redis,webapp/db

$ docker ps --format '{{.Names}}'
 webapp
 redis,webapp/db
So the command, for container in $(docker ps --format {{.Names}}') command stores each container names

let see how we extracting each container IP.
As we know docker inspect <containerid> print Jason format output below
$ docker inspect 52249ba75f0f
[
    {
        "Id": "52249ba75f0fa33f93202f4a2d7f83bc71600b8b75ea4db0bc5b56022bf254b6",
        "Created": "2017-11-17T14:38:05.340313315Z",
        "Path": "/bin/bash",
        "Args": [],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 1535,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2017-11-17T14:38:05.638951265Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        }
        .......
To Extract containers IP again the --format command comes to rescue us!

for ipadd in $(docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}} {{end}}' $container)

# {{range.NetwokSetting.Networks}}{{.IPAddress}} extract container IP
# ipadd store ip of container
# Container name passed as container varible in for parent for loop
So the command for ipadd in $(docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}} {{end}}' $container)  command to stores each container IP address

Then, echo "IP address of $container container :  $ipadd" Used to print out Container name and its IP

Viola!

find the full code here

That's pretty much it for TODAY, PEACE

References

https://docs.docker.com/engine/reference/commandline/inspect/










Docker Cheats

This article will be your one-stop-shop for Docker, going over some of the best practices and must-know commands that any user should know.

What is and Why Docker?
Docker is an open-source platform for wrapping up the software and its dependencies using “containerization” to make them more portable and easier to deploy.
So, the above definition tells what and why but! 

Why Docker Instead of VMs? What’s the Big Deal?

We know that VMs are a good choice for running apps that require all of the operating system’s resources and functionality and application's libraries and dependencies bounded with guest os.

let's say, applications you’ve built. If you want each app to be isolated, you will need to run each one inside of its own guest operating system. because of the binaries and libraries needs to run the application is not isolated. Though, it leads to the major issue.

if I want to run  30 applications and its need 30 virtual machines, you’ve got to boot 30 operating systems with at least minimum resource requirements available before factoring the hypervisor for them to run on with the base OS.

If you have Docker then you can have 30 containers that you want to run, you can run them all on a single virtual machine because its package all the dependencies and also make it portable.

So, Containers are a better choice than VMs when our biggest priority is maximizing the number of applications running.

Docker Commands and Practices
Here’s a quick overview of the vocabulary you should know.

Docker Image: Docker image is created at build time.
Docker Container: The Docker container is created at run time.
Docker File: The Dockerfile is at the heart of Docker. The Dockerfile tells Docker how to build the image that will be used to make containers.

I'll do another blog on how to create a docker image using a docker file.

Docker Commands

Find the version
docker --version or docker -v
Login to docker hub
docker login

Pull an image from the Docker Hub repository
docker pull <image>

Push an image to the Docker Hub repository
docker push <username/image>

Search the Docker Hub repository for a particular term
docker search <term>

Create a target tag or alias that refers to a source image
docker tag <source> <target>

Build an image from working directory
docker build -t <imagename> .
. refers workdir
-t optionally a tag in the ‘name:tag’ format
Ex: docker build -t flask:latest .

Build image for any locations docker file
docker build -t <imagename> -f <docker file path>/<url>
Ex: docker built -t flask -f /path/to/docker/Dockerfile .
EX: docker built -t flask -f github.com/5sfayas/IGm

See list of created images
docker images
docker image ls

Run the docker image
docker run <imagename>
docker run -d -p 80:8080 flask

-d run in the background -p assing port to container flask is imagename

Specify an ip-address for the container when running (See Network Related Section Below)
docker run -i -d --name=rc --net br0 --ip 192.168.0.104

Assing network type and ip to container
docker run it -add-host=example.com:10.1.1.2
---add-host flag is used to add a single hots to ip withing the docker container. this make entry in /etc/hosts file to make fqdn for container.

Remove a container upon exit
docker run --rm <image_name>

Remove docker by image name
docker rmi <image_name>

List running containers
docker ps

List all exited containers 
docker ps -aq -f status=exited

Get all low-level details of the container (including IP address)
docker inspect <containerId>

This throws lots of information and its useful to find IP of container.

Note: later I'll write a simple blog to find IP of the container

Get logs of the container
docker logs <containerId>
very useful to find out what happened to a container

Kill and Remove container
Kill Container
docker kill <containerId>

This will stop a running container
docker kill ${docker ps -q}
kill all container

Remove stopped containerdocker rm <containerId>
This remove and clean container(running, stopped)
Run container then remove it
docker run rm <imagename>

Create and start container with terminal interaction 
docker run -ti <imagename>

The useful to run bash command to container
docker run -ti <>imagename> <command>
docker run -ti <>imagename> /bin/bash

Inspect network
Docker Newtwork ls
Verify network through the inspect commanddocker network inspect br0


find the code notpad file here