How to Configure SSH for Git and Bitbucket on a Remote Server

How to configure SSH for Git and Bitbucket on a remote server

Many developers, juniors especially, clone repositories over HTTPS and enter a username and password (or an app password) on every pull. There is a better way: SSH. You set up a key pair once and never type credentials again. Here is the complete workflow for deploying a project from Bitbucket to a fresh Linux server.

Problem: How do you set up SSH access from a server to a Bitbucket (or GitHub) repository and get the project files onto the server?

Step 1. Connect to the server

ssh username@server-ip-or-hostname

Step 2. Generate an SSH key pair

Check for an existing key first, then generate one if needed:

ls ~/.ssh/id_*.pub 2>/dev/null || echo "No key found"

ssh-keygen -t ed25519 -C "deploy@example.com"
# Press Enter to accept the default path (~/.ssh/id_ed25519)

A passphrase is optional. Without it, automated deployments can use the key; with it, a stolen key file is useless on its own.

Step 3. Add the public key to Bitbucket

Print the public key and copy it:

cat ~/.ssh/id_ed25519.pub

In Bitbucket, go to Personal settings → SSH keys → Add key, paste the key and save. For GitHub it’s Settings → SSH and GPG keys → New SSH key.

If the server only needs to read one repository, add the key as an access key of that repository instead (Repository settings → Access keys). It gives read-only access to that repository and nothing else.

Test the connection:

ssh -T git@bitbucket.org
# Expected: "logged in as username"

Step 4. Get the project onto the server

The simplest way is to clone the repository straight into the project folder. The dot at the end clones into the current folder instead of creating a subfolder:

mkdir -p /var/www/my-project && cd /var/www/my-project
git clone git@bitbucket.org:username/my-repo.git .

git clone … . requires an empty folder. If the folder already has files (for example, the hosting panel created a default index.html), initialise Git in place and fetch the branch instead:

cd /var/www/my-project
git init
git remote add origin git@bitbucket.org:username/my-repo.git
git fetch origin
git checkout -t origin/master

Step 5. Check the result

pwd             # confirm the current folder
ls -la          # list files, including hidden ones
git status      # should say "nothing to commit, working tree clean"

Files ended up in a nested folder?

If you ran git clone without the dot, Git created a subfolder named after the repository, and you get project/my-repo/files instead of project/files. Move everything, including hidden files such as .git and .htaccess, one level up:

cd /var/www/my-project
mv my-repo/* my-repo/.[!.]* . && rmdir my-repo

The .[!.]* pattern matches hidden files, which * skips. If the repository has no hidden files besides .git, the shell may complain that the pattern matched nothing; check with ls -la that everything moved.