Deploying Gin App to Ubuntu VPS
Here's how to deploy a Gin app to vps once you've initated and ssh in a VPS running Ubuntu 14.04.
Installing Nginx & Dependencies
Install some libraries that most environments require.
sudo apt-get update
sudo apt-get install build-essential libssl-dev libyaml-dev libreadline-dev openssl curl git-core zlib1g-dev bison libxml2-dev libxslt1-dev libcurl4-openssl-dev libsqlite3-dev sqlite3 mysql-common mysql-client libmysqlclient-dev mysql-server python-software-properties
Enter mysql
password when install mysql.
After that, intall Nginx. The version on official apt-get repository is a little outdated, so we should install its stable version from another custom source.
sudo add-apt-repository ppa:nginx/stable
sudo apt-get -y update
sudo apt-get -y install nginx
It should automatically start when installed.
Configuring Nginx
Configure Nginx with:
sudo vi /etc/nginx/sites-enabled/default
and find the line:
server_name _;
Replace the _
with your ip or domain name. And find the location /
part. Write:
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Host $host;
proxy_pass https://127.0.0.1:3000;
}
It should direct all requests from /
to post 3000. And restart Nginx every time you change this file:
sudo service nginx restart
Setting up Go Environment
You can install Go by following the official documentation. Or here is a short version for installing the latest stable version:
sudo add-apt-repository ppa:ubuntu-lxc/lxd-stable
sudo apt-get update
sudo apt-get install golang
Finally, open the .bashrc
and add:
export GOROOT=$HOME/go
export PATH=$PATH:$GOROOT/bin
Type go version
and you should see the version.
Serve the Gin Application
Upload the project you've done, and follow the go pattern to put it in the correct directory. For example, my program should be put in:
~/go/src/github.com/adler/gin
When your development on the application is done. Make sure it listens to port 3000
as we set in the nginx configuration. Enter the directory and compile the program with:
go build -o gin main.go
Move the whole project to somewhere you want to host it:
sudo cp -r ~/go/src/github.com/adler/gin /var/www
Run the program:
cd /var/www
./gin
You should see the message that Gin is running. Open the browser and enter the public IP. Your index page should be there.
Running Server in Background
Use nohup
command to run the process and do not let it terminated by the signal sighup
sent to all processes by leaving the current process, usually by closing the terminal window.
nohup ./gin & disown
You can terminate the process by ctrl + z
when in the process. If you've closed the window, find the PID in the list.
ps -ef | grep ./gin
Replace the ./gin
with your program name. Find the PID and kill it.
kill -9 your_pid