Setting up Git Repo via SSH
Hello 👋, lets see how can we setup a git repository on a server via ssh access. We need to perform following steps to setup the repository.
Generate SSH Key
Authorize SSH Key
Add key in GIthub
Clone repository
Generate SSH Key
To get started, we need to have a SSH key. If you already have a SSH key you may skip this step.
We’ll use the ssh-keygen to generate the keypair. Use the below command to generate the keypair.
ssh-keygen -t rsa -b 4096
After executing this command the key will be generated and stored in the ~/.ssh/ directory with the name id_rsa.pub
Authorize SSH Key
Once we got the SSH key we need to add this key to our server’s authorized keys. Use below command to add the key to the authorized keys.
cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
Once the key is added to the authorized keys, we can proceed further.
Add key in Github
Use below command to print the generated key so that we can copy paste it into the Github. In Github you need to go to the repository settings and click on deploy keys and add deploy key.
You will be prompted to add title and the key, paste the key here and click Add key.
Clone Repository
We have now configured the Github, now ssh to the server and clone the repository in the required directory.
git clone [email protected]:{username}/{repository}.git
Tada 🎉, you have successfully cloned the repository using ssh key.
Already have code?
If you already have the git repository connected and you wanted to connect it with the git, you simply need to add the remote origin. Use the below command to add the origin.
git remote add origin [email protected]:{username}/{repository}.git
Once the origin is configured, setup the upstream branch with below command.
git branch --set-upstream-to=origin/main main
Now, you have configured the origin and the branch, we only need to pull the changes from the repository.
git pull
We have successfully configured the repository on our server.