Simple golang build and deploy script

There are many ways to build and deploy a golang application, the best method I have found so far is to use code ship which I will cover in a future article. The simplest method is to push your code to version control on your local development environment. Then log into the production server and run a script on the server which completes the following steps:

  1. Syncs the code from version control
  2. Complies the code
  3. Stops the application via the upstart script
  4. Moves the code to the production location
  5. Starts the application via the upstart script.

If you are running a small application like sleepy.fish even on a small server like a 512mb droplet from digitalocean.com it should sync, compile and deploy in a matter or seconds which means little to no downtime for deploys.

The following assumptions are made in the script:

  • You have set-up a basic build environment
  • You are deploying your script to /opt/wwwroot/sleepy.fish/public
  • Your upstart script is placed in /etc/init and is called sleepyfish.conf*
  • Your code is hosted in github.com or bitbucket.org and you have a installed git (sudo apt-get install git)

I would normally place the script in ~/deploy.sh so its easy to log into the server and deploy the code without having to issue too many commands.

#!/bin/sh

# Delete the old code so we get a clean pull

rm -r /usr/local/src/go/src/github.com/ollietrex/sleepyfish

# Clone your code from from the repository

git clone https://github.com/ollietrex/sleepyfish/ /usr/local/src/go/src/github.com/ollietrex/sleepyfish

# Change directory

cd /usr/local/src/go/src/github.com/ollietrex/sleepyfish

# Collect the dependencies from there repositories

go get -v

# Build the application

go build

# Stop the golang service

service sleepyfish stop

# Copy the executable into the correct location

cp /usr/local/src/go/src/github.com/ollietrex/sleepyfish/sleepyfish /opt/wwwroot/sleepy.fish/public

# Copy the static directory containing any javascript and media

cp -R /usr/local/src/go/src/github.com/ollietrex/sleepyfish/static /opt/wwwroot/sleepy.fish/public

# Restart the service

service sleepyfish start

All the variables can of course be adjusted to suit your own application but it should give you a generic method to simply deploy your application. If you cant run ~/deploy.sh don’t forget to set it as executable by running:

chmod 755 ~/deploy.sh

See also