How To Clone a Git Repository | Clone a Git Repository with Command Line & Sourcetree

Developers who are excited to learn more about the most popular Version Control System (VCS) ie., Git and cloning the Git repository can refer to this tutorial until the end. To start working with Git, you need to create your own Git repository or you can clone an existing Git repository.

This tutorial will help you concentrate on understanding what is cloning, about the git clone repository, and how to clone an existing Git repository. Moreover, you can observe various methods to clone a specific branch, clone git repository using the command line or Git commands, with sourcetree, clone using an SSH key, and determine access denied issues.

What is cloning?

Basically, Cloning is the process of downloading an existing repository hosted on a remote server to your own computer.

Git Clone Repository

Cloning a repo permit you to make local modifications to the repository before committing and pushing them to the remote. Especially, it is beneficial for beginner developers as cloning offers you a sandbox to experiment without affecting the original codebase.

Do Check: How To Install Git On Debian 10 Buster

Prerequisites

To clone a git repository, clearly, you should have Git installed on your computer. If you want to check that Git is correctly installed on Windows or on Linux, the following command should be executed:

$ git --version
git version 2.22.0

If Git is correctly installed, you are ready to start cloning your first Git repository.

Clone a Git repository using the command line (git clone)

To clone a git repository, use the “git clone” command with the URL of your Git repository.

$ git clone <url>

For instance, let’s assume that you want to clone a public repository from Github, you are going to execute the following command:

$ git clone https://github.com/username/project.git

Cloning into 'project'...
remote: Enumerating objects: 813, done.
remote: Total 813 (delta 0), reused 0 (delta 0), pack-reused 813
Receiving objects: 100% (813/813), 3.66 MiB | 5.52 MiB/s, done.
Resolving deltas: 100% (391/391), done.

As you can see, by default, Git is going to clone your Git repository into a folder named by the name of the project.

However, you can choose to clone your Git repository into a different folder.

Clone a Git repository with Sourcetree

By using Sourcetree, you can clone your repository. Are you new to the sourcetree? Make use of our provided alternative method using the command line. If you are interested to do this method, then follow the below instructions to clone your git repository.

  • Firstly, download the application of sourcetree, if you don’t have it earlier.
  • Choose the Clone button from the repository
  • In the Clone this repository dialog, choose the Clone in Sourcetree button.
  • If needed, update the Destination Path or Bookmark Name.
  • The Destination Path is the folder where your clone saves to your local system.
  • The Bookmark Name is the name of that folder.
  • Select the Clone button.

It also builds the folder on your local system and even more, you can make use of Sourcetree to interact with the repository.

clone with sourcetree view

A. Branches list: Lists your Git branches.
B. Files list: Includes all the files in your repository.
C. Action buttons: This allows you to interact with the repository.
D. Commits list: Includes a list of commits to the repository and details of each commit.
E. Selected file: Shows a diff of the selected file.

Clone a Git repository into a specific folder

In order to clone a git repository into a specific folder, execute the “git clone” command and specify the destination folder at the end.

$ git clone <url> <directory>

For example, given the Github project we fetched in the previous section, if we want to clone it into a folder named “myproject” we would run

$ git clone https://github.com/username/project.git myproject

Cloning into 'myproject'...
remote: Enumerating objects: 813, done.
remote: Total 813 (delta 0), reused 0 (delta 0), pack-reused 813
Receiving objects: 100% (813/813), 3.66 MiB | 5.65 MiB/s, done.
Resolving deltas: 100% (391/391), done.

Now, verify that your git project was correctly cloned to the destination folder.

$ ls -l
total 4
drwxrwxr-x 5 schkn schkn 4096 Nov  1 10:39 myproject

Awesome!

You successfully cloned a Git repository into a specific folder on your server.

In this case, you cloned the master branch from your Git remote repository.

You can check the current branch cloned by running the “git branch” command.

$ git branch
* master

However, in some cases, you may want to clone a specific branch in order to start working.

Your team may have chosen to let the “master” branch a bit behind and to have the most recent commits directly to the “dev” branch for example.

Git clone a specific branch

In order to clone a specific branch, you have to execute the “git branch” with the “-b” and specify the branch you want to clone.

$ git clone -b <branch> <remote_repo>

For example, in order to clone the “dev” branch of your Github repository, you would run

$ git clone -b dev https://github.com/username/project.git

Cloning into 'project'...
remote: Enumerating objects: 813, done.
remote: Total 813 (delta 0), reused 0 (delta 0), pack-reused 813
Receiving objects: 100% (813/813), 3.66 MiB | 5.65 MiB/s, done.
Resolving deltas: 100% (391/391), done.

To verify that you correctly cloned the “dev” branch, make sure to run the “git branch” command.

$ git branch
* dev

Using the “-b” option, you are fetching all the branches but you are checking out the branch you chose.

It means that if you run the “git branch” with the “-a” (for all) option, you are going to see that all your branches were fetched.

Note : you have to execute this command into the Git repository you just cloned.
$ git branch -a

* dev
  remotes/origin/HEAD -> origin/master
  remotes/origin/dev
  remotes/origin/master
  remotes/origin/feature

Git clone exclusively one branch

In order to clone and fetch exclusively the branch you chose, you have to specify the “–single-branch” option.

$ git clone --single-branch --branch <branchn> <repository>

Make sure that only the branch chosen was fetched on your local repository.

Note: you have to execute this command into the Git repository you just cloned.

$ git branch -a

* dev
  remotes/origin/dev

This option works for Git versions greater than 1.17.10, so make sure that this is the case before issuing the command.

$ git --version

git version 2.22.0

In the previous sections, we saw the various ways to clone public repositories to your local server.

It means that you did not need to provide any username or password in order to clone the repositories.

However, in some cases, you may have private Git servers that only authorized team members can access.

Clone a private Git repository

When cloning a Git repository, there are two ways of authenticating with the server: with a user/password set or using SSH keys.

In this section, we are going to see how you can authenticate to your Git server using both methods.

Clone using SSH

In most cases, you want to secure your Git repositories with SSH keys in order to avoid having to type your password every single time.

In order to clone from a private repository using SSH, your SSH keys need to be correctly set and configured on your server.

Go into your personal “.ssh” directory and create a new SSH key named “repo_id_rsa” where repo stands for the name of the repository you are trying to clone.

$ cd ~/.ssh && ssh-keygen -t rsa -b 4096 -C "email@example.com"

Generating public/private rsa key pair.
Enter file in which to save the key (/home/schkn/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in repo_id_rsa.
Your public key has been saved in repo_id_rsa.pub.
The key fingerprint is:
SHA256:Lu0CV79iccFGzDLs4x6RXZbUOyimXRsIlNc0o30T+u4 email@example.com
The key's randomart image is:
+---[RSA 4096]----+
|       o.+ +=o.  |
|        * =o=+.. |
|       . X.+o.o. |
|        * O +oo. |
|       oSO + o.. |
|    . .o= + ..   |
|     o..o+ .  .  |
|      .o+ .  .   |
|       o..    E  |
+----[SHA256]-----+

Your public key has been correctly generated.

Print down the public key content using the “cat” command.

ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDKRsXF9r2DSgSHxYe6QkJE0Otekn5F9E5e+VQfFtzJAr/xsgr8vCuJbWWsPo6Fibbw54jYjEGjVhnMFOQl9nWA8KxubX6HUHtXxlw9VRVKob6OyO4Qt0F8nw== email@example.com

On the server, head over to the “authorized_keys” file and add the content of your public key to the server.

$ sudo nano /home/git/.ssh/authorized_keys

ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDKRsXF9r2DSgSHxYe6QkJE0Otekn5F9E5e+VQfFtzJAr/xsgr8vCuJbWWsPo6Fibbw54jYjEGjVhnMFOQl9nWA8KxubX6HUHtXxlw9VRVKob6OyO4Qt0F8nw== email@example.com

Next, you should be able to clone the git repository using your newly created SSH keys.

$ git clone <username>@<hostname>:<repository>.git

Cloning into 'private-repo'...
remote: Enumerating objects: 3, done.
remote: Counting objects: 100% (3/3), done.
remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
Receiving objects: 100% (3/3), done.

Specifying the SSH key to use

In some cases, you might not use the “id_rsa” key in order to store your Git public keys.

To create a specific SSH key for your Git repositories, simply specify a name when prompted by the “ssh-keygen” utility.

$ cd ~/.ssh && ssh-keygen -t rsa -b 4096 -C "email@example.com"

Generating public/private rsa key pair.
Enter file in which to save the key (/home/schkn/.ssh/id_rsa): repo_id_rsa

In this case, if you try to clone the repository, you might not be able to do so because you need to tell SSH which key to use for the server.

To specify the SSH key to use, add the following content to your ~/.ssh/config file (you need to create it if it does not already exist)

Host *
    Hostname <server_ip>
    User git
    IdentityFile ~/.ssh/repo_id_rsa

If you were to use Github as a git server, it would give the following configuration.

Host *
    Hostname github.com
    User git
    IdentityFile ~/.ssh/repo_id_rsa

Restart your SSH service.

$ sudo systemctl restart ssh

Then, you should be able to clone your git repository seamlessly.

$ git clone <username>@<hostname>:<repository>.git

Clone using a password

The other way to authenticate to a Git server is to use a password in order to connect.

To git clone using a password, simply provide the username for the git account, and you will be prompted with the password.

git clone https://username@<repository_url>

Cloning into 'private-repo'
Password for 'https://<username>@<repository_url>:
remote: Enumerating objects: 3, done.
remote: Counting objects: 100% (3/3), done.
remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
Receiving objects: 100% (3/3), done.

For example, if you want to clone your repository from Github using a password, simply type the following command.

git clone https://<username>@github.com/<username>/<repository>.git

Password for 'https://<username>@github.com':

Store your password using git credentials

Using the previous method, you will have to specify the account password every time you want to push your code to the server or when you want to pull it from the server.

This is not very handy.

Luckily for you, you can set your password in order not to be prompted again.

To enable the credentials helper, simply run “git config” with the “credential.helper” option.

$ git config --global credential.helper store

When cloning a new repository, you will still be asked to provide the password the first time.

However, you won’t be asked to provide it again on push and pull operations.

Your credentials will be stored in the git-credentials file in your home directory.

$ cat ~/.git-credentials

https://<username>:<password>@<server>

Git Clone Authentication Failure

In some cases, you may be facing authentication failures when performing git clones.

Here are some hints on what you may check in order to solve this issue :

  • Make sure that you are writing the correct password when cloning a repository.

In the section dedicated to git clone with a password, you may need to inspect the git-credentials file. If your password is changed on the server, make sure to change it in your git-credentials file for the changes to be applied.

  • Make sure that the user account is correctly configured on the Git server.

In some cases, you may have an account on the Git server but you may not have enough rights to perform read or write operations to the server.

Depending on the git server you are using (Gitlab, Gittea, Bitbucket), you need to check the account sections to see if the user account is correctly configured.

  • When using authentication with SSH, you may need to check that your SSH client is actually using the SSH key to connect to your server.

In order to check if OpenSSH is using your SSH key, use “ssh” with the “-vT” option.

$ ssh -vT git@github.com:<user>/<repository>.git

OpenSSH_7.6p1 Ubuntu-4ubuntu0.3, OpenSSL 1.0.2n  7 Dec 2017
debug1: Reading configuration data /home/schkn/.ssh/config
debug1: /home/schkn/.ssh/config line 1: Applying options for *
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug1: Connecting to github.com [140.82.118.3] port 22.
debug1: Connection established.
  • When using SSH key-based authentication, verify that your server contains the public key of your client.

In order to check authorized keys on the server, make sure to inspect the authorized_keys in the .ssh directory.

$ cat ~/.ssh/authorized_keys

ssh-rsa AAAABfzaC1yc2EAAAADAfgzrgegtexoq6FuKMPSs9cpeoCv+HUaL3fijO2otTw54451cfzfxpcdrtRLfYZp34qztJGC1AwNiU5yezfzi/D2afzfzzFls3wvwn+DNA email@example.com

Conclusion

In this tutorial, you learned more about the git clone and how it can be used in order to start working on different projects on your codebase.

You also learned more about the two main authentication methods: SSH key-based authentication and password.

If you are interested in software engineering, we have a complete section dedicated to it on the website, so make sure to have a look.

How To Check SSL Certificate Expiration with Grafana

How To Check SSL Certificate Expiration with Grafana | Grafana SSL Certificate Expiry Check

In this tutorial, we are going to discuss How To Check SSL Certificate Expiration with Grafana. Security is more important these days so you have to secure various parts with SSL Certificates while setting up the entire monitoring solutions.

In our previous Prometheus setup on Linux also we have created SSL certificates to ensure the interaction between those agents and grafana was protected.

Also Check: MongoDB Monitoring with Grafana & Prometheus

As time passes, it is common to verify SSL certification expiration and secure the visualizing data. Let’s assume that one of the SSL certificate expiration dates is about to expire. Now, we have to check the ways to secure it.

In today’s guide, we are explaining the simple process to monitor SSL certificate expiration dates with Grafana and Prometheus.

Get Ready?

What You Will Learn?

Those are the concepts that you are going to learn if you follow this tutorial until the end.

  • How to setup Prometheus and Grafana easily
  • How to install the node-cert exporter to monitor your SSL certificates.
  • How to design a Grafana dashboard to visualize SSL certificate expirations.
  • How to raise alerts when your SSL certificates are about to expire.

That’s a long program, let’s start working.

Installing Prometheus & Grafana

The complete Prometheus & Grafana installation has already been covered in one of our previous articles.

It explains how to setup your Prometheus monitoring instance, how to secure it using HTTPS, and how to bind it securely to Grafana.

You can skip the reverse proxy steps, but it is highly recommended to setup an NGINX reverse proxy for safety purposes.

When you are done, you are ready to go to step two.

Do Check: Complete MySQL dashboard with Grafana & Prometheus

Installing the node-cert exporter in Prometheus

Now that our Prometheus & Grafana stack is ready, it is time to install the node-cert exporter.

The node-cert exporter is an exporter that will periodically check your SSL certificates given a set of filesystem paths.

It is highly recommended to store your SSL certificates in the /etc/ssl folder, but you may store them in different places.

a – Download the node-cert exporter

To download the node-cert exporter, run a simple wget command.

$ wget https://github.com/amimof/node-cert-exporter/releases/latest/download/node-cert-exporter-linux-amd64

You should now have the node-cert-exporter executable on your instance.

Move this executable to your /usr/local/bin folder and make it executable, at least for the owner of the file.

$ sudo mv node-cert-exporter-linux-amd64 /usr/local/bin
$ sudo chmod u+x /usr/local/bin/node-cert-exporter-linux-amd64

Create a user for the node-cert exporter.

$ sudo useradd -rs /bin/false node-cert-exporter

Make the node-cert-exporter user the owner of the exporter executable.

$ sudo chown node-cert-exporter:node-cert-exporter /usr/local/bin/node-cert-exporter-linux-amd64

This should be the content of your bin folder.
Node Cert Exporter archive

b – Install the node-cert exporter as a service

As always, we are going to install the exporter as a service.

Running exporters as a background process is the best way to crash them. Plus, you can monitor your systemd services and be notified when one goes down.

As always, head to the /lib/systemd/system folder, and create a node-cert service file in there.

$ cd /lib/systemd/system
$ sudo touch node-cert-exporter.service

The node-cert exporter uses the path flag to specify where your certificates are located on your system.

In my case, I am going to suppose that my certificates are located in the /etc/ssl/certs folder.

Make sure to finetune the path flag for your own SSL path.

Here is the content of the service file.

[Unit]
Description=Node Cert Exporter
Wants=network-online.target
After=network-online.target

[Service]
Type=simple
User=node-cert-exporter
Group=node-cert-exporter
ExecStart=/usr/local/bin/node-cert-exporter-linux-amd64 \
    --path=/etc/ssl/certs

Restart=always

[Install]
WantedBy=multi-user.target

Enable your service, and start it.

$ sudo systemctl enable node-cert-exporter
$ sudo systemctl start node-cert-exporter

enable-service

Great!

Let’s have a look at the metrics exposed by the node-cert exporter.

$ sudo lsof | grep LISTEN | grep node-cert

node-cert

Given the information of the last column, we can see that the node-cert exposes metrics on the port 9117.

Let’s do a quick curl command to see if it is aggregating metrics correctly.

$ curl http://localhost:9117/metrics

If you are seeing metrics named “ssl_certificate_expiry_date“, congratulations!

Your node-cert exporter is correctly installed.

ssl_cert_expiry

c – Binding your exporter to Prometheus

Now that your node-cert exporter is correctly running, you need to bind it to Prometheus.

To do so, navigate to your Prometheus configuration file, and start editing it to add the following targets.

$ cd /etc/Prometheus
$ sudo vi prometheus.yml

In the static_configs part of your configuration file, add a new entry for the cert exporter.

static_configs:
            - targets: ['localhost:9090', 'localhost:9117']

Restart Prometheus for your changes to be applied.

$ sudo systemctl restart prometheus

Don’t forget to verify that Prometheus is actively scraping your new target.

Head over to http://localhost:1234/targets (if you followed the Prometheus and Grafana tutorial).

targets-prom

Awesome! The exporter is up and running.

Time to check the SSL certificate expirations in Grafana.

Creating a Grafana dashboard

In order to visualize SSL certification expiration dates, we are going to use a predefined dashboard built by the creator of the exporter.

a – Import a Grafana dashboard

To import a Grafana dashboard, click on the Import option available in the left menu.

import-dash

In the next window, choose to import your dashboard given a dashboard ID.

The dashboard ID for the node-cert dashboard is 9999.

In the next window, choose to import your dashboard given a dashboard ID.

From there, Grafana should automatically detect that you are trying to import the dashboard.

This is what you should see.

import-dash-2

b – Write a PromQL query for SSL certificate expiration

By default, the dashboard is not fully loaded in Grafana.

For some reasons that I ignore, the PromQL query is not actively loaded. That’s not a big problem, we are going to write it our way.

Edit the table panel in your dashboard.

edit-panel

Go to the query panel, select Prometheus as a datasource and write the following PromQL query.

promql-query

Important Note: Do not forget to check the “Instant” option on the second line of your query panel (otherwise you won’t be able to see anything)

This is what you should now see on your dashboard.

final-dashboard-1

Awesome!

You now have a dashboard checking your SSL certificates with pleasing colors.

As you can see, most of my certificates are safe, but some of them will have to be renewed in a month or so.

c – Customizing the threshold levels

As you can see, some thresholds are already defined in this Grafana dashboard.

By default, red lines will be displayed for SSL certificates that need to be renewed in less than three monthsorange lines between three months and six months, and green lines for more than six months.

Would you like to customize those levels?

Let’s have red lines for expirations in less than one week, and orange between one week and one month.

To customize it, head over to the “Visualization” panel in Grafana and search for the corresponding option line.

visu-panel

The levels are stored in the “Thresholds” text field.

The current values are 7889231 seconds (3 months) and 15778463 seconds (6 months).

Let’s modify this text field for 2592000 (1 month) and 25920000 (10 months).

604800,2592000

orange-levels

Firing alerts when SSL certificates expire

If you are to check your SSL certification expiration dates, it is very likely that you are not going to take a look at your dashboard every day.

You want to be alerted when one of your certificates is about to expire.

Make sure to install the AlertManager with Prometheus by following this tutorial.

a – Creating a rules file

In your Prometheus folder, create a “alerts” folder. This is the place where you are going to store all your alert files.

Go to your alerts folder, and create a new file named “ssl_rules.yml“.

$ cd /etc/prometheus
$ sudo mkdir alerts && cd alerts
$ sudo nano ssl_rules.yml

In the file, paste the following content.

groups: 
  - name: ssl_expiry.rules 
    rules: 
      - alert: SSLCertExpiringSoon 
        expr: sum(ssl_certificate_expiry_seconds{}) by (instance, path) < 86400 * 30 
        for: 10m

The following configuration will fire an alert when you need to check your SSL certificate (one month away from being expired)

As a reminder, the Prometheus server is going to be used as a client for the Alert Manager.

b – Create an AlertManager rules file

Now we are going to create a rules file for the AlertManager.

For this part, we are going to use Slack as a recipient, but you could send an email, or use PagerDuty for example.

If you are looking to create a Webhook for Slack and Prometheus, check our other articles or go for a web search.

Go to your /etc/alertmanager folder and create a new file named “alertmanager.yml“.

$ cd /etc/alertmanager
$ sudo touch alertmanager.yml

Paste the following content in your file (change the webhook URL for the one provided by your Slack workspace)

global:
  resolve_timeout: 5m

route:
 group_by: ['SSLCertExpiringSoon']
 group_wait: 10s
 group_interval: 10s
 repeat_interval: 1h
 receiver: slack
 

receivers:
- name: slack
  slack_configs:
  - api_url: $WEBHOOK_URL
    channel: '#devconnecteds-blog'

Save your file, and make sure that your AlertManager service is launched with the correct option (with the correct –config flag)

alertmanager-service-1

Restart your AlertManager service.

$ sudo systemctl restart alertmanager

c – Getting AlertManager alerts on Slack

Now that our configuration is set, it is time to have an alert firing on the Prometheus server.

As you can see, two alerts are already firing on my Prometheus alerts tab.

alerts-prom

On the AlertManager, this is what you should see.

alerts-am

Finally, you should receive your alerts on Slack. In this case, they are grouped, but you can modify this option in your rules file (by replacing the group by option).

alerts-slack

Awesome! You are now notified when you have to check your SSL certificates.

Alternatives

Alternatives to Prometheus and Grafana exist to check your SSL certificate expiration.

David McKay, the developer advocate for InfluxData, wrote an article on how to check your SSL certificates using Telegraf and InfluxDB.

This is more or less the same principle, except that you would have to use an InfluxDB datasource in Grafana.

If you are not sure about how to setup the TIG stack, here is how to setup InfluxDB and Grafana on Linux.

Free services also exist if you are looking to monitor your SSL certificates online. Certificate Expiry Monitor is one of them as an example. Are you going to start using Prometheus to monitor your SSL certificates?

I hope that you learned something new today. Till next practice well with our useful tutorials on modern technologies.

How To Clear Git Cache

How To Clear Git Cache | Learn Git Clear Cache in Different Ways

Are you worried about adding some new lines to your gitignore files while working with Git? And do you realize such files are still shown in git? Then, Git Clear Cache comes into the frame. Furthermore, you may also get to know some Git commands that help to clear a git repo’s cache from here.

In this tutorial, we are going to discuss how to clear git cache in different ways. By using the commands, you can easily clear the git cache. Moreover, we are also explaining thoroughly how to actively remove files you needed to ignore in the first place.

Commands to Clear a Git Repository’s Cache

Here are the commands for clearing out your git repo’s cache in order for the changes to take place.

git rm -r --cached .
git add .
git commit -am 'git cache cleared'
git push

Clear Git Cache using rm

Usually, you want to clear your Git cache because you added new entries in your gitignore files and you want them to be taken into account.

The easiest way to clear your Git cache is to use the “git rm” command with the “–cached” option.

You can choose to remove one file or to remove an entire working directory.

$ git rm --cached filename

Concrete example

Note : do not forget the cached option or your file will be deleted from the filesystem.

For this example, the .gitignore file is set to ignore all files ending in “.conf

Content of .gitignore:

*.conf

However, the file named “file.conf” is already in the staging area of my Git repository, this is also called the index.

On branch master
Your branch is ahead of 'origin/master' by 2 commits.
  (use "git push" to publish your local commits)

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        new file:   file.conf

In this case, you want your file to go from the staging area back to the working directory (essentially the untracked part of Git).

Also Check: How To Delete Local and Remote Tags on Git

To clear the cache, you use the git rm command.

When provided with the “–cached” option, it will only delete files from the staging area, not from the working directory.

$ git rm --cached file.conf

$ git status

On branch master
Your branch is ahead of 'origin/master' by 2 commits.
  (use "git push" to publish your local commits)

Untracked files:
  (use "git add <file>..." to include in what will be committed)

        file.conf

nothing added to commit but untracked files present (use "git add" to track)

Clear Entire Git Cache

In some cases, you may want to clear the cache of your entire Git staging area.

This is particularly useful when you added multiple files that you want now to be ignored via your .gitignore file.

To clear your entire Git cache, use the “git rm” command with the “-r” option for recursive.

$ git rm -r --cached .

When all files are removed from the index, you can add the regular files back (the ones you did not want to ignore)

$ git add .
$ git commit -am 'Removed files from the index (now ignored)'

Concrete Example

For this example, the .gitignore file is set to ignore files ending in .conf.

Content of .gitignore:

*.conf

In the staging area, we have two files ending in .conf and three regular files ending in .js.

On branch master
Your branch is ahead of 'origin/master' by 2 commits.
  (use "git push" to publish your local commits)

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        new file:   file.conf
        new file:   file2.conf
        new file:   index.js
        new file:   script.js

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   .gitignore

First, let’s remove all the files that are currently tracked.

$ git rm -r --cached .
rm '.gitignore'
rm 'README.md'
rm 'file.conf'
rm 'file2.conf'
rm 'index.js'
rm 'script.js'

Now some of the files may be marked as deleted and some others are back in the working directory.

Now, you want to add them back to the staging area while taking into account the content of your .gitignore file.

$ git add .

$ git status

On branch master
Your branch is ahead of 'origin/master' by 2 commits.
  (use "git push" to publish your local commits)

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        modified:   .gitignore
        new file:   index.js
        new file:   script.js

Awesome!

The configuration files are not in the staging area anymore.

You can now commit and push them to your repository.

$ git commit -am 'Removed files from the index (now ignored)'

$ git push

Note: Do not forget to set your upstream branch when pushing your changes.

Clear specific files from Git Cache

Let’s discuss how to clear the git cache for specific files here. After using the following commands, it will remove the specific file from git.

git rm --cached database.php
git add --all
git commit -m "Remove the database config file cache"
git push origin branch_name

Ultimately, you have learned how to remove the cache for specific files using the git command. It will assist when you add a new file on the gitignore file and it’s not excluded from git.

Conclusion

In this tutorial, you learned how you can clear your Git cache easily and how it can help when you updated your .gitignore file.

You also learned more about the “git rm” command and how it can be used in order to remove some files from the staging area back to the working directory.

If you are curious about Git or software engineering, we have a complete section dedicated to it on the website.

Make sure to check it out!

How To Delete File on Git

How To Delete File on Git | Removing Files from Git Repository using git rm Command

We all know how important to add many files into a git repository for developing the project. But developers should realize and work on deleting unused files on git. Always, delete files on git is so confusing as it is a big question mark to delete them from my repository or delete them from the filesystem?

Also, Have a look at the Git Commands for gaining enough knowledge & practice on Git.

To clear your confusion, we have come up with this new Git Tutorial on How to Delete File on Git. Here, we have explained completely how you can easily delete files on Git, whether it is only from your Git repository or from the filesystem. Let’s dive into it without any further do.

The git rm Command

Whenever you are planning to delete or remove a file or multiple files from a git repository, then this command ie., git rm is used. Not only it deletes but also remove files from the staging index and the working directory. If you wish then it could also delete files from the filesystem.

Deleting a file from the actual Git repository is a separate task that is done easily by the git rm command. But removing the file from the filesystem can be made in several other applications, e.g. a text editor, IDE, or file browser.

Also Check: How To Delete a GitHub Repository

Delete Files using git rm

The easiest way to delete a file in your Git repository is to execute the “git rm” command and specify the file to be deleted.

$ git rm <file>

$ git commit -m "Deleted the file from the git repository"

$ git push

Delete Files using git rm git-rm

Note that by using the “git rm” command, the file will also be deleted from the filesystem.

Also, you will have to commit your changes, “git rm” does not remove the file from the Git index unless you commit it.

As always, let’s have a quick example in order to illustrate the commands we just described.

In my current repository, I have three files named “file1”, “file2” and “file3” and I want to delete the “file1” file from my Git repository.

By using the “git ls-tree” command, I am able to see the files tracked on my current branch.

$ git ls-tree -r master

Delete Files using git rm git-list-tracked-files

In order to delete the file “file1” from the Git repository and from the filesystem, we are going to execute the “git rm” command with the name of the file.

$ git rm file1
rm 'file1'

You should get a small confirmation message saying that the “rm” command was executed on this file.

How To Delete File on Git git-rm-example

So what happened here?

As you can see, by executing the “git rm” command, a “deleted” action was added to the changes to be committed.

It means that the file was removed from the filesystem but it was not deleted from the index just yet.

In order for the changes to be effective, you will have to commit your changes and push them to your remote repository.

How To Delete File on Git git-rm-commit-changes

Now the file should be deleted from the filesystem and from the index, you can verify it by re-executing the “git ls-tree” command in order to list files in the current index.

How To Delete File on Git git-list-files-index

Congratulations, you successfully deleted a file from your Git repository.

Removing Multiple Files

Deleting multiple files from a repo is the same as the early use-case of removing a single file using git rm. On the basis of your preferred method, there are some ways to do this. For instance, you can just explicitly list all files to be deleted like below:

$ git rm lib/db.js lib/api.js
rm 'lib/api.js'
rm 'lib/db.js'

Or, if there are more files than you feel like listing, you can always use the wildcard character:

$ git rm lib/*.js
rm 'lib/api.js'
rm 'lib/db.js'

Be noted that by deleting all of the contents from the lib directory, Git will also remove the actual directory itself. This is done because Git only tracks files, not directories:

$ git ls-files
.gitignore
index.js
package.json

Delete Files Recursively on Git

In order to delete files recursively on Git, you have to use the “git rm” command with the “-r” option for recursive and specify the list of files to be deleted.

$ git rm -r <folder>

$ git commit -m "Deleted the folder from the repository"

$ git push

This is particularly handy when you need to delete an entire directory or a subset of files inside a directory.

As an example, let’s say that our Git repository has a folder named “folder1” that contains two files.

In order to delete this folder, and the files contained in it, we are going to execute the “git rm” command with the “-r” option.

$ git rm -r folder1

Delete Files Recursively on Git git-rm-recursive
Again, do not forget that the changes are effective when you commit them, not before.
Delete Files Recursively on Git git-delete-folder

Congratulations, you successfully removed an entire folder from your Git repository.

Delete Files From Git Repository Only

In some cases, you want to delete files from the Git repository but not from the filesystem, you have to execute the “git rm” command with the “–cached” option.

$ git rm --cached <file>

$ git commit -m "Deleted file from repository only"

$ git push

Back to our example, we currently have two files sitting in our working folder: file2 and file3.

Let’s pretend that we want to delete the file “file2” from the repository but we want to keep it on the filesystem.

To achieve that, we simply execute the “git rm” command with the “–cached” option.

$ git rm --cached file2

Delete Files From Git Repository only git-rm-cached

As you can see, after executing the “git rm” command, the file is still on the filesystem.

Awesome, you simply have to commit and push the changes now for them to be effective.

What’s in my git status?

Before committing your changes, you may notice with a “git status” command that the file was added to the changes to be committed, as well as in the list of untracked files.

Delete Files From Git Repository only git-status-command

Quite logic because your file is not tracked anymore as the result of your previous deletion.

Now for the file not to be listed in your Git repository under the “untracked files”, make sure to add it to your Git Ignore file.

$ touch .gitignore

# Content of the gitignore file

file2

What s in my git status gitignore-files

Commit your gitignore file and you should be good to go!

Delete Files From Git History

In some cases, you want to delete files from your entire Git history.

It may be the case for example if you committed a file that contains passwords or some sensitive information, that you want to remove.

In order to delete the file from Git history, you have to use the “git filter-branch” command and specify the command to be executed on all the branches of your Git history.

Finally, you want to specify the revision to execute the changes from we are going to choose HEAD (as a reminder, HEAD is the last commit of your repository).

In this case, the Git command to be executed is the “git rm” command we described earlier.

$ git filter-branch --force --index-filter --prune-empty "git rm --cached --ignore-unmatch <path_to_file>" HEAD

As the command is quite complex, let’s have a breakdown of all the options used :

  • –force: quite self-explanatory, it forces the filter-branch to start even if it may not want to (given the documentation because it can contain temporary directories)
  • –index-filter: option used in order to rewrite the index, exactly what we want in the case of a file deletion
  • “git rm” command: the command to be executed on all branches, revisions, and commits matching in the history, in this case, it will remove the file from the repository and ignore files that don’t match
  • –prune-empty: avoid having empty commits in the repository with zero files, this option will prune commits automatically

In this case, let’s say that we want to delete the file “file1” contained in our repository.

We are going to execute the following command.

$ git filter-branch -f --prune-empty --index-filter "git rm -r --cached --ignore-unmatch ./file1" HEAD

Delete Files From Git History rewrite-history

This command can take a while if your history contains many files, but in the end, the deleted file won’t be in your Git history anymore.

You can check with a “git log” command, but the commits linked to the deleted file should be pruned if necessary.

Conclusion

In this tutorial, you learned how you can easily delete a file from a Git repository, whether you want to delete it from the filesystem or not. Also, learned that it is completely possible to delete a file from an entire Git repository using the “filter-branch”.

Deleting files in Git is associated to file restoration, as a result, you may be interested in the following resources:

How To Git Add All Files

How To Git Add All Files | Git How to Add All Modified File to Commit?

Adding new files or a bunch of files to the repositories is quite common for all developers working on the software project with Git. In various cases, we face a situation where we need to add multiple files to git. To make it possible, Git provides a single command for that i.e. git add command also check other Git Commands from this available quick link.

In case, if you want to add untracked files to your repository then also you can simply refer & utilize the same command. Well, this tutorial is designed to explain how easily add all your files to your Git repository. Also, you can learn how to Git Add All New files, modified files, deleted files, untracked files, etc. from the available links.

Determine your Git version

Depending on the current Git version that you installed on your computer, the “git add” command can differ.

To determine your current Git version, use “git” followed by the “–version” option.

$ git --version

Determine your Git version git-version

Add All Files using Git Add

The easiest way to add all files to your Git repository is to use the “git add” command followed by the “-A” option for “all”.

$ git add -A                       

$ git add .                        (at the root of your project folder)

In this case, the new (or untracked), deleted and modified files will be added to your Git staging area. We also say that they will be staged.

Alternatively, you can use the “git add” followed by a “.” which stands for “current directory”. However, using the “.” syntax implies that you are currently at the top of your project folder hierarchy.

As an example, let’s say that we created a branch named “feature“. On this branch, we have three files: one deleted, one with its content modified, and another one that is untracked.
Add All Files using Git Add git-add-all-files

In order to add all those files to our staging area, we will use the “git add” command followed by the “-A” option.

Add All Files using Git Add adding-all-files

As you can see, the files were correctly added to the staging area, awesome!

You can now commit them to your Git repository in order for the changes to be shared with your colleagues.

The Git Add Command

This command updates the index using the current content found in the working tree, to prepare the content staged for the next commit. It typically adds the current content of existing paths as a whole, but with some options, it can also be used to add content with only part of the changes made to the working tree files applied or remove paths that do not exist in the working tree anymore.

The git add command will not add ignored files by default. If any ignored files were explicitly specified on the command line, git add will fail with a list of ignored files.

The SYNOPSIS of the git add command is as follows:

git add [--verbose | -v] [--dry-run | -n] [--force | -f] [--interactive | -i] [--patch | -p]
[--edit | -e] [--[no-]all | --[no-]ignore-removal | [--update | -u]]
[--intent-to-add | -N] [--refresh] [--ignore-errors] [--ignore-missing] [--renormalize]
[--chmod=(+|-)x] [--pathspec-from-file=<file> [--pathspec-file-nul]]
[--] [<pathspec>…​]

Adding all files by Wildcard

In some cases, you may be interested in adding all files that have a specific extension : *.txt or *.js for example.

To add all files having a specific extension, you have to use the “git add” command followed by a wildcard and the extension to add.

$ git add *.txt

$ git add *.js

As an example, let’s say that you have created two Javascript files and one text file.

Adding all files by extension add-file-by-extension

In order to add all Javascript files, we are going to use the wildcard syntax followed by “*.js”.

$ git add *.js

Adding all files by extension wildcard-git-add

Congratulations, you successfully added your files having a specific extension!

Using dot with git add

As explained before, the “.” symbol stands for “current directory“.

As a consequence, if you don’t use it at the top of your project hierarchy, you will only add files in the current working directory.

To illustrate this concept, let’s say that you have two new files: “root-file” in your project top folder and “new-file” in a folder named “folder”.

Using dot with git add git-add-dot

If you navigate to your new folder and execute the “git add” command with the dot syntax, you will notice that you only add files located in this directory.

$ cd folder

$ git add .

Using dot with git add git-add-dot-syntax

As a consequence, you might miss some of your files in your commit.

To avoid this problem, you can use the dot syntax combined with the absolute path to your project top folder.

$ git add <path>/.

Using dot with git add git-add-absolute-path

Adding all files on older Git versions

In the first chapter, we use the “–version” option in order to check our current Git version.

This step is quite important because the behaviour of the “git add” command can differ depending on the Git version used.

If you use the dot syntax with an old Git version (less than 2.x), the modified and deleted files won’t be automatically added to your commit.

Adding all files on older Git versions git-add-chart

Adding All deleted and modified files

In order to add all deleted and modified files only to your staging area, you have to use the “git add” command followed by the “-u” option.

$ git add -u

As an example, let’s say that we modified one of our files, deleted one, and added one to our working directory.

Using a simple “git status” command, we can inspect the state of our Git working directory.

Adding deleted and modified files only git-add-deleted-files

In order to add the deleted and modified files only, we are going to execute “git add” with the “-u” option.

$ git add -u .

Adding deleted and modified files only git-status

Awesome, you successfully added all your deleted and modified files to your current Git repository!

Conclusion

In this tutorial, you learned how you can easily add all your files to your Git repository using the “git add” command. You also learned that you can use specific wildcards or options in order to add only deleted or modified files.

How To Cherry Pick Git Commits

How To Cherry Pick Git Commits | When & How to use a Git Cherry Pick Commit?

If you are working with Git, you may require to add some specific changes to your current branch. For instance, if you require to include a particular commit located on another branch than your current branch,. To perform this case make use of the required git commands ie., git cherry pick. 

It is one of the most useful commands in Git and also it does not change your current Git history rather it adds commits to it. In this tutorial, we will be explaining more about Git Cherry Pick commit and how you can use the Git cherry-pick command for including specific changes to your current branch.

Git Cherry-pick

Git cherry-picking refers to applying some commit from one branch into another branch. If you did any error and performed a change into the wrong branch, then you shouldn’t merge the whole branch. You can revert the commit and apply it to another branch.

git cherry pick commit

The principal objective of a cherry-pick is to apply the changes proposed by some current commit. Cherry-pick is a helpful tool, but always it is not a good option. It is in contrast with different ways such as merge and rebase command.

Do Refer: How To Clear Git Cache

How to use git cherry-pick?

If you want to allow the “cherry-pick” only the commits you want from another branch then Git’s cherry-pick command is useful for you. The following steps are very important to understand how to use git cheery pick:

  • Pull down the branch locally. Use your git GUI or pull it down on the command line, whatever you’d like.
  • Get back into the branch you’re merging into. You’ll likely do this by running git checkout master.
  • Find the commits you want to pull into your branch. Go to either the git log or the GitHub UI and grab the unique commit hashes for each of the commits that you want.
  • “Cherry pick” the commits you want into this branch. Run this command: git cherry-pick super-long-hash-here. That will pull just this commit into your current branch.
  • Push up this branch like normal. git push origin master

How do I cherry pick a commit in Git?

In Git, the cherry pick command drives changes from a target commit and puts them on the HEAD of the currently checked out branch.

From here, you can either continue working with these changes in your working directory or you can directly commit the changes onto the new branch.

how do i cherry pick a commit in Git

How to Cherry Pick a Commit?

Cherry-pick using Git commit hash

The easiest way to cherry-pick a commit is to use the “cherry-pick” command with the commit hash.

$ git cherry-pick <hash>

In order to cherry-pick changes, you will need to identify your commit hashes.

In order to see the commit hashes for your current branch, simply run the “git log” command with the “–oneline” option in order to make it more readable.

$ git log --oneline

45ab1a8 (HEAD -> branch2) added gitignore
808b598 (branch) Initial commit

By default, the log command will display the commits from the history beginning until the top of your current branch.

As a consequence, you may not see commits that are not related to your current branch timeline.

If you want to see commits related to a specific branch, specify the branch name when running the “git log” command.

$ git log --oneline master

93ae442 (master) committed changes
44ee0d4 added gitignore
808b598 (branch) Initial commit

As you can see, one additional commit was displayed: you can now use this hash in order to cherry-pick your commit.

$ git cherry-pick 93ae442 

[master 299a73d] added file
 Date: Wed Nov 20 16:04:52 2019 -0500
 1 file changed, 1 insertion(+)
 create mode 100644 file.txt

Great!

You have successfully cherry-picked your commit.

Cherry-pick from another branch

In order to pick commits from another branch, you need to list commits that were performed on this other branch using the “git log” command.

$ git log --oneline <branch>

Let’s say for example that I want to cherry-pick a commit from the feature branch.

$ git log --oneline feature

93ae442 (master) Feature 1
44ee0d4 Feature 2
808b598 (branch) Initial commit

Now, you can go to the branch where you want the commit to be cherry-picked, let’s call it “master” in this case.

$ git checkout master

$ git cherry-pick 93ae442 

[master 299a73d] added file
 Date: Wed Nov 20 16:04:52 2019 -0500
 1 file changed, 1 insertion(+)
 create mode 100644 file.txt

Great!

You successfully cherry-picked commits from another branch into your main branch.

Cherry-pick multiple Git commits

In some cases, you may want to cherry-pick multiple commits at once.

Luckily for you, this option is available since Git 1.7.2.

Since Git 1.7.2, you can cherry-pick a range of commits by using the dot notation.

$ git cherry-pick A..B

Note that using this command, commit A will NOT be included in the cherry-pick.

In order to include commit A, you can use this syntax

$ git cherry-pick A^..B

For example, back to the “master” branch, let’s try to cherry-pick two commits into the feature branch.

$ git checkout master

$ git log --oneline feature
481981f (feature) file 4
6653c90 file3

$ git cherry-pick 6653c90^..481981f

[master 04fbbcf] file3
 Date: Wed Nov 20 16:20:23 2019 -0500
 1 file changed, 1 insertion(+)
 create mode 100644 file3
[master f3ecc5a] file 4
 Date: Wed Nov 20 16:20:36 2019 -0500
 1 file changed, 1 insertion(+)
 create mode 100644 file4

Note that the commits need to be placed into the correct order: commit A needs to be older than commit B otherwise the command will fail silently.

Cherry-pick with original commit reference

In some cases, you may want to keep a reference to the original commit when performing a cherry-pick.

When you are performing a regular cherry-pick, you will get a new commit hash but the commit message will be the same.

However, there is a way to append the origin of a cherry-pick to the commit message: by using the cherry-pick with the “-x” option.

$ git cherry-pick -x <commit>

For example, let’s say that I cherry-picked one commit from the master branch into my “branch2” branch.

$ git cherry-pick -x ed5d4c4

Now when inspecting the commit list, you can pay attention to the commit name.

$ git log

commit de05030c3c03def40c8fa8f23e5283a7b2eaab6a (HEAD -> master)
Author: Antoine <test@gmail.com>
Date:   Wed Nov 20 16:06:10 2019 -0500

    added file 2

    (cherry picked from commit ed5d4c45dda6a6671df7d8bfc63e293ef1de23fa)

As you can see, the commit has the original commit message but it also has an informational message from the original commit

$ (cherry picked from commit <hash>)

This option can be quite handy when you want to track cherry picks done on the branch.

If you don’t specify the “-x”, you won’t be able to tell if the commit was cherry-picked in the past.

Change commit message when cherry-picking

Cherry-picking commits is very useful in order to reuse some existing work.

However, in some branches, the commit may be useful for different reasons.

As a consequence, you may want to change the commit message when cherry-picking.

To change the commit message when cherry-picking, use “git cherry-pick” with the “-e” option.

$ git cherry-pick -e <hash>

As illustrated in this example, your default editor will open and it will let you change the commit message.

Change commit message when cherry-picking own-message

When you are satisfied with the edits, save your file and your commit message should be saved successfully.

[master 1aac0e2] file5
 Date: Wed Nov 20 16:25:17 2019 -0500
 1 file changed, 1 insertion(+)
 create mode 100644 file5

Resolving cherry-pick conflicts

In some cases, you may run into cherry-pick conflicts when trying to cherry-pick your commits with the current branch.

$ git cherry-pick 93ae442

error: could not apply 93ae442... committed changes
hint: after resolving the conflicts, mark the corrected paths
hint: with 'git add <paths>' or 'git rm <paths>'
hint: and commit the result with 'git commit'

This error is happening because Git is trying to merge the content of the cherry-picked commit with your current branch.

However, as in a merge operation, the content merging can fail and you will have to solve the conflicts by yourself.

In order to fix the issues, first, take a look at the status of your working directory and staging area.

$ git status

On branch branch2

You are currently cherry-picking commit 93ae442.
  (fix conflicts and run "git cherry-pick --continue")
  (use "git cherry-pick --abort" to cancel the cherry-pick operation)

Changes to be committed:

        new file:   index.js
        new file:   script.js

Unmerged paths:
  (use "git add <file>..." to mark resolution)

        both modified:   .gitignore

As you can see, the status command states that “you are currently cherry-picking commit 93ae442“.

The files to be solved are located in the “unmerged paths” section. In order to solve the cherry-pick conflict, edit the file and modify the file until you are satisfied with the modifications.

$ nano .gitignore

(Previous content)

<<<<<<< HEAD
=======
*.conf
>>>>>>> 93ae442... committed changes

(After conflict modification)

*.conf

When conflicts are solved, add the files to your staging area and continue the cherry-pick process.

$ git add .

$ git cherry-pick --continue

The last command will open your current editor in order to add a message to your current operation.

Resolving cherry-pick conflicts continue

When you are done, save your changes and your changes should be merged.

[branch2 bd8763f] Fixed conflicts on cherry-pick
 Date: Wed Nov 20 12:56:50 2019 -0500
 3 files changed, 1 insertion(+)
 create mode 100644 index.js
 create mode 100644 script.js

Great! You successfully resolved cherry pick conflicts on your current branch.

Conclusion

In this tutorial, you learned more about the git cherry-pick command and how it can be used in many ways to merge specific commits into your current working branch.

How To Git Commit With Message

How To Git Commit With Message | Best Practices & Rules To Write Good Commit Messages in Git

Using Git as a version control system for your projects is very helpful for developers. After performing any changes, you would probably need to add your files to the index and commit them to be saved. While working with Git, it will be always a good practice to create Git commits with a message.

Git commit messages are important to express and distribute with others what you did. Also, it can be helpful when working to hotfix issues appearing on your master branches. In this short tutorial, We will be discussing more on how easily one can create Git commits with messages along with best practices of Git commit messages, other Git Commands used to commit messages to learn and write good ones when required.

What is a commit message?

The usage of the commit command is for saving changes to a local repository after staging in Git. But, before you can save changes in Git, you have to tell Git which changes you want to save as you might have made tons of edits. An excellent way to do that is by adding a commit message to recognize your changes.

Git Commit With Message

The easiest way to create a Git commit with a message is to execute “git commit” with the “-m” option followed by your commit message.

$ git commit -m "Describe your commit here"

When using the Git CLI, note that you should restrict your commit message in order for it not to be wrapped.

Usually, a good practice is to keep Git commit messages under 50 characters or less.

If you want to append a description to your Git commit, you will have to use another method.

Also Check: How To Amend Git Commit Message 

Git Commit With Description

In some cases, you may want to create a Git commit with a larger description.

Furthermore, you want to make your Git commit message fit the character limit on Git.

To create a Git commit message with a large description, you have to execute the “git commit” command without any options.

On Linux or in the Git bash, it will open an editor for you to write your Git commit message.

$ git commit

When leaving the editor and creating your Git commit message, you will be able to see that the short message was taken into account to create the commit.

Git Commit With Description git-commit-2

Similarly, if you try to inspect your Git history, you will be able to see that only the short message is visible to other users.

$ git log --oneline --graph

Git Commit With Description changes
Now that you know the basics of creating Git commit messages, we will see what rules you can use in order to write proper commit messages.

Writing Good Git Commit Messages

Writing good commit messages is crucial to any workflow. Git commits provide insights on the performed work.

As a result, if they are not written properly, you have the risk of not identifying clearly what you have worked on, or what others have worked on.

This can lead to a very messy process where you are not able to perform code integration or reverse-engineer what you did in the past.

Best Practices of Git Commit Messages

Best Practices of Git Commit Messages

Five Rules To Write Great Git Commit Message

Here is a small list of rules that you can follow to write good Git commit messages:

1 – Keep your Git commit messages short and informative

When you are working on a task, you should be able to clearly identify what you are working on.

There is no such task as “creating a website” or “refactoring the entire codebase”.

# Bad habit

$ Created pages for the website

# Good habit

$ Created the sign-up form front-end and added controls

$ Added the Login button to the Login page

Instead, if you divided your big tasks from the beginning, you should have a small set of features that you can work on.

Your Git commit message should reflect the properly divided work you are currently performing.

2 – Git commit messages should reflect your Git flow

When working with Git, choosing a Git flow is essential to ensure that integrations are performed without any regression or additional bugs.

If you are not sure about Git Flow, Atlassian wrote a very useful guide about it : you should read it and choose a Git flow if not done already.

Now that your Git flow is chosen, you can reflect it in your Git commit messages.

For example, if you are working on a feature branch, you can easily write a prefix or a suffix describing the branch you are working on.

$ (on <branch>) Fixed the UI bug when creating a new user

$ Fixed the UI bug when creating a new user (on <branch>)

Note: Whenever you are trying to inspect changes done in the past, you will be able to easily identify all the branches associated with a feature.

3 – You are not working alone

Most of the time, you are not working alone on your project: you are working with other developers.

As an outcome, writing good Git commit messages is also a sign that you care about other developers on your team.

When other developers will pull your changes, they will most likely try to understand what you have done.

It is also very likely that your modifications had some kind of impact on other parts of the code that you are not directly aware of.

Being descriptive is the best way to ease the future work that they will have to do.

It might not make a big difference on one or two commits, but the impact is huge when done over several hundred commits.

# Bad habit

$ Fixed bug on code

# Good habit

$ Fixed the NullPointerException when trying to create a user from login

4 – Use good spelling and syntax for your Git commits

This is a very obvious step but you should try to keep good spelling a proper grammar when writing Git commit messages.

Also, the syntax should be adapted to the Git commit message: avoid exclamation marks and words that add nothing descriptive or useful to the content of your Git message.

# Bad habit

$ Finally fixed the UI page! 😊

# Good habit

$ Fixed the UI page by adding an try-catch clause

Usually, Git commit messages should stay neutral and they should only try to convey the intent of the commit.

5 – Use verbs that fit the modifications done

When creating Git commit messages, one of the hardest parts is coming up with verbs that describe the actions performed in the commit.

Did you fix a bug? Did you refactor a class? Did you delete some methods?

# Bad habit

$ Wrote some new code for the feature

# Good habit

$ Added unit-tests to cover the user creation workflow

Choosing the best verbs is actually crucial: there is an actual difference between fixing a bug and hot-fixing a bug for example.

One can be done on one of your feature branches while the other implies that you have performed a modification directly on one of your production branches.

Conclusion

In this tutorial, you learned how you can write good Git commits with messages.

You saw that it is possible to keep Git commit messages while adding a longer description to your commit.

If you are interested in Git or in Software Engineering in general, we have a complete section dedicated to it on the website, so make sure to check it out!

How To Generate Git SSH Keys

How To Generate Git SSH Keys | Process of Git Generate SSH Key on Windows, Linux, Mac

In case you are a great expert in working with Git, then you would know that how necessary is to set up SSH authentication. Are you excited to learn how to generate Git SSH key and SSH authentication? Then, this tutorial is the best option for you.

From here, you will understand that SSH authentication is one of two ways of logging into your Git remote repository and pushing modifications to it. In this tutorial, we are explaining more about how you can generate SSH keys for Git on Linux, or on Windows, or on Mac. Along with that, you should have some knowledge of Git Commands to check the Git installation version using the command line.

Note: If you are using Github, follow this tutorial to setup SSH keys on Github

What is an SSH KEY?

The definition of an SSH key is an access credential for the SSH (secure shell) network protocol. For remote communication between machines on an unsecured open network, we use this authenticated and encrypted secure network protocol. Also, SSH is utilized for remote file transfer, network management, and remote operating system access. The SSH acronym is also utilized to specify a set of tools used to communicate with the SSH protocol.

How to Create an SSH Key?

SSH keys are created using a key generation tool. The generation of SSH keys can be through a public key cryptographic algorithm, the most common being RSA or DSA. At a very high-level SSH keys are created via a mathematical formula that uses 2 prime numbers and a random seed variable to output the public and private keys. This is a one-way formula that assures the public key can be obtained from the private key but the private key cannot be obtained from the public key.

Checking PC’s SSH Keys

You can check your PC’s SSH Keys by following the command below.

ls -al ~/.ssh

By typing the above command, you can see your SSH keys easily. The filename of the public key is one of the following by default:

id_ecdsa.pub
id_ed25519.pub
id_rsa.pub

Generate a new SSH key

If you don’t have an SSH key, first, you should create it. Later, please follow the step-by-step guide on how to generate a new SSH key.

Type the command below, using your GitHub’s account email:

ssh-keygen -t rsa -b 4096 -C "[your github's email]"

After running this command, you will be offered to set the SSH key path, but we advise you to use its default value by pressing the “Enter” button.

Enter a file in which to save the key (/Users/you/.ssh/id_rsa): [Press enter]

After that, it will allow you to insert a passphrase to protect your SSH key.

> Enter passphrase (empty for no passphrase): [Type a passphrase]
> Enter same passphrase again: [Type passphrase again]

Read More on Git: 

How to Generate SSH keys for Git authorization

This tutorial is all about generating SSK Keys on various platforms like Windows, Mac, Linux, etc. If you poor at this concept then check out how to do it by following the steps given here:

Generate SSH Keys on Linux

In order to generate SSH keys for your Git repository, use the “ssh-keygen” command and specify the encryption algorithm that you want to use.

$ ssh-keygen -t rsa -b 4096 -C "email@example.com"

Note that it is recommended to generate your SSH keys in the “.ssh” directory of your home directory.

When using the ssh-keygen utility, you will be prompted with multiple questions.

First, you will be asked to provide the filename for your key as well as the passphrase.

For the filename, you usually want to leave the default options and simply press Enter.

For the passphrase, we won’t bother choosing a passphrase for this tutorial.

Even if it includes an extra layer of security for your Git repository, you will be prompted with the passphrase every time that you want to perform an operation on the repository.

Generate SSH Keys on Linux ssh-keygen

The ssh-keygen utility created two files for you :

  • id_rsa: this is the private key of your SSH key pair, you should not share this key with anybody.
  • id_rsa.pub: this is the public key of your SSH key pair, this is the key that you will copy to your server in order to connect to it seamlessly.

Generate Git SSH Keys on Mac

Just take a look at the below provided five main steps and follow them carefully to generate SSH keys for git:

  1. Start the terminal
  2. Navigate to your home directory by typing: cd ~/
  3. Now, perform the following command: ssh-keygen -t rsa (when prompted, enter a password, the key name can stay the same)
  4. Open the file you’ve just created ~/.ssh/id_rsa.pub with your favorite text editor, and copy contents to your Git repository’s keys field (GitHub, beanstalk, or any other repository provider), under your account.
  5. Make sure that you don’t copy any whitespace while copying the public key’s content (id_rsa.pub).

Generate SSH keys for Git on Windows

In order to generate SSH keys for Git on Windows, you have to enable the OpenSSH commands using the “Add-WindowsCapability” command.

$ Add-WindowsCapability -Online -Name OpenSSH.Client*

Path          :
Online        : True
RestartNeeded : False

Note: You have to be an administrator to enable OpenSSH on your computer.

Now that OpenSSH is enabled and configured on Windows, simply use the “ssh-keygen” command in order to generate your SSH keys.

$ ssh-keygen -t rsa -b 4096 -C "email@example.com"

By default, you will be prompted to provide a public key filename as well as a passphrase.

You can leave those options empty: by default, your key-pair will be named “id_rsa” (or “id_rsa.pub” for the public key).

When it comes to the passphrase, it provides more security to add one but you will be asked to provide it on every SSH authentication.

Generate SSH keys for Git on Windows rsa-windows

As you can see, your SSH keys for Git are located in the “.ssh” directory of your user home.

The ssh-keygen utility created two files for you :

  • id_rsa: this is the private key of your SSH key pair, you should not share this key with anybody.
  • id_rsa.pub: this is the public key of your SSH key pair, this is the key that you will copy to your server in order to connect to it seamlessly.

Setup SSH authentication on Git

Now that your SSH keys are generated for Git, it is time to add them to your remote Git repository in order to push changes.

In order to setup SSH authentication on the server, you will have to copy the content of the public key to the “authorized_keys” file of the server.

Copy SSH keys to your Git server

On the client, use the “cat” command in order to see the content of the public key.

$ cat ~/.ssh/id_rsa.pub

Copy SSH keys to your Git server id-rsa

Copy the output of your cat command, and paste it into the “authorized_keys” file of your server (or remote repository).

$ sudo vi /home/git/.ssh/authorized_keys

Copy SSH keys to your Git server server

Alternatively, if you don’t want to copy and paste the content of your public key, you can use the “ssh-copy-id” command.

This command will simply take the content of your “.ssh” directory and add the relevant public keys to the “authorized_keys” file of the server.

$ ssh-copy-id <user>@<remote>

Push Changes to Git through SSH

Now that your keys are correctly configured for Git, you should be able to pull and push modifications to your Git repository.

Head over to the directory where your project files are stored.

$ cd /home/myproject

If you don’t have a Git repository, initialize one using the “git init” command.

$ git init

Initialized empty Git repository in /home/user/myproject/.git/

If there is already a “.git” file in your directory, it means that there is already a repository initialized.

Note: To get the content from your existing Git repository, use the “git clone” command.

Now that your Git repository is correctly configured, add the remote repository using the “git remote add” command.

$ git remote add origin git@<server_ip>:<path_to_git_repository>

On the server, if the “project.git” file (i.e the repository root) is located directly on the git user home directory, you would write

$ git remote add origin git@8.8.8.8:project.git

After adding your remote, make sure that your modifications are effective by running the “git remote -v” command.

$ git remote -v

origin   git@8.8.8.8:project.git (fetch)
origin   git@8.8.8.8:project.git (push)

Great!

Let’s now try to add some files in order to test if files can be pushed to your remote repository.

Create a README file using the “touch” command.

$ touch README

Add the files using the “git add” command and commit them using the “git commit” command.

$ git add .

$ git commit -m "This is the first commit of this repository"

Finally, push your modifications: the push operation should not require any password using the SSH method.

$ git push

Now, you have correctly configured SSH key-based authentication for your Git repository.

Conclusion

In this tutorial, you learned how you can generate SSH keys for Git easily using the ssh-keygen utility.

You learned that the same utility is used on Linux and on Windows. The directories used in order to store the keys are also the same.

How To Delete Local and Remote Tags on Git

How To Delete Local and Remote Tags on Git | Git Delete Tag for local & remote

Are you curious to learn how to delete local & remote tags on Git? Firstly, you should gain some knowledge about tags and git tags together with Git Commands. Generally, tags are utilized to tag particular commits that may be more significant than others. Also, you can use tags for bookmarking specific events like releases, bug fixes or simply to add an informative and descriptive note to a commit.

For instance, tags are often associated with genuine product releases on GitHub. But in some situations, you may require to delete git tags locally or remotely with ease. Now, it’s time to learn completely about the process of deleting Local and Remote Tags on Git. Use these available links and learn the concept that you are eagerly waiting for.

Describing Git Tags

Git tags support tagging particular points in the history of the repository and answer to them later. Once you create a tag, it won’t have a commit history. Actually, you can observe two types of tags supported by git. They are Annotated and Lightweight Tags. The major difference between them is the amount of metadata they store. One more difference is that annotated tags are public, and lightweight tags are private.

Now, you get some idea about git tags. So, take a look at the below explained delete local and remote tags in Git.

Delete a Local Git Tag

To delete a local Git tag, use the “git tag” command with the “-d” option.

$ git tag -d <tag_name>

For example, if you wanted to delete a local tag named “v1.0” on your commit list, you would run

$ git tag -d v1.0
Deleted tag 'v1.0' (was 808b598)

If you try to delete a Git tag that does not exist, you will simply be notified that the tag does not exist.

$ git tag -d v2.0
error: tag 'v2.0' not found.

If you want to make sure that tags were correctly deleted, simply list your existing tags using the tag command and the “-l” option.

$ git tag -l
<empty>

Delete a Remote Git Tag

To delete a remote Git tag, use the “git push” command with the “–delete” option and specify the tag name.

$ git push --delete origin tagname

Back to the previous example, if you want to delete the remote Git tag named “v1.0”, you would run

$ git push --delete origin v1.0

To https://github.com/SCHKN/repo.git
 - [deleted]         v1.0

To delete a remote Git tag, you can also use the “git push” command and specify the tag name using the ref’s syntax.

$ git push origin :refs/tags/<tag>

Back to the example, in order to delete a tag named “v1.0”, you would run

$ git push origin :refs/tags/v1.0

To https://github.com/SCHKN/repo.git
 - [deleted]         v1.0
Why should we specify the “refs/tags” instead of just specifying the tagname?

In some cases, your tag may have the same name as your branch.

If you tried to delete your Git tag without specifying the “refs/tags” you would get the following error

$ git push origin :v1.0

error: dst refspec v1.0 matches more than one.
error: failed to push some refs to '<repository>'

As a consequence, you need to specify that you are actually trying to delete a Git tag and not a Git repository.

Conclusion

In this tutorial, you have learned how you can easily delete a local and a remote Git tag. If you are interested to learn more about Git, check out our other tutorials on the subject such as:

How To Install Prometheus with Docker on Ubuntu 18.04

How To Install Prometheus with Docker on Ubuntu 18.04

Guys do you know what is Prometheus & Docker? If not, then stay tuned to this guide. As it comes with detailed information about both along with the How To Install Prometheus with Docker on Ubuntu 18.04

Prometheus is an open-source monitoring system and time series database used in DevOps for real-time monitoring founded in 2012 at SoundCloud. Whereas, Docker provides a space for you to encapsulate server processes with Linux containers (or other encapsulation technologies) thus why they are more efficiently managed and isolated from each other.

If you hold the professions like system administrator or a site reliability engineer, then you are apparently seeking to set up reliable monitoring architectures. One of the techniques to accomplish it is to set up Prometheus in a Docker container.

By following this approach you can test it easily on your local system and make sure that it will perform the same when deploying it on a remote server. The tutorial that we have come up with is to install Prometheus with Docker in addition to setting up a basic configuration for Prometheus.

Moreover, we are also explaining how to install the Node Exporter to meet metrics from your local Linux host.

Prerequisites

In order to install Prometheus on Docker, you will need to have sudo rights on your host.

If you are not sure about it, run the following command

$ sudo -v

Installing Docker on Ubuntu

Before installing Prometheus on Docker, it is important that Docker is already correctly installed and configured on your instance.

If you need a complete Docker installation for Ubuntu, there is a guide on devconnected about it.

Before moving to the next section, make sure that you have the latest version of Docker running.

$ docker --version
Docker version 19.03.1, build 74b1e89

Now that your Docker is ready, let’s install the Prometheus container.

Before that, you can also check out our other docker installation tutorials from the below quick links:

Installing Prometheus on Docker

The official Prometheus image for Docker is named: prom/Prometheus.

The “prom” community organization is also editing Docker images for all the components of the Prometheus stack: alert manager, node exporter, MySQL exporter, or the Pushgateway.

The Prometheus Docker image is going to install the Prometheus server. It is the one responsible for aggregating and storing time-series metrics.

The configuration files and the data directories are going to be stored on the local host filesystem.

As a consequence, those folders will be mapped into the Docker container to ensure data persistence. It is also easier to modify files on the local filesystem rather than in a container.

a – Prepare Prometheus for Docker

Likewise to the way we have installed Prometheus and Grafana on Linux, create a user for Prometheus on your system if not already existing.

$ sudo useradd -rs /bin/false prometheus

In your etc directory, create a new folder and a new configuration file for Prometheus.

$ sudo mkdir /etc/prometheus
$ cd /etc/prometheus/ && sudo touch prometheus.yml

Similarly, create a data folder for Prometheus.

$ sudo mkdir -p /data/prometheus

Make sure that the permissions are correctly set for the configuration file and for the data folder.

$ sudo chown prometheus:prometheus /data/prometheus /etc/prometheus/*

This way, only the Prometheus and root can modify this file. This provides greater security to our Prometheus setup.

b – Configure Prometheus for Docker

This step consists of filling up the configuration file that we have created recently. Head over to your configuration folder, and start editing the file.

$ vi /etc/prometheus/prometheus.yml

Paste the following configuration in your file.

# A scrape configuration scraping a Node Exporter and the Prometheus server
# itself.
scrape_configs:
  # Scrape Prometheus itself every 10 seconds.
  - job_name: 'prometheus'
    scrape_interval: 10s
    target_groups:
      - targets: ['localhost:9090']

For now, Prometheus is only going to monitor itself.

Later on, we are going to add the Node Exporter that will be responsible for gathering metrics from our local Linux system.

Now that Prometheus is configured for Docker, we are going to run the Prometheus container.

c – Running the Prometheus Docker container

We are going to use the image from the Prometheus image from the prom repository.

As a reminder, to start a Docker container, you have to use the docker container run command.

Make sure that nothing is running on port 9090 already.

$ sudo netstat -tulpn | grep 9090

As we configured our folders to be accessible by the Prometheus user, you will have to determine the ID for this user.

To find the Prometheus user ID, head over the passwd file and run

cat /etc/passwd | grep prometheus
prometheus:x:996:996:/home/prometheus:/bin/false

As you can see, the Prometheus user ID is 996. This is what we are going to use to create our Prometheus container.

Note: The user ID might be different on your instance. If it is the case, modify the –user parameter in the command below.

To start Prometheus on Docker, run the following command.

docker run -d -p 9090:9090 --user 996:996 \ 
--net=host \
-v /etc/prometheus/prometheus.yml \ 
-v /data/prometheus \ 
prom/prometheus \ 
--config.file="/etc/prometheus/prometheus.yml" \ 
--storage.tsdb.path="/data/prometheus"

Here is an explanation of all the parameters provided in this command.

  • -d: stands for detached mode. The container will run in the background. You can have a shell to run commands in the container, but quitting it won’t stop the container.
  • -p: stands for the port. As containers are running in their own environments, they also have their own virtual networks. As a consequence, you have to bind your local port to the “virtual port” of Docker (here 9090)
  • -v: stands for volume. This is related to “volume mapping” which consists of mapping directories or files on your local system to directories in the container.
  • –config.file: the configuration file to be used by the Prometheus Docker container.
  • –storage.tsdb.path: the location where Prometheus is going to store data (i.e the time series stored).
  • –net: we want the Prometheus Docker container to share to the same network as the host. This way, we can configure exporters in individual containers and expose them to the Prometheus Docker container.

To make sure that everything is running properly, list the running containers on your instance.

$ docker container ls -a
CONTAINER ID        IMAGE               COMMAND                         CREATED              STATUS              PORTS                        NAMES
gfre156415ea78      prom/prometheus     "/bin/prometheus --con.."       About a minute ago   Up 
0.0.0.0:9090 ->9090/tcp      modest_hypatia

As you can see, my container is up and running.

Want an interactive shell running to access your Prometheus Docker?

docker exec -it <container_id> /bin/sh

If your container is not running, it is probably marked as “Exiting” in the status column. If this is the case, here is a command to inspect what happened during the initialization of the container.

$ docker container logs -f --since 10m <container_id>
8/29/2019 @ 11:11:00 - Port already in use : 9090

This command is very handy when something wrong happens on your container.

However, if your container is up, you should have access to the Prometheus Web UI, located by default at.

prometheus-web-u

As Prometheus is already scrapping itself, you should see it as a target in the “Status > Targets” panel.

targets-prom-2

Congratulations, you successfully installed Prometheus on Docker.

However, Prometheus alone isn’t very useful. As a consequence, we are going to install the Node exporter: an exporter responsible for gathering and aggregating metrics related to Linux system performance.

Installing the Node Exporter on Docker

The Node exporter also comes with its own Docker image.

Similar to what we did with the Prometheus Docker image, let’s create a user for the Node Exporter.

a – Prepare the Node Exporter for Docker

$ $ sudo useradd -rs /bin/false node_exporter

Again, to launch the container properly, you will have to get the Node Exporter user ID. To do it, run

$ cat /etc/passwd | grep node_exporter
prometheus:x:995:995:/home/node_exporter:/bin/false

b – Running the Node Exporter Docker image

The Node Exporter does not have a dedicated configuration file.

Instead, it relies on the flag provided to the command line to enable or disable collectors. By default, a lot of them are enabled by default (you can find the list here) but some of them are not.

To enable them, you will have to provide a –collector.<name> flag to the command line.

Before running the node exporter image, make sure that nothing is running on port 9100 (the default Node Exporter port).

$ sudo netstat -tulpn | grep 9100

You will have to map certain directories on your filesystem to the Node Exporter image.

Indeed, if you don’t map the correct folders, you are going to monitor the filesystem of your Docker image, which is not what we want in this case.

To run the Node Exporter image, run the following command

docker run -d -p 9100:9100 --user 995:995 \
-v "/:/hostfs" \
--net="host" \
prom/node-exporter \
--path.rootfs=/hostfs

Here are the details of the flags provided to this command.

  • -d: detached mode, will run the node exporter even if we are not directly interacting with it;
  • -p: as the node exporter runs on port 9100, we are going to expose this port to Prometheus;
  • –user: the node exporter user ID, for security purposes.
  • -v: the host filesystem (the machine you are monitoring) is mapped to a folder in the Docker image.
  • –net: sets the Docker image and the host to share the same network.
  • –path.rootfs: instructs the node exporter to look for the filesystem in the hostfs folder. This way, the Node exporter is not monitoring your Docker filesystem, but the mapped filesystem from your host.

c – Verify that the Node exporter is running

To verify that the Node exporter is running, make a simple curl call on your host.

$ curl http://localhost:9100/metrics

node_scrape_collector_success{collector="arp"} 1
node_scrape_collector_success{collector="bcache"} 1
node_scrape_collector_success{collector="bonding"} 1
node_scrape_collector_success{collector="conntrack"} 1
node_scrape_collector_success{collector="cpu"} 1
...

Great! It seems that the Node Exporter is running correctly. Make sure that the Node exporter is actually scrapping your host and not the Docker image.

$ curl http://localhost:9100/metrics | grep uname

node_uname_info{domainname="(none)",machine="x86_64",nodename="schkn-debian",release="4.15.0-42-generic",sysname="Linux",version="#45-Ubuntu SMP Thu Nov 15 19:32:57 UTC 2018"} 1

As you can see, the nodename is correct and the version is also correct. The Node exporter is correctly scrapping my host, and not the Docker container itself.

d – Bind Prometheus to the Node Exporter

Now that the Node Exporter and Prometheus are running separately, it is time to bind Prometheus to the Node Exporter to start storing our metrics.

Head over to your Prometheus configuration file, and append the following changes.

# A scrape configuration scraping a Node Exporter and the Prometheus server
# itself.
scrape_configs:
  # Scrape Prometheus itself every 10 seconds.
  - job_name: 'prometheus'
    scrape_interval: 10s
    target_groups:
      - targets: ['localhost:9090']

  - job_name: 'node_exporter'
    scrape_interval: 10s
    target_groups:
      - targets: ['localhost:9100']

Make sure that you create a new scrape configuration for the node exporter. This way, metrics are going to be correctly labeled and they will be easily retrievable.

There is no need to restart the Prometheus Docker container for the modifications to be applied.

To restart your Prometheus configuration, simply send a SIGHUP signal to your Prometheus process.

First, identify the PID of your Prometheus server.

$ ps aux | grep prometheus
schkn  4431  0.0  0.0  14856  1136 pts/0    S+   09:34   0:00 /bin/prometheus --config.file=...

The PID of my Prometheus process is 4431. Send a SIGHUP signal to this process for the configuration to restart.

$ sudo kill -HUP 4431

Now, your Prometheus instance should have the Node Exporter as a target. To verify it, head over to http://localhost:9090 and verify that it is the case.

node-exporter-target-docker

As you can see, the node exporter target is up and running.

Now that your system is monitored using Prometheus and the Node Exporter through Docker, let’s have a quick Grafana installation to visualize our metrics.

Installing Grafana on Docker

Installing Grafana on Docker is pretty straightforward. Here is the command to get it.

a – Getting the Grafana image

$ docker run -d -p 3000:3000 --net=host grafana/grafana

Note: Do not forget the net option, otherwise your Grafana instance is not going to find your Prometheus instance running on your host.

If your Docker image cache doesn’t have the Grafana image, it is going to retrieve it, store it, and create a Grafana docker on your host.

When the installation is done, head over to http://localhost:3000 (the default port for Grafana)

grafana-default

By default, the credentials are admin for the username and admin for the password.

By clicking on “Log In”, you are asked to change the default password. Choose a strong one, and click on “Save“.

grafana-change-pass

b – Add Prometheus as a Datasource

By default, you will be redirected to the Homepage. Click on the “Add a Datasource” option.

home

Choose a Prometheus Datasource and click on “Select

prometheus-datasource-1

Here is the configuration for your Prometheus host.

datasource-prometheus

Click on “Save and Test” and make sure that your Prometheus configuration is running properly.

save-test

c – Import the Node Exporter dashboard

As the Node exporter is quite a popular exporter, there are developers who already created dashboards for it.

As a consequence, we are going to install the Node Exporter dashboard on Prometheus.

In the left menu, click on the “Plus” icon, then “Import”.

import

In the Grafana dashboard text box, type 1860 and wait for Grafana to retrieve the dashboard information automatically.

dashboard-import

In the next window, select Prometheus as a datasource and click on “Import“.

import-2

That’s it! Your dashboard should now automatically be created.

final-dash

Going Further

As you can see, installing Prometheus on Docker is pretty simple. Because we have covered the installation process along with how to install a simple exporter and dashboard monitoring solution which is Grafana in this case.

This is a basic yet very effective setup for your monitoring architecture. If you are looking for more Docker tutorials, then go through this website completely. I hope that you learned something new today. Until then, have fun, as always.