Back to Blog

Setting Up Git-Based Automatic Deployment on a Virtual Private Server (VPS)

Poster for Setting Up Git-Based Automatic Deployment on a Virtual Private Server (VPS)

When leveraging Git for version control, the conventional workflow primarily revolves around managing source code. However, Git can also be a powerful tool for seamlessly deploying applications to production environments. In this guide, we'll walk you through the process of setting up automatic deployment with Git on a Virtual Private Server (VPS), enhancing your development and deployment pipeline.


Server Configuration:


Imagine your workspace as follows:

  • Server live directory: /var/www/domain.com
  • Server repository: /var/repo/site.git

To initiate the process, let's create the repository on your VPS:


cd /var
mkdir repo && cd repo
mkdir site.git && cd site.git
git init --bare


The use of --bare signifies that this folder will exclusively handle version control, without containing the actual source files.


Git Hooks:


Git repositories include a directory called 'hooks,' housing sample files for potential actions. Three notable server hooks are 'pre-receive,' 'post-receive,' and 'update.' We'll focus on 'post-receive,' which executes after a 'push' is completed.

Navigate to the 'hooks' folder and create the 'post-receive' file:


cd hooks
cat > post-receive


Insert the following content:


#!/bin/sh
git --work-tree=/var/www/domain.com --git-dir=/var/repo/site.git checkout -f


Save with 'control-d' and set proper permissions:


chmod +x post-receive


Local Machine Configuration:


Create a local repository, configure the remote path, and add a remote called 'live':


cd /my/workspace
mkdir project && cd project
git init
git remote add live ssh://[email protected]/var/repo/site.git


Assuming your work is ready, stage and commit changes, then push to the server:


git add .
git commit -m "My project is ready"
git push live master


Beta Deployment:


If you prefer a staged deployment, create a beta directory and repository on the server. Repeat the 'post-receive' file creation, linking it to the beta directory. Set up a remote pointing to the beta repository on your local machine:


git remote add beta ssh://[email protected]/var/repo/beta.git


Now, you can push to the beta repository for testing:


git push beta master


Once satisfied, proceed to push to the live repository:


git push live master


Collaborative Deployment:


Enable collaborative decision-making by linking the beta and live repositories on the server:

cd /var/repo/beta.git
git remote add live ../site.git


Now, push from beta to live on the server:


git push live master


Congratulations! Your VPS is now configured for automatic deployment using Git, offering a streamlined and efficient development workflow.

Was this page helpful?

By continuing to use this site you consent to the use of cookies in line with our Cookies Policy.