- Published on ·
- Time to read
- 3 minute read
Git Deployment for Websites
- Authors
- Name
- Patrick Hulce
- @patrickhulce
I’ve been developing web applications for multiple clients for years now, and I’ve always been frustrated by the deployment process. Remembering FTP usernames and passwords, attempting to sync with the server, the non-existent merge assistance, and the occasional crisis of lost files, it’s just a nightmare. Or rather it was a nightmare until I started using git for my deployment. Now, I keep a clone of my sites repository on my server, setup a post-update commit hook, and I don’t even have to think about deploying anymore. Simply add, commit, push, and relax.
If you're interested in a similar setup, here's how you can get started.
How-To
Server Setup
First, ssh into the server you'd like to deploy to and create a nice space for your code to live.
ssh patrick@my-cool-ec2-server-ip
mkdir -p /var/www/my-website.git
mkdir -p /var/www/my-website
You'll notice how we created two separate directories here. That's because we're going to setup a bare repository. In most of the git repos you've worked with before, you've probably had a .git
directory within the code that you're working on. That's the raw git data, where git stores the commit history, branches, etc, while the parent directory is the actual code, your working directory. In a bare repository, the .git
directory is separated from the working directory which helps us keep the git data separate from the actual copy of the code that's deployed to the server.
Next, we'll initialize the bare repository.
cd /var/www/my-website.git
git init --bare
cat <<EOF > hooks/post-receive
#!/bin/bash
export GIT_WORK_TREE=/var/www/my-website
git checkout -f
cd $GIT_WORK_TREE && ls -alh
echo "Deployment complete!"
EOF
chmod +x hooks/post-receive
You'll notice we added a post-receive
hook to the repo. This is the script that will be triggered whenever a new commit is "deployed" (pushed). In our case, we check out the latest code into the deployment directory, and then run you can optionally run any additional deployment commands (like npm install, restart services, etc). There's a lot of flexibility here so feel free to customize it to your situation but this is a good starting point.
Client Setup
Now, we'll setup the client side. This is how we'll push our code to the server.
git remote add production ssh://patrick@my-cool-ec2-server-ip:/var/www/my-website.git
That's it! Now, you can push your code to the server.
git push production master
Profit
With this setup, deploying code is as easy as committing your changes and running git push. Say goodbye to the headaches of FTP or manual synchronization and enjoy the simplicity of git-powered deployments!