Deploying a Go App on Apache
Categorizing Hacker News Posts (26 Jul 2024)
I recently decided to try my hand at creating a Go-based website with the Gin framework, and I was surprised to find there isn’t a simple way to host this app on my personal server which is running Apache.
In the past I’ve created a couple of web apps with Sinatra (in Ruby), and deploying them was relatively simple. It required just installing the Phusion Passenger packages with apt
, enabling the Passenger Apache module, and editing the apache config to include the app at a certain subdomain.
Unfortunately, it seems like nothing like this appears to exist for Go apps. One of the benefits of something like Passenger is that it automatically handles app startup (after, say, rebooting my server) and can restart the app automatically if it crashes for some reason. All nice to have, but for this small personal project I decided it doesn’t matter that much.
Instead, I decided to find a quick and dirty solution to get my website up and running. Gin comes with a simple built-in web server, which we can run from the command line.
// api.go
func main() {
router := gin.Default()
router.StaticFile("/", "./index.html")
router.GET("/stories", getTopStories)
router.Run("localhost:8080")
}
$ go run .
From here, we can simply hit Ctrl+Z
to suspend the program, then disown it and make it run in the background1:
$ disown -h
$ bg
And voila, we have our web server as a background process running forever (at least, until it crashes).
$ ps x | grep go
217490 pts/1 S+ 0:00 grep --color=auto go
3934484 ? Sl 0:37 /usr/local/go/bin/go run .
3934514 ? Sl 0:24 /tmp/go-build1016660365/b001/exe/api
Currently, our web app is only accessible from localhost:8080
, but we want to make it available to the world! To do this, we’ll use the Apache proxy module to redirect traffic from a certain public subdomain to our local Gin server.
First we just enable the module:
$ a2enmod proxy
$ a2enmod proxy_http
Next, we’ll create a new apache config for our subdomain and tell it to proxy all of our traffic to our Gin server2:
<VirtualHost *:80>
ProxyPreserveHost On
ProxyRequests Off
ServerName hn.caleb.software
ProxyPass / http://localhost:8080/
ProxyPassReverse / http://localhost:8080/
</VirtualHost>
And bam, after restarting Apache, our site is now live at hn.caleb.software!
Source: stack overflow post ↩
Source: stack overflow post ↩