Best practices in creating a Dockerfile – build docker images

The Dockerfile is a very simple to understand format containing of Statements often referred to as Docker DSL(Domain Specific Language), It tends to become quiet complex and difficult to understand over the time.

[vamshi@docker01 ~]$ cat Dockerfile
# Dockerfile which runs a Latest Ubuntu image and sleeps for 100 seconds
FROM ubuntu:18.04
LABEL maintainer="vamshi" version="1.0.0" description="My First Docker Image"
RUN apt-get update && apt-get dist-upgrade -y && apt-get autoremove -y && apt-get install -y tomcat
RUN apt-get remove --purge -y $(apt-mark showauto) && rm -rf /var/lib/apt/lists/*
WORKDIR /data
ENTRYPOINT ["sleep", "100"]

Let’s examine the Dockerfile and the Statements as follows:

The First line starting with # is a comment.
The Second line with FROM tag determines the image and the latest tag; .
Eg:

FROM ubuntu:latest FROM ubuntu:18.04 or FROM centos:7

The LABEL is a Descriptive tag and contains the information about the original author credits
RUN command simulates a shell command and the subsequent statements are executed as a shell command inside the container.
WORKDIR determines the  directory context inside the running container.
ENTRYPOINT is the invocation of the container main process which runs when the docker container runs and its failure to run means the termination or the end of the particular container.
From the above Dockerfile you would have noticed 2 formats of Instruction, Now lets discuss them in details:
Shell Form
The instructions are written as shell commands

RUN apt-get update , this in turn is formatted as bin sh -c “apt-get update” and enables for command expansion, inclusion of the special characters and it enables combining of multiple commands.

Exec Form
It is JSON array style
These instructions are also shell commands but they are represented in the form of elements in a list.

["command-name","arg1","arg2"]

This format has the following drawbacks
Here the shell is not provided
No scope for variable expansion and
also this format doesn’t allow the special characters like (&&, ||, >….) to be included into the command expression statements.

While running the docker container, the CMD takes the run time arguments and the JSON list format works as a preventive measure.

Advantage of CMD and ENTRYPOINT using square bracket JSON array notation

The most advantageous point with CMD or ENTRYPOINT being written in JSON list format is the during the container runtime, the CMD can take certain arguments which can alter the main container process.. and Thus we can shield against variable expansion, Injecting special characters and not providing a shell as a counter measure security practice.

How to build a Dockerfile?

From the current working directory navigate to the location where Dockerfile is present and run the below command.

# docker build --tag first-docker-image -f Dockerfile .

How to extract Build description from docker image?

We are able to extract the docker LABEL description and MAINTAINER information from the docker command which will help in identifying its purpose when have some hundreds of docker images.

[vamshi@node01 ~]$ docker image inspect first-image --format='{{.Config.Labels}}'
map[description:My First Docker Image maintainer:vamshi version:1.0.0]

Best Practices while building Docker images.

  • While writing the Dockerfile, Its a good practice to include the version information.
  • Include the description of the image which can be easily understood while inspecting the docker image from the inspect command.
  • Grouping RUN shell commands together with && which are inter-dependent and relevant. The Docker by design stores a single STATEMENT as One Layer Image. This will enable better compressing and storing of docker image layers. This technique is called cache-busting.
    RUN apt-get update && apt-get dist-upgrade -y
  • Its a good practice to cleanup the installed package sources and build files which lightens up the size of docker image layer.
    RUN apt-get autoremove -y && rm -rf /var/lib/apt/lists/*
  • The Docker statements can be grouped together that have require less to no modification to save the network bandwidth and increase the docker build time.

How to Create Endpoints for external services in Kubernetes

The endpoints in kubernetes are the mechanism that directly interact and implement the Kubernetes Service

The Endpoints are underlying mechanism which are created in the background and enable us to talk to the kubernetes Services.
As we know that by creating a Kubernetes service we automatically generate the FQDN with the help of core-dns services

There was a requirement for me to setup the specific endpoint and create a service to convert a outside IP into the kubernetes FQDN [svc-name.namespace.cluster.local]
I managed to work around it by creating an endpoint of my external IP which was running mySQL.

[root@master01 ~]# cat Mysql-ep.yaml 
---
kind: Endpoints
apiVersion: v1
metadata:
 name: mysql-svc
 namespace: actoneye
subsets:
 - addresses:
     - ip: 172.22.110.130
   ports:
     - port: 3306

Lets take a look at Kubernetes Service yaml file.

[root@master01 ~]# cat Mysql-svc.yaml
---
kind: Service
apiVersion: v1
metadata:
 name: mysql-svc
spec:
  ports:
    - protocol: TCP
      port: 3306
      targetPort: 3306

The mysql FQDN mysq-svc.dev.cluster.local was used in my application code for my cluster which the mysql resource was outside the kubernetes cluster.

Please try this out and let me know if you had any similar experiences to share.

Create a new kubernetes user with custom kubeconfig auth

The important directories in the reckoning are /etc/kubernetes/pki/
The file ca.key and ca.crt are the Certificate Authority key and certificate respectively.

STEP 1: Generating the key and .csr(Certificate Signing Request)

Lets now generate the .key and .csr. certificates for 1 year with openssl:

[root@node01 ssl]# openssl req -new -sha256 -newkey rsa:2048 -nodes -keyout builduser01.key -days 365 -out builduser01.csr -sha256 -subj "/C=IN/ST=TG/L=/O=/OU=/CN=/subjectAltName=DNS.1="

Verification of the CSR:

[root@node01 ssl]# openssl req -in linuxcent.com.csr -noout -text
Certificate Request:
Data:
Version: 0 (0x0)
Subject: C=IN, ST=TG/subjectAltName=DNS.1= -- INFORMATION RETRACTED --
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (2048 bit)
Modulus:00:e4:b4:24:d7:22:ec:5d:c1:37:8c:d1:a0:62:17:
96:24:77:8d:75:4e:d5:74:15:4d:61:e0:8b:66:d6:
                Exponent: 65537 (0x10001)
        Attributes:
            a0:00
    Signature Algorithm: sha256WithRSAEncryption
         87:ef:83:b2:a6:f5:3a:f3:6f:1c:e4:02:ec:bf:5d:75:64:1d:

STEP 2: Digitally Signing .csr and generating .crt using root CA files.

Now we will using the root ca.key and ca.crt to digitally sign this csr and generate a .crt

[root@node01 ssl]# openssl x509 -req -in builduser01.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out builduser01.crt -days 365 -sha256
Signature ok
subject=/C=IN/ST=TG/subjectAltName=DNS.1=
Getting CA Private Key

We have successfully generated the .crt file from the .csr along with the .key file from STEP1 with the below names. builduser01.crt and builduser01.key

How to create user accounts on kubernetes

We now will create a builduser-config to create a kubeconfig for new user.

Injecting the cluster and the API server information into the kubernetes config file:

[root@node01 ssl]# kubectl config --kubeconfig=builduser-config set-cluster kubernetes --server=https://10.100.0.10:6443 --insecure-skip-tls-verify

We are now injecting the CA certificate information into the config file:

[root@node01 ssl]# kubectl config --kubeconfig=builduser-config set-cluster kubernetes --server=https://10.100.0.10:6443 --certificate-authority=/etc/kubernetes/pki/ca.crt --embed-certs=true

Injecting the credentials key and cert file data into the config file.

[root@node01 ssl]# kubectl config --kubeconfig=builduser-config set-credentials builduser01 --client-certificate=linuxcent.com.crt --client-key=linuxcent.com.key --embed-certs=true

Using –embed-certs=true, we can dump the cert and key file data into the config file instead of writing the path names

[root@node01 ssl]# kubectl config --kubeconfig=builduser-config set-credentials builduser01 --username=builduser01 --password=password123

Using the username and password is not explicitly required while the keys are being used.
Now copy the builduser-config to the $HOME/.kube/config and connect to the kubernetes cluster.

How to Inject Variables into Docker image in build time without modifying the Dockerfile

How to Inject Variables into Docker image in build time without modifying the Dockerfile

 

We have a requirement wherein we need to modify the specific Dockerfile with the build information and we make use of string replace operations like SED to modify the data in Dockerfile, But we can make use of the docker build time arguments to achieve the results efficiently.

Here’s a snippet of Dockerfile

FROM ubuntu:17.04
LABEL maintainer="vamshi" version="1.0.0" description="JRUBY Docker image"
WORKDIR /app
ARG JRUBY_VER 9.2.11.1
ENV JRUBY_VER ${JRUBY_VER}
ADD https://repo1.maven.org/maven2/org/jruby/jruby-dist/${JRUBY_VER}/jruby-dist-${JRUBY_VER}-bin.tar.gz .

We now build this Dockerfile as follows passing the –build-arg:

# docker build --build-arg JRUBY_VER=9.2.8.0 -t jruby:v2  -f ./Dockerfile .

Here we have passed in the build arguments of –build-arg the JRUBY_VER=9.2.8.0 and this then assigns the Argument to the ENV and passed it to ADD command which downloads tar.gz.

When run the command without any build-args it readsup the predefined ARG JRUBY_VER 9.2.11.1 from the Dockerfile.

Conclusion:
Another best usecase is while you have a continuous Docker build pipeline system and want to pass the build time arguments on user input, Its best to use ARG statements inside while writing your Dockerfile

Environmental Variables in Dockerfile.

The Docker Environment variables can be declared during the (1) Docker image creation inside the Dockerfile and (2) During the docker container run time.

The Dockerfile ENV syntax is shown as follows:

ENV VAR_NAME value

We will look at the Dockerfile syntax in the following snippet:

# Exporting the Environment Variables
ENV MAVEN_HOME /usr/share/maven/
ENV JAVA_HOME /usr/lib/jvm/java-8-openjdk-amd64/
# Added as per Java team
ENV JAVA_OPTS -Xms256m -Xmx768m

We can even reference the ENV variable after the declaration at the next statement.

RUN ${JAVA_HOME}/bin/java -version

Conclusion:

Setting the ENV is a lot better than Hard coding the values into the Dockerfile, as it makes maintaining the Dockerfile a simpler task.

Its a good practice for storing the path names, version of packages which are set to be modified over a longer course of time.

How to identify if a docker container files have been modified

The docker container is simply a run time copy of a docker image resources, The docker container utilizes the filesystem structure originally packed into it via the union filesystem packaged from various image layers during the docker image creation.

The docker provides a standard diff command which compares the filesystem data in docker image with the container.

Syntax:

# docker diff [CONTAINER ID | CONTAINER NAME]

Before jumping in lets examine a docker container below and take a look at filesystem by logging into it.

root@node03:~# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
e3de85aaf61c        9a0b6e4f0956        "sh"                2 months ago        Up 3 minutes                            jovial_hertz

We have a running container with a random name jovial_hertz, and we login to the container as follows

root@node03:~# docker exec -it jovial_hertz bash

We are now inside the container and now will create a directory linuxcent and the also create a ASCII text file test and then exit out from the container.

root@e3de85aaf61c:~# mkdir linuxcent
root@e3de85aaf61c:~# cd linuxcent
root@e3de85aaf61c:~# touch test
root@e3de85aaf61c:~# exit

Created a directory called linuxcent and a touched a test file and now logged out from the container with the exit command.
The docker diff command will run against the container should result in the modified data and we contemplate the results

root@node03:~# docker diff jovial_hertz 
C /root
A /root/linuxcent
A /root/linuxcent/test
C /root/.bash_history

The Flags A in front of /root/linuxcent and /root/linuxcent/test indicate that these are directory and file that were the new additions to the container and Flag C indicates that the other 2 files were changed.
Thus it helps us to compare and contrast the new changes to a container filesystem for better auditing.

Docker login to private registry

STEP 1: Docker login to private registry

Lets see the syntax of docker login command followed by the authorized username and the repository URL.
Syntax:

[root@docker03:~]# docker login [DOCKER-REGISTRY-SERVER] -u <username> [-p][your password will be seen here]

The -p is the option for password which can be given along with the docker command or you can type it in the password prompt after hitting enter on the docker login command.

Example given:

[root@docker03:~]# docker login nexusreg.linuxcent.com:5000 -u vamshi
Password:
Login Succeeded

Once the docker login is succeeded a json file will be generated under your home directory at the following path which contains the auth metadata information.

[root@docker03:~]# cat $HOME/.docker/config.json
{
	"auths": {
		"nexusreg.linuxcent.com:5000": {
			"auth": "1234W46TmV0ZW5yaWNoMjAxOQ=="
		}
	},
	"HttpHeaders": {
		"User-Agent": "Docker-Client/18.09.1 (linux)"
	}
}

The docker login repository URL can be found out from your docker client machine using docker info command if you had previously logged in, as we see below:

[root@docker03:~]# docker info | grep Registry
Registry: https://index.docker.io/v1/

How to logout from the specific docker registry use the docker logout command.
The syntax is shown as below:
docker logout [DOCKER-REGISTRY-SERVER]

Example given:

[root@docker03:~]# docker logout 
Removing login credentials for https://index.docker.io/v1/

Setup and configure Zookeper and Kafka on Linux

We would need java runtime environment to install and operate the kafka and zookeeper programs on our linux environment as a dependency which uses the java runtime environment.
So lets quickly check the current java version on the system with java -version.
If its not present Lets now begin with the setup of Java and quickly download the java stable version from the epel repository.

# yum install java-1.8.0-openjdk

Once the java version is installed we verify it with the java -version command.
Creating the kafka user account.

# useradd kafka -m -d /opt/kafka

Adding the kafka password

# echo "kafka" | passwd kafka --stdin
usermod -aG wheel kafka
# su -l kafka

Now login to the system as kafka user.

# cd /opt

Navigate to the url : https://downloads.apache.org/kafka/ and download the latest kafka version

# curl https://downloads.apache.org/kafka/2.5.0/kafka_2.13-2.5.0.tgz -o /opt/kafka.tgz
# tar -xvzf ~/opt/kafka.tgz --strip 1
# cd /opt/kafka
# cp -a /opt/kafka/config/server.properties ~/opt/kafka/config/server.properties.bkp
# echo -e "\ndelete.topic.enable = true\nauto.create.topics.enable = true" >> /opt/kafka/config/server.properties

Adding the Kafka start/stop scripts to systemctl controller daemon services

# sudo vim /etc/systemd/system/zookeeper.service
Add the following lines to /etc/systemd/system/zookeeper.service
[Unit]
Requires=network.target remote-fs.target
After=network.target remote-fs.target

[Service]
Type=simple
User=kafka
ExecStart=/opt/kafka/bin/zookeeper-server-start.sh /opt/kafka/config/zookeeper.properties
ExecStop=/opt/kafka/bin/zookeeper-server-stop.sh
Restart=on-abnormal

[Install]
WantedBy=multi-user.target

Now adding the Kafka control scripts to systemd service

# sudo vim /etc/systemd/system/kafka.service
Add the following lines to /etc/systemd/system/kafka.service
[Unit]
Requires=zookeeper.service
After=zookeeper.service

[Service]
Type=simple
User=kafka
ExecStart=/bin/sh -c '/opt/kafka/bin/kafka-server-start.sh /opt/kafka/config/server.properties > /opt/kafka/kafka.log 2>&1'
ExecStop=/opt/kafka/bin/kafka-server-stop.sh
Restart=on-abnormal

[Install]
WantedBy=multi-user.target
# sudo chown kafka.kafka -R /opt/kafka/logs
# sudo mkdir /var/log/kafka-logs
# sudo chown kafka.kafka -R /var/log/kafka-logs

Now start the zookeeper and kafka services as follows:

# sudo systemctl enable zookeeper --now

# sudo systemctl enable kafka --now





How to create user account in Linux

The Linux system provides a couple of command line utilities to create new users on the system

As we are aware, the Linux login has the essential fields listed as follows:

  • A unique system wide username,
  • A Strong password,
  • The home directory and
  • A login shell.

These are the mandatory fields to enable account creation.

The other fields are the UID and GID numbers associated with User an Group name numerical IDs which will be generated sequentially allocated by the Linux Kernel

We can do a broad categorization of login accounts into 2 types, those are the Privileged and the normal user.

The Absolute Privileged account is root which comes by default in all the linux machines.

The normal account can be enabled with root Privileged by assigning user to certain groups and providing elevated access in the scope.

What is the Process to create a User account in Linux?

The user creation has to be done with root privileges using useradd command.

$ sudo useradd newuser

Now it’s time to enter the password

$ sudo passwd newuser

How to check if the userid is present and active on the system?

The new user details will be updated to /etc/passwd file and the login information updated to /etc/shadow

Now let’s check if the user account is created and has a valid shell

vamshi@node03:/$ grep vamshi /etc/passwd

vamshi:x:1001:1001::/home/vamshi:/bin/bash

How to Add the user to new groups in Linux?

Usermod command line linux utility enables to add user to groups and the ability to add an existing user to new groups additionally or overwrite the group membership

$ usermod -aG dockerroot wheel vamshi

The option -a: appends the user to two new groups called dockerroot and wheel with out overwriting the existing user assigned groups, violating this option will restrict the newuser to be part of only the mentioned groups in the command

How to check and verify if the user is a member of group in Linux?

[vamshi@node02 Linux-blog]$ id vamshi
uid=1001(vamshi) gid=1001(vamshi) groups=1001(vamshi),0(root),10(wheel),992(dockerroot)

How to Verify the Login Confirmation in Linux?

From the root user account run the command: su - newuser to check the new login account environment.

How to find the group names assigned to the user

The user can list of his active membership groups by running the linux command groups

The user can run the groups command to list the groups with active membership

[vamshi@linuxcent ~]$ groups
vamshi root wheel dockerroot

Login to the server remotely using SSH

You may now use the ssh command to login with the new username and enter your password at login prompt.

$ ssh [email protected]

How to connect to server with SSH running on non-standard port like 2202?

[vamshi@linuxcent ~]$ ssh localhost -p 2202
Last login: Mon Mar 13 17:57:56 2020 from 10.100.0.1

How to create a useraccount in Linux using useradd command?

The usercreation can also be done with parametrized command as demonstrated below:

$ sudo useradd vamshi -b /home/ -m -s /bin/bash

Alternatively you can be more elaborate as mentioned below:

$ sudo useradd vamshi -c "Vamshi's user account" -d /home/vamshi -m -s /bin/bash -G dockerroot

The useradd command-utility options describes as follows:

-b or --base-dir : base directory of new user home directory.

-c or --comment : Description about the user Or as A Standard Practice can be used to Mention the Current User’s Full name.

-d or --home-dir : create the user’s home directory

-m or --create-home :  create the user’s home directory as per -d option.

-s or --shell : Type of Login Shell.

-u or --uid : is the Unique UID on linux machine

-G or --groups : list of secondary groups to be assigned

-k or --skel : determines the default parameters if no options are passed while account creation. Present at /etc/default/useradd

With the skel properties finely tunes, you can proceed to use adduser command which is based on the default skel behavior as shown below:

$ sudo adduser vamshi

How to using the SSH key pair to login:
Use the -i followed by the /path/to/id_rsa private key file

$ ssh -i ~/.ssh/id_rsa [email protected]
$ ssh -i ~/.ssh/id_rsa -l linuxcent.com

-l : using the login name

-i : is the identity file; rsa the private key file

 

Troubleshooting the SSH connection in Verbose mode printing Debug information

Using -v option with the ssh command will print the debug information while logging

The verbosity levels -v can be concatenated from one to Nine; eg -v to -vvvvvvvvv

$ ssh -i ~/.ssh/id_rsa [email protected] -vvvvvvvvv

How to make a file or Folder undeletable on Linux

How to make a file or Folder/Directory un-deletable on Linux?

The linux operating as we know if famous for the phrase “Everything is a file”, In such circumstances it is interesting to explore the possibilities of making a file undeletable, even by the owner of the file and for that matter even the root user, In the Linux Ecosystem the root is the poweruser.

This section we will see the potential of such feature.

As we have already seen the section on deleting files on Linux (removing the files in Linux).

We will now demonstrate the power of Linux where you can restrict the deletion of a file on Linux.

Linux offers a chattr commandline utility which generally modifies the file attributes as the name suggests, but the practical use is to make a file undeletable.

Sample command syntax:

[vamshi@linuxcent ~]$ chattr +i <samplefile>
vamshi@linuxcent delete-dir]$ sudo chattr +i samplefile2.txt
Now we do ls -l samplefile2.txt
[vamshi@linuxcent ~]$ sudo chattr +i samplefile2.txt
[vamshi@linuxcent ~]$ ls -l samplefile2.txt
-rw-rw-r--. 1 vamshi vamshi 4 Apr 8 15:42 samplefile2.txt

Now we shall try to write some content to this file and see no change in the basic file permissions(see changing ownership of files).

[vamshi@linuxcent delete-dir]$ echo "New content" > samplefile2.txt
-bash: samplefile2.txt: Permission denied

Deleting file forcefully with the --force option ?

[vamshi@linuxcent delete-dir]$ sudo /bin/rm -f samplefile2.txt

/bin/rm: cannot remove ‘samplefile2.txt’: Operation not permitted

Linux command lsattr offers the ability to view the permissions set by the chattr command.
The current File attributes can be listed using lsattr followed by the filename [/code]samplefile2.txt[/code] as below

[vamshi@linuxcent delete-dir]$ lsattr samplefile2.txt
----i----------- samplefile2.txt

Even the root user on the host is unable to delete the file or modify its contents.

The file can be deleted only when the attributes are unset, It is demonstrated as follows:

[vamshi@linuxcent delete-dir]$ sudo chattr -i samplefile2.txt
[vamshi@linuxcent delete-dir]$ lsattr samplefile2.txt
---------------- samplefile2.txt

As we can see the lsattr doesn’t hold true anymore attributes on our file samplefile2.txt and is now being treated as any other normal file with basic file attributes.
The - operation removes the special linux file attributes on the mentioned file.

The chattr / lsattr linux commandline utilities currently supports the popular filesystems such as ext3,ext4,xfs, btrfs etc,.

Linux Find command – with Practical examples

The Linux find command utility is a powerful command in locating the files and directories at system wide level, the

The basic syntax of find command is very straight forward. The number of filters and types of options you choose while forming the find command determines and complexity of the operation and is directly proportional to the run time of the command.

Lets examine the general syntax of Linux find command line utility

$ find [path] [Options/filters] [expression]

How to Find all the files that are modified within 1 day.

$ find . -mtime -1

Use find command to find all the files that are modified within last x Minutes

$ find . -mmin -360

How to Find all the files that are created within given Minutes

$ find . -cmin -360

How to Find all the files under a specific size on the filesystem.

$ find . -type f -size -100G

NOTE: the - will find the files including and under the mentioned size

How to find really big size files with a given size using Linux Find Command.

$ find . -type f -size +100G

NOTE: the + will find the files exceeding the mentioned size

How to Find all the files with a pattern match using Find command?

vamshi.santhapuri@linux-pc:~/Linux/Programs> find *.py
my_program.py
myProgram.py
My_program.py

OutPut Demonstrated:

vamshi@linuxcent:~/Linux/Programs> ls -l
total 0
-rwxr-xr-x 1 vamshi users 0 Apr 8 16:33 my_program.py
-rwxr-xr-x 1 vamshi users 0 Apr 8 16:32 myProgram.py
-rwxr-xr-x 1 vamshi users 0 Apr 8 16:32 My_program.py ex

 

Find Files Based on file-type using option -type

Find only the regular file type

$ sudo find / -type f -print

Find only the Directory

$ sudo find / -type d -print

Lets see some special file formats like character files as in network level files and block files as in storage device file type.

$ sudo find /dev/ -type b -print
/dev/sdb8
/dev/sdb7
/dev/sdb6
/dev/sdb5
/dev/sdb4
/dev/sdb1
/dev/sdb
/dev/sda6
/dev/sda5

How to find empty files and Directories in Linux using Find command?

$ find . -empty # Finds all files and directories that are empty
$ find . -type f -empty #Find onlt empty files
$ find . -type d -empty #Find only empty Directories

How to Find all the hidden files and directories using Find command

You can also add the type flag as required

$ find . -name ".*" //Prints all the files and directories that are hidden

Find the character stream files and identify them yourselves.

$ sudo find / -type c -print

 

How to exclude some files or directories while using the find command?

The negation Operator ! in find command line

[vamshi@linuxcent ~]$ find / -type d  ! -path /mount ! -path /mnt/3TB/

How to find the files with .py extension and then setting the execute permission on them ?

-exec is a special builtin option which takes the specified command on the selected files

[vamshi@linuxcent ~]$ find *.py -exec chmod +x {} \;

A practical example of Finding and Deleting Big size files using Find Command

We Demonstrate a Big thread dump file that we generated in our Test environment by finding it on our server and then deleting it.

[vamshi@linuxcent ~]$ find /var -type f -size +100G -exec rm {} \;

 

To find the files with matching file permissions

[vamshi@linuxcent ~]$ sudo find / -type f -perm 0600 -print

More complex find operations can be performed by combining the negation operator and by excluding the certain mount points and using the logical AND OR operators.

For example:

sudo find / -xdev -type d \( -perm -0002 -a ! -perm -1000 \) -exec ls -ld {} \;

Ignore case using the find command

The filter -iname enables the find to perform case insesitive search.

[vamshi@node02 Linux-blog]$ find . -iname "rEadMe*" 
./Debian-Distro/README-Debian-Distro
./OpenSuse-Distro/README-Opensuse-Distro
./README
./Redhat-Distro/Centos/README-CentOS
./Redhat-Distro/README-Redhat-Distro

How to use Maxdepth Option in the find command to explore the directory depth?

[vamshi@node02 Linux-blog]$ find . -maxdepth 1 -name "README*" 
./README

By using find command filter option -maxdepth Now we can extract the results based on the one level deeper subdirectory, which is demonstrated as follows:

[vamshi@node02 Linux-blog]$ find . -maxdepth 2 -name "README*" 
./Debian-Distro/README-Debian-Distro
./OpenSuse-Distro/README-Opensuse-Distro
./README
./Redhat-Distro/README-Redhat-Distro

How to use mindepth Option in the find command to restrict the results based on the subdirectory depth?

The -mindepth filter option restricts the find command search to nth subdirectory level from the given path.

[vamshi@node02 Linux-blog]$ find . -mindepth 3 -name "README*" 
./Redhat-Distro/Centos/README-CentOS