Golang

Launch a Golang web server using Docker

If you have a web server the simplest way to deploy is using Docker.  Golang code is compiled to a binary and does not a special environment to run.

Here is the simplest web server code to get started. Save as webserver.go

package main
import ( 
      "fmt" 
      "log" 
      "net/http" 
      "runtime"
     )
func main() { 
     http.HandleFunc("/", indexHandlerHelloWorld) 
     log.Fatal(http.ListenAndServe(":8080", nil))
}

func indexHandlerHelloWorld(w http.ResponseWriter, r *http.Request) { 
     fmt.Fprintf(w, "Hello world, I'm running search on %s with an %s CPU ", runtime.GOOS, runtime.GOARCH)
}

We can use the simplest docker image scratch and add a directive to copy the binary to the server. Save as Dockerfile.

FROM scratch
MAINTAINER Maria De Souza <maria.g.desouza@gmail.com>

ADD go-webserver go-webserver
ENTRYPOINT ["/go-webserver"]
EXPOSE 8080

We setup a start shell script to build and kick up the docker

#!/bin/bash

GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -a -o go-webserver webserver.go || exit 1
if [ "$(docker ps -q -f name=go-web-server)" ]; then
 docker stop $(docker ps -a -q --filter name=go-web-server --format="{{.ID}}")
fi
docker build -t go-web-server . || exit 1
docker run -p 8000:8080 go-web-server || exit 1

You can use the -h option to add the hostname to the webserver

Voila! Now your webserver is running. Navigate to http://localhost:8000/ to test.

 

 

 

 

 

 

 

 

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s