Go (Golang) / Deploying Go Applications

Using Docker to Containerize Go Applications

In this tutorial, you'll learn how to containerize your Go applications using Docker. This involves packaging your application along with its dependencies into a Docker container.

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Covers best practices for compiling, packaging, and deploying Go applications.

1. Introduction

Goal

This tutorial aims to guide you on how to containerize your Go applications using Docker. Containerization helps to ensure that your application runs the same way regardless of the environment it's in.

What You Will Learn

By the end of this tutorial, you will be able to:

  • Write a simple Go application
  • Write a Dockerfile for your Go application
  • Build a Docker image for your Go application
  • Run your Go application in a Docker container

Prerequisites

Before we begin, ensure that you have the following installed:

  • Go (latest version)
  • Docker (latest version)

2. Step-by-Step Guide

Docker and Go

Docker allows you to package your application and its dependencies in a virtual container that can run on any Linux or Windows server. This helps to eliminate the "it works on my machine" problem when collaborating with others.

Go, also known as Golang, is a statically typed, compiled language designed at Google. Go is robust and ideal for developing scalable and efficient software.

Dockerizing a Go Application

To containerize a Go application, you need to create a Dockerfile. A Dockerfile is a text document that contains all the commands needed to build a Docker image.

Let's go through the steps of dockerizing a simple Go application.

3. Code Examples

Example 1: Write a Simple Go Application

First, let's create a simple Go application. Create a file named main.go and add the following code:

package main

import (
    "fmt"
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello, you've requested: %s\n", r.URL.Path)
    })

    http.ListenAndServe(":8080", nil)
}

This application starts a simple HTTP server that returns a message with the requested URL path.

Example 2: Dockerfile for Go Application

Now, let's create a Dockerfile for our Go application. Create a file named Dockerfile in the same directory as your main.go file and add the following:

# Use the official Golang image to create a build artifact.
FROM golang:1.16 as builder

# Copy local code to the container image.
WORKDIR /app
COPY . .

# Build the command inside the container.
RUN go build -v -o server

# Use the official lightweight Scratch image.
# https://hub.docker.com/_/scratch
FROM scratch

# Copy the binary to the production image from the builder stage.
COPY --from=builder /app/server /server

# Run the web service on container startup.
CMD ["/server"]

This Dockerfile creates a Docker image that runs our Go application.

Example 3: Build and Run the Docker Image

Build the Docker image using the following command:

docker build -t go-app .

Run the Docker image using the following command:

docker run -p 8080:8080 go-app

You can now access the application at http://localhost:8080.

4. Summary

In this tutorial, we've learned how to write a simple Go application and containerize it using Docker. We wrote a Dockerfile to create a Docker image for our application and ran the application in a Docker container.

To learn more about Docker and Go, you can check out the following resources:

5. Practice Exercises

Now, try the following exercises to deepen your understanding:

  1. Modify the Go application to return the current time at a /time endpoint.
  2. Update the Dockerfile to include the new version of the application. Build and run the Docker image.
  3. Try to access the application at http://localhost:8080/time.

Solutions:

  1. Add a new route in main.go like this:
http.HandleFunc("/time", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "The current time is: %s\n", time.Now())
})
  1. Rebuild the Docker image with docker build -t go-app . and run it with docker run -p 8080:8080 go-app.
  2. Access the application at http://localhost:8080/time to see the current time.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Countdown Timer Generator

Create customizable countdown timers for websites.

Use tool

Base64 Encoder/Decoder

Encode and decode Base64 strings.

Use tool

Random Password Generator

Create secure, complex passwords with custom length and character options.

Use tool

Date Difference Calculator

Calculate days between two dates.

Use tool

Hex to Decimal Converter

Convert between hexadecimal and decimal values.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help