Deploy a website to a remote server with Git push

Three steps to configure the deployment process with a Git Hook.

François Romain
Jun 28, 2017 · 3 min read

Git is a great tool for version control, but not only. It can also simplify the deployment process, thanks to Git Hooks.


Three steps to configure the deployment process:

1. Create an empty Git repo on the server

2. Write a Git Hook to deploy the code

3. Deploy from the local computer

tl;dr

On the remote server:

On your local computer:


Prerequisite
- Connect to the server via SSH without root.
- Git is installed globally on the server and locally.


User access and permissions

Connect to the server: $ ssh <your-name>@<your-ip>

Add your user to the users group, so it has permissions to use Git: $ sudo adduser <your-name> users.

On the server, we are going to use two directories:

  • /srv/tmp/ is a temporary directory for deployment.
  • /srv/www/ contains the actual production files (this could be /var/www/html/ on an Apache server).

Create the directories and set the permissions so your user can deploy without a root access:


1. Create an empty Git repo on the server

First we need to configure an empty Git repo on the remote server to push the content of our local git repo.

Create an empty Git repo

Conventions:

  • Add a .git extension on a git repo.
  • Store git repos in srv/git/.

Set the permissions on the Git repo

We need to set the permissions on the repo so that we can modify its content without sudo (from stackoverflow).


2. Write a Git hook to deploy the code

When we push our code to the server, we want to trigger a command to deploy the code from the git repo. To do so, we use a Git post-receive hook.

Create the Git hook file

Edit the /srv/git/<your-app>.git/hooks/post-receive file content:


Here is a bash script to automate the two steps above. Upload it somewhere on your server, then call bash ./project-create.sh <your-project>.


3. Deploy from the local computer

Initialize the repo and add the server repo as a remote

Push to the server (and deploy)


Next steps:

  • Automate testing before deployment.
  • Configure a load balancer to ensure no downtime.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store