Docker allows you to package Go applications into lightweight containers, making them portable and easy to deploy across different environments. This guide explains how to build and run a Go application inside Docker on Ubuntu.
sudo apt update
sudo apt install docker.io -y
Enable and start Docker:
sudo systemctl enable docker
sudo systemctl start docker
Verify installation:
docker --version
Create a file named server.go:
package main import ( "fmt" "log" "net/http" ) func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello from Go + Docker!") }) log.Fatal(http.ListenAndServe(":8080", nil)) }Create a file named Dockerfile in the same directory:
FROM golang:1.20-alpine WORKDIR /app COPY . . RUN go build -o server . CMD ["./server"]sudo docker build -t go-server .
sudo docker run -d -p 8080:8080 go-server
This maps port 8080 on the host to port 8080 inside the container.
Open your browser or use curl:
curl http://your-server-ip:8080
You should see: Hello from Go + Docker!
List running containers:
sudo docker ps
Stop a container:
sudo docker stop
Remove a container:
sudo docker rm
Note: HostPalace offers Docker-ready servers for Go applications, making deployment faster and more secure.