Tag Archives: DevOps

Mastering the users command in Linux with Examples

Introduction

In Linux, user management is a fundamental part of system administration, especially when it comes to monitoring active user sessions. The users command is one of the simplest yet effective tools for this purpose. With just a single command, you can instantly view who is logged into your system, making it a valuable utility for Linux administrators.

In this article, we will delve deep into the users command -its basic syntax, practical use cases, and advanced examples that show how you can automate user session monitoring. Whether you’re a beginner or an experienced administrator, you’ll find useful insights into how this command fits into everyday Linux administration.

What is the users Command in Linux?

The users command is a Linux utility that displays the usernames of all users currently logged into the system. It fetches this data from the /var/run/utmp file, which keeps track of all active sessions. This simple tool is invaluable for monitoring who is using the system at any given moment, especially when maintaining or troubleshooting multi-user environments.

Why Use the users Command?

The users command is useful for:

  • Quickly checking which users are currently logged in.
  • Monitoring user sessions during system maintenance.
  • Tracking user activities for security purposes.

While it seems straightforward, the users command can be enhanced and combined with other Linux commands to create powerful user management tools.

Basic Syntax of the users Command

The basic syntax for the users command is extremely simple:

users

When you run this command, it will display a space-separated list of usernames currently logged into the system. No options or additional parameters are required.

Example

$ users
root admin user1

This example shows that three users – root, admin, and user1 – are currently logged in.

Practical Use Cases of the users Command

Now, let’s explore some practical use cases where the users command comes in handy.

Example 1: Basic Usage

To see all currently logged-in users, simply run:

$ users
john mary admin

This provides a quick overview of who is using the system.

Example 2: Combine with the who Command for Detailed Info

If you need more information, like the terminal or login time, you can use the who command. The who command provides detailed user session data such as the terminal (pts/), login time, and remote host IP:

$ who
john     pts/0        2023-10-05 09:15 (192.168.1.100)
mary     pts/1        2023-10-05 09:20 (192.168.1.101)
admin    pts/2        2023-10-05 09:25 (192.168.1.102)

This shows the login times and other session details, which can be useful for system monitoring.

Count the number of logged-in users:

users | wc -w

By piping the output of the users command to wc -w, we can count the number of words in the output, which corresponds to the number of logged-in users.

Check if a specific user is logged in:

users | grep <username>

Check if a user is logged in and display a custom message:

if users | grep -q <username>; then echo "<username> is logged in"; else echo "<username> is not logged in"; fi

Advanced Examples with the users Command

The true power of Linux commands comes from combining simple commands with more advanced tools or integrating them into scripts. Let’s look at some advanced examples of using the users command.

Example 3: Count the Number of Logged-In Users

To count how many users are currently logged into your system, combine the users command with wc -w (word count):

$ users | wc -w
3

This counts the total number of words (usernames) output by the users command, showing that three users are logged in.

Example 4: Search for a Specific User

If you want to check if a specific user, like john, is logged in, you can use grep with the users command:

$ users | grep john
john

If john is logged in, his name will appear in the output. If he is not logged in, you’ll get no output.

Example 5: Monitor Users Continuously with watch

The watch command allows you to continuously execute the users command, refreshing every two seconds by default:

watch users

This command will update the list of logged-in users in real time, which is useful for monitoring systems under heavy use or tracking session changes during maintenance.

Automation and Scripting with the users Command

The users command can also be integrated into shell scripts for more complex automation tasks, such as user activity tracking or system monitoring.

Example 6: Create a Shell Script to Alert When Multiple Users Are Logged In

Below is a simple shell script that checks the number of logged-in users and sends a warning if there are more than three users:

#!/bin/bash

logged_in_users=$(users | wc -w)

if [ $logged_in_users -gt 3 ]; then
    echo "Warning: More than 3 users are logged in!"
fi

This script is a basic example of automating system monitoring by counting users and triggering an alert based on specific conditions. You can customize this further to send alerts via email or log events.

Additional Commands for User Monitoring

While the users command is excellent for a quick snapshot of logged-in users, you may need more detailed insights in some scenarios. Here are a few other commands that complement the users command:

1. The who Command

The who command offers more comprehensive information about logged-in users, including the terminal, login time, and remote IP:

$ who

2. The w Command

The w command displays not only the list of logged-in users but also what they are currently doing. It shows CPU usage, terminal details, and more:

w

Example Output:

09:23:31 up 1:12,  3 users,  load average: 0.08, 0.05, 0.01
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
john     pts/1    192.168.1.100    09:21    1:12   0.01s  0.00s bash
mary     pts/2    192.168.1.101    09:23    0.02s  0.03s  0.01s vim
admin    pts/3    192.168.1.102    09:24    0.03s  0.02s  0.01s sshd

3. The last Command

The last command displays a log of all user login and logout events. It is useful for auditing and tracking user activity over time:

$ last
john     pts/0    192.168.1.100    Thu Oct  5 09:15   still logged in

Frequently Asked Questions (FAQs)

What does the users command do?

The users command in Linux shows a list of all users currently logged into the system by fetching data from the /var/run/utmp file.

Can the users command show login times or session details?

No, the users command only displays usernames. For more details like login times, use the who or w command.

How do I count the number of logged-in users?

You can count the number of logged-in users by using the users command combined with wc -w:

users | wc -w

Can I monitor users in real-time?

Yes, you can use the watch command with the users command to monitor logged-in users in real-time:

watch users

Conclusion

The users command in Linux is a versatile tool for monitoring logged-in users and tracking session activity. Though it provides only basic information, it can be combined with other commands like who, w, and last for more detailed insights. Advanced users can even automate tasks by integrating the users command into shell scripts to create custom monitoring solutions.

Whether you are just starting with Linux or managing a complex server environment, understanding how to use it efficiently will make you a better system administrator. Explore the commands and examples shared here, and enhance your ability to manage user sessions effectively.. Thank you for reading the DevopsRoles page!

Git merge development branch to master branch

Introduction

In the world of software development, Git is a vital tool for version control, enabling teams to collaborate efficiently. One of the most common Git operations is merging a development branch into the master branch. This process ensures that the latest changes from the development branch are incorporated into the stable master branch. In this guide, we’ll cover everything you need to know about how to Git merge development branch to master branch, including best practices, conflict resolution, and real-world examples.

Understanding Git Branches

What Are Git Branches?

Git branches allow developers to work on different features, bug fixes, or experiments without affecting the stable codebase. The master branch (or main, as renamed in newer Git versions) serves as the main production branch, while the development branch is used for active feature development and testing.

Why Merge Development Branch to Master?

  • Integrate new features: Ensure tested features are available in production.
  • Maintain a clean codebase: Keep a structured development workflow.
  • Improve collaboration: Merge approved code into the main branch.
  • Reduce conflicts: Regular merges prevent large, conflicting changes.

Steps to Merge Development Branch to Master Branch

Step 1: Switch to Master Branch

Before merging, ensure you are on the master branch.

 git checkout master

Alternatively, for newer Git versions:

 git switch master

Step 2: Update Master Branch

Before merging, update the master branch with the latest changes from the remote repository to prevent conflicts.

 git pull origin master

Step 3: Merge Development Branch

Run the merge command to integrate the development branch into the master branch.

 git merge development

If there are no conflicts, the merge will be successful.

Step 4: Resolve Merge Conflicts (If Any)

If there are conflicts, Git will prompt you to resolve them manually. Open the conflicting files, edit them as needed, and mark them as resolved.

 git add <conflicted-file>
 git commit -m "Resolved merge conflicts"

Step 5: Push the Merged Changes

Once the merge is complete, push the updated master branch to the remote repository.

 git push origin master

Best Practices for Git Merging

1. Keep Development Branch Updated

Regularly pull changes from the master branch into the development branch to minimize conflicts.

 git checkout development
 git pull origin master

2. Use Feature Branches

Instead of merging directly to the development branch, create separate feature branches and merge them into development before merging development into master.

 git checkout -b feature-branch

3. Test Before Merging

Run tests to ensure that the merge doesn’t introduce bugs.

 npm test   # Example for JavaScript projects

4. Use Pull Requests

For team projects, use pull requests (PRs) to review code before merging.

5. Avoid Merge Conflicts

Regularly pull changes and communicate with your team to prevent conflicts.

Advanced Git Merge Scenarios

Merging with a Rebase

Instead of a merge, you can use rebase to maintain a linear history.

 git checkout development
 git rebase master
 git checkout master
 git merge development

Squash Merging

Squash commits before merging to keep the history clean.

 git merge --squash development
 git commit -m "Merged development branch with squash"

Aborting a Merge

If you encounter issues, you can abort the merge and reset.

 git merge --abort

Frequently Asked Questions (FAQs)

1. What is the difference between git merge and git rebase?

  • git merge creates a new commit combining both branches.
  • git rebase moves the development branch commits on top of the master branch.

2. What happens if there is a merge conflict?

Git will notify you of conflicts, and you must manually resolve them before completing the merge.

3. How can I undo a merge?

If a merge was completed but needs to be undone:

 git reset --hard HEAD~1

Note: This will erase uncommitted changes, so use with caution.

4. How often should I merge development into master?

It depends on your workflow, but ideally, after features are fully tested and approved.

5. Should I delete the development branch after merging?

If the development branch is no longer needed, delete it to keep the repository clean:

 git branch -d development
 git push origin --delete development

External Resources

Conclusion

Merging the development branch into the master branch is a crucial step in maintaining a clean and organized Git workflow. By following best practices such as updating branches regularly, using feature branches, and resolving conflicts proactively, you can ensure a smooth and efficient development process. Mastering Git merge techniques will help you collaborate effectively with your team and maintain a high-quality codebase. I hope will this your helpful. Thank you for reading the DevopsRoles page!

Docker My Note: A Complete Reference Guide

Introduction

Docker is a popular tool in the DevOps field that simplifies the deployment and management of applications.

In this article, we will explore important notes about Docker, including basic concepts, common commands, and useful tips. Whether you are a beginner or have some experience, these notes will help you optimize your work with Docker. To learn more, visit Docker My Note.

Docker My Note: Your Go-To Guide for DevOps Success

Cannot connect to the Docker daemon. Is the docker daemon running on this host?

Solve the problem: Add this user to the docker group.

Detach and Attach

  • Detach : Ctrl-p + Ctrl-q
  • Attach: docker attach [container]

Why can not detach?

Solve the problem: docker run with “-i”, “-t” options. http://stackoverflow.com/questions/20145717/how-to-detach-from-a-docker-container

Docker runs without -it, but attach, so can not type CTRL-C

Close your terminal! Anything OK.

To safely detach…

Docker runs without “-i”, “-t” options. But you want to detach, if you hit Ctrl-C then the docker process be killed.
To avoid it, attach with

--sig-proxy=false

You want to log in to a container…

docker exec -it [container-name] /bin/bash

start on os-startup

docker command

 --restart=always

docker-compose add restart: always in docker-compose.yaml file

search a docker image in hub.docker.com

docker search nginx

Download a docker image from hub.docker.com

docker image pull <image_name>:<image_version/tag>

List out docker images from your local system

docker image ls

Expose your application to host server

docker run -d -p <host_port>:<container_port> --name <container_Name> <image_name>:<Image_version/tag>

List out running containers

docker ps

List out all docker containers (running, stpooed, terminated, etc…)

docker ps -a

Stop/Start a container

docker stop <container_id>

docker start <container_id>

Remove a container

docker rm <container_id>

Conclusion

Docker has become an indispensable tool in the modern DevOps toolkit. Through this article, we hope you have grasped the basic knowledge and useful commands to effectively apply Docker in your work. If you want to learn more and stay updated with the latest information about Docker, don’t forget to visit Docker My Note. Let Docker help you simplify and optimize your application deployment process.

A Beginner’s Guide to Git Clone Repository

Introduction

In this tutorial, we will guide you on how to git clone a repository and sync it to your server. Git is a popular version control system used by developers to manage source code and collaborate on projects efficiently.

To clone a Git repository, you need to have Git installed on your system. Follow these steps to clone a repository:

Prerequisites

  • Target: gitlab repository
  • Source: Server Linux

Steps to Clone a Git Repository

1. Install Git

Ensure Git is installed on your system. If not, install it using the following command:

sudo apt-get install git

2. Clone the Repository

To create a clone or copy of the target repository on your server, use the following command:

git clone https://huupv@https://gitlab.com/DevopsRoles/devopsroles.git

3. Switch Branches

To switch from the master branch to the develop branch, use:

git checkout develop

4. List All Branches

To list all the branches in your repository, execute:

git branch

5. Fetch and Merge Changes

To fetch and merge changes from the remote server to your working directory, run:

git pull

Conclusion

By following this guide, you can successfully clone a Git repository to your local machine. You can now navigate into the cloned repository and start working with the code or files it contains. We hope this guide is helpful. Thank you for reading the DevopsRoles page!

Docker compose example

Introduction

Docker compose is used to run multiple containers. In this tutorial, Using Docker compose example for NGINX and MYSQL. I used Docker compose version “3”

In today’s digital era, Docker has become an essential tool for developers and DevOps professionals. With its ability to package and deploy applications easily, Docker has revolutionized the way software is managed and deployed. However, as applications grow more complex, managing multiple containers simultaneously can be challenging. This is where Docker Compose shines. This article will guide you through Docker Compose with a practical example, making it easier to manage and coordinate multiple containers within the same application.

“Build, Manage and Secure Your Apps Anywhere. Your Way.” Quote from docker!

Docker compose example

Creating Docker-compose file. All docker compose file is a YAML file. Now, let’s go create the docker-compose.yml file as below

[root@DevopsRoles ~]# mkdir docker-instance
[root@DevopsRoles ~]# cd docker-instance/
[root@DevopsRoles docker-instance]# vim docker-compose.yml

The content docker-compose file as below

version: '3'

services:
 WEB01:
   image: nginx:latest
   container_name: "web01"
   hostname: web01
   ports:
        - "8888:80"
        - "8443:443"
        - "2233:22"
   #deploy:
   # resources:
   # limits:
   # memory: 512M
   #mem_limit: 512m
   volumes:
     - ./data_web01:/mnt_nfs
   networks:
     - bridge
   restart: always

 DB01:
   image: mysql:latest
   container_name: "db01"
   hostname: db01
   ports:
        - "33306:3306"
        - "2234:22"
   command: --default-authentication-plugin=mysql_native_password
   environment:
      MYSQL_ROOT_PASSWORD: 123456789
      #MYSQL_USER=huupv
      #MYSQL_PASSWORD=passforhuupv
      #MYSQL_DATABASE=DevopsRolesDB
   #deploy:
   # resources:
   #    limits:
   #      memory: 512M
   volumes:
      - ./data_db01:/mnt_nfs
   networks:
      - bridge
   restart: always

volumes:
   web_mnt_nfs:
     driver: local
networks:
   bridge:
     driver: bridge
     ipam:
       config:
          - subnet: 192.168.12.0/24

Creating and starting a container

[root@DevopsRoles docker-instance]# docker-compose up -d

The screen output terminal:

Creating network "docker-instance_bridge" with driver "bridge"
Creating db01 ... done
Creating web01 ... done

The result, Docker compose example

Access browser Nginx server

Checking running containers for nginx and mysql

Conclusion

Thought the article, you can use “Docker compose example” as above. Docker Compose is not just a convenient tool but also a key to simplifying and enhancing container management in any software project. Continue reading the article to gain a deeper understanding of how to use this tool in real-world scenarios! I hope will this your helpful. Thank you for reading the DevopsRoles page!

Bash string comparison

Introduction

In Bash scripting, comparing strings is an essential skill that allows you to check and manipulate input data. Unlike other programming languages, Bash has its own syntax and rules for handling string comparisons. In this article, we will explore how to use conditional expressions to compare strings in Bash. We will learn about common comparison operators, string handling techniques, and how to test strings under different conditions.

This guide aims to help you grasp the basics and provides practical examples that you can apply to your daily tasks. How do I use bash string comparison? In the bash shell use the if statement “==” to check equality and “!=” to check the inequality of the string. String comparison examples. The bash script is essential for DevOps Roles.

In bash, you can compare strings using various operators. Here are some common string comparison operators in bash:

  • = : Checks if two strings are equal
  • != : Checks if two strings are not equal
  • -z : Checks if a string is empty (has zero length)
  • -n : Checks if a string is not empty
  • < : Checks if one string is less than another string (in lexicographical order)
  • > : Checks if one string is greater than another string (in lexicographical order)

Bash string comparison use “==” operator

#!/bin/bash
STRA=huu
STRB="www.devopsroles.com"
if [[ "$STRA" == "$STRB" ]]; then
   echo "$STRA equal $STRB"
else
   echo "$STRA not equal $STRB"
fi

The screen output terminal:

Bash script string compare use “!=” operator

#!/bin/bash
STRA=huu
STRB="www.devopsroles.com"
if [[ "$STRA" != "$STRB" ]]; then
   echo "$STRA not equal $STRB"
else
   echo "$STRA equal $STRB"
fi

The screen output terminal:

Bash script string compare use wildcards

#!/bin/bash
STRA=huu
STRB="www.devopsroles.com"
if [[ "$STRA" == *$STRB* ]]; then
   echo "$STRA equal $STRB"
else
   echo "$STRA not equal $STRB"
fi

The screen output terminal:

Examples of string comparison in bash

Conclusion

In summary, comparing strings in Bash is a crucial skill that every Bash programmer needs to master. By using comparison operators and conditional expressions, you can effectively and accurately perform string checks and manipulations. Understanding how to compare strings not only helps you write more powerful scripts but also improves your ability to handle data and automate complex tasks.

Hopefully, this article has given you a comprehensive overview and the necessary knowledge to apply to your Bash projects. I hope will this your helpful. For more details refer to the Bash script.

How to install Ansible on Centos/ Ubuntu/Fedora

Introduction

In this tutorial, I guide how to install Ansible on Centos 7/ Ubuntu 14.04 / Fedora. Ansible is an Automation tool for IT Management. It’s useful for System Admin, and DevOps to build Automation Configure Management. Ansible the essential for DevOps Roles.

To install Ansible on CentOS, Ubuntu, or Fedora, you can follow the instructions below for each respective operating system:

Requirements

  • Control Machine: Run Ansible.
  • Remote server: Deploy and Configure such as Tomcat,  Nginx, Apache, and so forth from Control Machine.

Control Machine and remote server communication through SSH key Authentication.

How to install Ansible on Control Machine

For Centos 7 and RHEL 7

Open a terminal on your CentOS machine.

 # rpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
 # yum install ansible

For Ubuntu 14.04 / 15.04

 $ sudo apt-get install software-properties-common
 $ sudo apt-add-repository ppa:ansible/ansible
 $ sudo apt-get update
 $ sudo apt-get install ansible

Checking Ansible version

 $ ansible --version

For example, The output Ansible version

ansible 2.5.3
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/site-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.5 (default, Apr 11 2018, 07:36:10) [GCC 4.8.5 20150623 (Red Hat 4.8.5-28)]

That’s it! Ansible should now be installed on your CentOS, Ubuntu, or Fedora machine. You can start using Ansible to automate your IT infrastructure tasks.

Conclusion

Thought this article, How to install Ansible on Centos/Ubuntu and Fedora. In the next post, I installed and configured Nginx automation from Control Machine for the Remote server. Thank you for reading the DevopsRoles page!

Docker SSH into Container: A Complete Guide for Beginners and Advanced Users

Introduction

Docker containers have revolutionized the way developers build, ship, and manage applications. However, one common question arises: How do you Docker SSH into Container? While Docker doesn’t support traditional SSH access like physical servers, it provides a powerful alternative with the docker exec command. In this guide, we’ll explore step-by-step instructions on how to “SSH” into Docker containers from basic operations to more advanced use cases.

What is Docker SSH into Container?

Before diving into the practical steps, it’s important to clarify that Docker doesn’t actually use SSH for container access. Instead, Docker uses the docker exec command, which allows you to run commands or get an interactive shell inside running containers. This method is more efficient, secure, and tailored for containers than traditional SSH.

Why You Shouldn’t Use SSH for Docker Containers

  • Containers are lightweight: Adding an SSH server increases container size.
  • Docker has built-in tools: Using docker exec provides direct and simple access to containers without the overhead of SSH configuration.
  • Security: Running an SSH service in every container increases the attack surface. Docker’s approach with docker exec is more secure.

How to SSH into a Docker Container: Basic Method

Let’s start with the basics – getting into the shell of a running Docker container.

Step 1: List Running Containers

To view the currently running containers, you can use the following command:

docker ps

This command will display:

  • CONTAINER ID: Unique ID for each running container
  • IMAGE: The Docker image used to create the container
  • COMMAND: The main process running in the container
  • STATUS: Whether the container is running, paused, or stopped
  • NAMES: Friendly names assigned to containers for easy identification

Step 2: Access the Shell of a Running Container

Once you have the container ID or name, you can use the docker exec command to access the container’s bash shell. For example:

docker exec -it <container_ID_or_name> /bin/bash
  • -i: Keep STDIN open even if not attached.
  • -t: Allocate a pseudo-TTY, allowing you to interact with the container.

If your container uses a different shell, such as sh, replace /bin/bash with the appropriate shell path.

Advanced Docker Exec Usage

Once you’ve mastered the basics, you can use the docker exec command for more advanced tasks. Let’s look at some examples.

Running Commands in a Docker Container

You don’t always need to access a full shell; sometimes you just need to run a single command. You can do this using the docker exec command, followed by the command you want to execute. For example, to check the /etc/hosts file inside a container:

docker exec -it <container_ID_or_name> cat /etc/hosts

Inspect Container Configuration

To view detailed information about a container, such as its environment variables, network settings, and mounted volumes, use:

docker inspect <container_ID_or_name>

This is helpful when you need to troubleshoot or validate container configurations.

How to SSH into Stopped or Exited Containers

You can only run the docker exec command on running containers. If your container has stopped or exited, you need to start it before you can access it. Here’s how:

  1. List all containers (including stopped ones):
docker ps -a
  1. Start a stopped container:
docker start <container_ID_or_name>
  1. SSH into the container using the previously mentioned docker exec command.

Automating Docker SSH Access

For users who frequently need to access containers, creating a function in your .bashrc or .zshrc file can streamline the process:

function docker_ssh() {
    docker exec -it $1 /bin/bash
}

This allows you to use a simpler command like docker_ssh <container_ID_or_name>.

Frequently Asked Questions (FAQs)

1. Can I install SSH in a Docker container?

Yes, you can install SSH in a Docker container, but it’s generally discouraged. Adding SSH increases the container’s size and complexity. Using docker exec is the recommended way to access containers.

2. How do I copy files between my host machine and Docker containers?

You can use the docker cp command to copy files from your host to the container or vice versa. For example:

docker cp <source_path> <container_ID_or_name>:<destination_path>

3. How can I access Docker containers with graphical applications?

Docker containers can run graphical applications using X11 forwarding, but this setup requires additional configuration beyond simple terminal access.

4. What happens if I stop a container after SSHing into it?

If you stop a container while you’re connected using docker exec, your session will end immediately. You must restart the container to regain access.

Advanced Topics: Managing Multiple Containers

In environments with many running containers, it’s essential to efficiently manage them. Here are a few strategies:

Using Docker Compose for Multi-Container Applications

If you are running multiple containers, Docker Compose is a valuable tool. It allows you to define and manage multi-container applications with a simple YAML configuration file. To install and use Docker Compose:

sudo apt-get install docker-compose
docker-compose up

With Docker Compose, you can specify the configuration for all containers in one place, making it easier to scale, start, and stop services together.

Handling Docker Networks

Managing container networks is crucial, especially for multi-container applications. Docker provides default networking, but you can create custom networks for better isolation and performance.

  • List networks: docker network ls
  • Create a new network: docker network create my_network
  • Run a container on a network: docker run --network my_network <image>

Conclusion

Accessing a Docker container’s shell or executing commands inside it is made simple with the docker exec command. This guide covered everything from basic shell access to running advanced commands and managing multiple containers. Docker’s flexibility allows you to streamline container management without the need for traditional SSH. Thank you for reading the DevopsRoles page!

How to inspect Docker container

Introduction

In this tutorial, I’ll guide you on How to inspect docker container to gain detailed insights into containers. Docker inspect is a powerful tool that provides comprehensive information about various aspects of a container, including its network settings, current status, attached volumes, and more. By exploring these details, you’ll have a deeper understanding of your containers’ configurations and runtime characteristics.

This knowledge proves invaluable for troubleshooting, optimization, and gaining a holistic view of your Dockerized applications. Follow along as I demonstrate the versatility of Docker inspect, enabling you to effectively manage and analyze your containers with precision and ease.

What is docker inspect?

Docker inspect ” is a command in Docker that provides a detailed overview of container information. This powerful tool unveils specifics such as network configurations, status, and attached volumes. By leveraging “docker inspect,” users gain valuable insights into container settings and runtime details, essential for troubleshooting and optimizing Dockerized applications. Mastery of this command empowers efficient container management, allowing users to delve into the intricacies of their Docker environments with precision and ease

What is a Docker container?

  • Portable Packages: Docker containers encapsulate applications along with their dependencies, ensuring a consistent and portable environment.
  • Isolation: Containers operate independently, isolated from the host system and other containers, promoting stability and consistency.
  • Comprehensive Inclusion: Each container includes the necessary components—code, runtime, libraries, and tools—creating a self-contained unit ready to execute.
  • Docker Platform: Docker, a widely used containerization platform, facilitates the seamless packaging and deployment of applications.
  • Cross-Environment Consistency: Developers can build a container once and run it consistently across various environments, from local development setups to large-scale production systems.
  • Resource Efficiency: Containers optimize resource utilization, offering agility, scalability, and quick deployment, making them popular in modern software development and deployment practices.

Inspect Docker container

Utilize the “docker ps” command to showcase a list of containers as follows:

$ sudo docker ps

The displayed results below

CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
055772699b49 devopsroles/nginx:v2 "nginx" 4 seconds ago Up 2 seconds 0.0.0.0:8080->80/tcp devopsroles

Provide details for the “devopsroles” container as illustrated below:

$ sudo docker inspect devopsroles

As an illustration, the output for the “devopsroles” container is presented below:

The omit
"NetworkSettings": {
 "Bridge": "",
 "SandboxID": "38a0b8ae70f0853cf36b25add2182132c2b31183c3d969f7c2b927f75080288c",
 "HairpinMode": false,
 "LinkLocalIPv6Address": "",
 "LinkLocalIPv6PrefixLen": 0,
 "Ports": {
 "80/tcp": [
 {
 "HostIp": "0.0.0.0",
 "HostPort": "8080"
 }
 ]

},
 "SandboxKey": "/var/run/docker/netns/38a0b8ae70f0",
 "SecondaryIPAddresses": null,
 "SecondaryIPv6Addresses": null,
 "EndpointID": "c0103fac129e8ff88fcb597b6cfd1836ca7ffb50580cbe60dc6e7b39f2de1e24",
 "Gateway": "172.17.0.1",
 "GlobalIPv6Address": "",
 "GlobalIPv6PrefixLen": 0,
 "IPAddress": "172.17.0.2",
 "IPPrefixLen": 16,
 "IPv6Gateway": "",
 "MacAddress": "02:42:ac:11:00:02",
 "Networks": {
 "bridge": {
 "IPAMConfig": null,
 "Links": null,
 "Aliases": null,
 "NetworkID": "42dd4e0f69e1edff2c81b2f311b2a0ed53478f47fdf5371643df9f1bdb150ba5",
 "EndpointID": "c0103fac129e8ff88fcb597b6cfd1836ca7ffb50580cbe60dc6e7b39f2de1e24",
 "Gateway": "172.17.0.1",
 "IPAddr$ sudo docker inspect devopsrolesess": "172.17.0.2",
 "IPPrefixLen": 16,
 "IPv6Gateway": "",
 "GlobalIPv6Address": "",
 "GlobalIPv6PrefixLen": 0,
 "MacAddress": "02:42:ac:11:00:02"
 }
 }

How to display the IP Address for the “devopsroles” container as below:

$ sudo docker inspect -f '{{ .NetworkSettings.IPAddress }}' devopsroles

Below is the presented output:

172.17.0.2

For example, display IP, Image, Name, Host Config, and status for containers as below:

$ sudo docker inspect -f 'Image:[{{ .Config.Image}}] Name:{{.Name}} HostConfig:{{ .HostConfig.Binds}} Status:{{ .State.Status}} IP_Container:{{ .NetworkSettings.IPAddress }} ' 055772699b49 | cat -n

The output below:

1 Image:[devopsroles/nginx:v2] Name:/devopsroles HostConfig:[/home/huupv/project/nginx/devopsroles:/var/www/html/devopsroles:ro] Status:running IP_Container:172.17.0.2

An alternative approach is as follows:

$ sudo docker inspect -f 'Image:[{{ .Config.Image}}] Name:{{.Name}} HostConfig:{{ .HostConfig.Binds}} Status:{{ .State.Status}} IP_Container:{{ .NetworkSettings.IPAddress }} ' $(sudo docker ps -a -q) | cat -n

How to display all containers, including non-running

$ sudo docker ps -a -q

The output below:

055772699b49

Conclusion

Throughout the article, we guide you on inspecting containers effectively. Learn how to determine crucial container details such as status, volume, and networking. We’ll continually update this post with useful commands for your reference. Thank you for exploring the DevopsRoles page – we appreciate your readership!

Docker build image from Dockerfile

Introduction

Creating our own Docker images starts with a Dockerfile. Using the docker build command, we can easily transform the instructions in the Dockerfile into a new image. Wondering How to Docker build image from Dockerfile? Let’s dive in!

The first images built with Docker

To create a directory and a Dockerfile, the sample as below:

$ mkdir project
$ cd project
$ touch Dockerfile

The example Docker build the image from Dockerfile

$ vim Dockerfile

The content a Dockerfile as below:

 # CentOS 7 Dockerfile
 # Docker build:
 # sudo docker build -t devopsroles/centos:latest .
 # Docker create:
 # sudo docker create -it --name centos -h centos devopsroles/centos
 # Docker start:
 # sudo docker start centos
 # Connect with bash
 # sudo docker exec -it centos bash
 FROM centos:latest
 MAINTAINER PHAN VAN HUU <pvhuu90@gmail.com> My blogs: devopsroles.com
 #Update centos
 RUN yum update -y && yum upgrade -y
 RUN yum -y install git curl net-tools wget vim
 # Install EPEL Repository
 RUN yum install -y epel-release
 # Clean CentOS 7
 RUN yum clean all
 # Set the environment variables
 ENV HOME /root
 # Working directory
 WORKDIR /root
 # Default command
 CMD ["bash"]

Docker build image from Dockerfile

Running the Dockerfile use Docker build commands

$ cd project
$ sudo docker build -t .
$ sudo docker build -t devopsroles/centos:latest .
$ sudo docker create -it --name centos -h centos devopsroles/centos

The result, Docker images devopsroles/centos as below:

$ sudo docker images

The output, docker images as below:

 REPOSITORY TAG IMAGE ID CREATED SIZE
 devopsroles/centos latest c9ef43af9836 2 minutes ago 428.7 MB

The docker start container centos

$ sudo docker start centos
$ sudo docker ps

The output below:

CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
 2d1a8e53668f devopsroles/centos "bash" 43 seconds ago Up 4 seconds centos

The connect container bash

$ sudo docker exec -it centos bash

The output below:

[root@centos ~]# ifconfig
 eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
 inet 172.17.0.2 netmask 255.255.0.0 broadcast 0.0.0.0
 inet6 fe80::42:acff:fe11:2 prefixlen 64 scopeid 0x20<link>
 ether 02:42:ac:11:00:02 txqueuelen 0 (Ethernet)
 RX packets 8 bytes 648 (648.0 B)
 RX errors 0 dropped 0 overruns 0 frame 0
 TX packets 8 bytes 648 (648.0 B)
 TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
 inet 127.0.0.1 netmask 255.0.0.0
 inet6 ::1 prefixlen 128 scopeid 0x10<host>
 loop txqueuelen 1 (Local Loopback)
 RX packets 0 bytes 0 (0.0 B)
 RX errors 0 dropped 0 overruns 0 frame 0
 TX packets 0 bytes 0 (0.0 B)
 TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

[root@centos ~]# ping 8.8.8.8
 PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
 64 bytes from 8.8.8.8: icmp_seq=1 ttl=127 time=68.7 ms
 64 bytes from 8.8.8.8: icmp_seq=2 ttl=127 time=69.1 ms
 ^C
 --- 8.8.8.8 ping statistics ---
 2 packets transmitted, 2 received, 0% packet loss, time 1001ms
 rtt min/avg/max/mdev = 68.720/68.945/69.170/0.225 ms

Or test ping 8.8.8.8 from docker run command as below

$ sudo docker run centos ping 8.8.8.8 -c4

The output below:

 PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
 64 bytes from 8.8.8.8: icmp_seq=1 ttl=127 time=40.6 ms
 64 bytes from 8.8.8.8: icmp_seq=2 ttl=127 time=41.7 ms
 64 bytes from 8.8.8.8: icmp_seq=3 ttl=127 time=42.1 ms
 64 bytes from 8.8.8.8: icmp_seq=4 ttl=127 time=40.1 ms

--- 8.8.8.8 ping statistics ---
 4 packets transmitted, 4 received, 0% packet loss, time 3005ms
 rtt min/avg/max/mdev = 40.124/41.184/42.196/0.832 ms

Conclusion

Docker build image from Dockerfile. You can update and edit package from Dockerfile file. For example to install Nginx, PHP, MySQL package in Dockerfile file. Thank you for reading the DevopsRoles page!