Deploying Go Applications with Docker

Ubuntu: Deploying Go Applications with Docker

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.


Step 1: Install Docker

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


Step 2: Write a Simple Go Application

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)) }

Step 3: Create a Dockerfile

Create a file named Dockerfile in the same directory:

FROM golang:1.20-alpine WORKDIR /app COPY . . RUN go build -o server . CMD ["./server"]

Step 4: Build the Docker Image

sudo docker build -t go-server .


Step 5: Run the Container

sudo docker run -d -p 8080:8080 go-server

This maps port 8080 on the host to port 8080 inside the container.


Step 6: Test the Application

Open your browser or use curl:

curl http://your-server-ip:8080

You should see: Hello from Go + Docker!


Step 7: Manage Containers

List running containers:

sudo docker ps

Stop a container:

sudo docker stop

Remove a container:

sudo docker rm


Best Practices

  • Use multi-stage builds to reduce image size
  • Run containers as non-root users for security
  • Use Docker Compose for multi-container applications
  • Store logs outside the container for persistence
  • Regularly update base images to patch vulnerabilities

Note: HostPalace offers Docker-ready servers for Go applications, making deployment faster and more secure.