Deploying with git
21 Jan, 2023
Easily setup git to push updates to production with a simple git push production main
.
I wanted to use git to push updates to a production server and found it relatively easy to setup with just one gotcha to overcome.
Create a bare repository
ssh
to the production server and create a bare respository. It's important to set the global config defaultBranch to "main" otherwise it will default to "master". I tend to use a dedicated deploy
user and place everything in the associated home directory, so this is where I'll create a repo
directory to hold the repository.
> mkdir /home/deploy/repo
> mkdir /home/deploy/repo/<repo name>.git
> cd /home/deploy/repo/<repo name>.git
> git config --global init.defaultBranch main
> git init --bare
This has created a bare respository on the production server.
Setup a working directory
The next step is to set up the working directory where our app files will live and be served from.
Again the working directory will reside in the deploy
user's home
directory:
> mkdir /home/deploy/<repo name>
Setup a post-receive hook script
The next step is to add a post-receive
hook to tell git what to do when it has received an new update.
> vim /home/deploy/repo/<repo name>.git/hooks/post-receive
Thsi will open the vim
editor. Add the following to the new file:
#!/bin/sh
# Check the repo out into the working directory for our application
git --work-tree=/home/deploy/<repo name> --git-dir=/home/deploy/repo/<repo name>.git checkout -f main
cd /home/deploy/<repo name>
scripts/compile
In this case the last line is kicking off a script to compile the app, you can replace this with your own or delete it as necessary.
Enter ESC-x
to exit and save the file. Now ensure the post-receive
file has executable permissions:
> chomd +x /home/deploy/repo/<repo name>.git/hooks/post-receive
Push your first update
The last thing we need to do is add the production server as a remote to our local git repository. Back on out local development machine (assuming the deploy user is being used to deploy to the remote server):
> git remote add production ssh://deploy@<hostname>/home/deploy/repo/<repo name>.git
You can check this using git remote -v
.
Finally, to push to production for the first time use the command:
> git push production main
You can check the deployment worked by doing ls /home/deploy/<repo name>
on the remote server.
And that's it, all you need to git push
to production.