Member-only story
Preparing Your Go Application for Deployment in Docker
Using Docker for Bootstrapping Go Applications
When developing web applications in Go, whether for HTTP or other types of services, deployment to different stages or environments (local development, production, etc.) is a common consideration. In this article, we’ll explore integrating the Golang stack within Docker containers, a widely adopted approach, using Docker Compose for orchestration.
Prepare Your Go Application
First, you need a fully functional Go application. Below is the code for our main.go
file along with a brief explanation:
// /src/main.go
package main
import (
"fmt"
"net/http"
"os"
)
func main() {
var PORT string
if PORT = os.Getenv("PORT"); PORT == "" {
PORT = "3001"
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello World from path: %s\n", r.URL.Path)
})
http.ListenAndServe(":"+PORT, nil)
}
This code sets up a basic HTTP server that returns “Hello World” when a request is received, and dynamically assigns a port based on environment variables.